huyby
10/13/2015 - 8:27 AM

Bash script for a quick(er) Laravel applicaton setup

Bash script for a quick(er) Laravel applicaton setup

#!/usr/bin/env bash

# Prompt for Yes/No answer
# $1 - question
# $2 - default answer (Y|N)
ask() {
    while true; do

        if [ "${2:-}" = "Y" ]; then
            prompt="Y/n"
            default=Y
        elif [ "${2:-}" = "N" ]; then
            prompt="y/N"
            default=N
        else
            prompt="y/n"
            default=
        fi
        # Prompt
        REPLY=`prompt "$1" $prompt`

        # Default?
        if [ -z "$REPLY" ]; then
            REPLY=$default
        fi

        # Check if the reply is valid
        case "$REPLY" in
            Y*|y*) return 0 ;;
            N*|n*) return 1 ;;
        esac

    done
}

# Prompt for an answer
# $1 - question
# $2 - default value (optional)
prompt() {
    QUESTION=$1

    if [ ! -z "$2" ]; then
        DEFAULT=$2
        QUESTION="$QUESTION [$DEFAULT]"
    fi

    # Ask the question - use /dev/tty in case stdin is redirected from somewhere else
    read -p "$QUESTION: " ANSWER </dev/tty

    # Default?
    if [ -z "$ANSWER" ]; then
        ANSWER=$DEFAULT
    fi
    echo $ANSWER
}

CURRENT_DIR=${PWD##*/}
if ask "Create project in current directory? (./$CURRENT_DIR)" 'Y'; then
    # Setup Laravel Project
    PROJECTNAME=$1
    composer create-project laravel/laravel --prefer-dist .

    if [ $? -eq 0 ]; then

        if [ ! -z PROJECTNAME ]; then
            echo "Setting application namespace to $PROJECTNAME"
            php artisan app:name $PROJECTNAME
        fi
        echo "Setup directory & file permissions"
        find ./storage -type d -mindepth 1 -exec chmod 777 {} \;
        chmod 777 bootstrap/cache
        echo "Done"

        if ask 'Run npm install?' 'Y'; then
            npm install
        fi
        if ask 'Open in Sublime?' 'Y'; then
            subl .
        fi
    fi
fi