Skip to content

Instantly share code, notes, and snippets.

@Jeff-Russ
Created May 20, 2016 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jeff-Russ/3da6c4772f63a98a0412c8ba8fcb3c9e to your computer and use it in GitHub Desktop.
Save Jeff-Russ/3da6c4772f63a98a0412c8ba8fcb3c9e to your computer and use it in GitHub Desktop.
`rails new <appname>` for Node.js apps
#!/bin/sh
SD=$(dirname "${BASH_SOURCE[0]}")
function echo_blue { echo "\033[34m$1\033[0m"; }
function echo_green { echo "\033[32m$1\033[0m"; }
function echo_red { echo "\033[31m$1\033[0m"; }
function echo_magenta { echo "\033[35m$1\033[0m"; }
####################### PARAMETER CHECKS ######################################
ARGC="$#"
# NO ARGUMENTS (warning: this will make app at working directory):
if [ $ARGC -eq 0 ]; then
echo_magenta "calling nodeinit without args will modify this working directory!"
echo "Are you sure you want initilize this directory as a new Node.js project?"
read -n1 -r -p "Press space to continue or anything else to quit..." key
if [ "$key" != '' ]; then
echo "\nexiting"; exit 0
fi
DIR=$(pwd);
# MORE THAN TWO ARGUMENTS (too many):
elif [ $ARGC -gt 2 ]; then
echo "too many arguments"; exit 1
# TWO OR THREE ARGUMENTS:
else
DIR="$(pwd)/$1" # (use 2rd as new directory name)
# THREE ARGUMENTS (use 3rd as description):
if [ $ARGC -eq 2 ]; then
DESC=$2
fi
fi
################## DETERMINING PROJECT VARIABLES ##############################
HAS_JSON=false
HAS_GIT=false
if [ -d "$DIR" ]; then # inspect any pre-existing content
echo_blue "found directory with matching name"
README=$(ls "$DIR" | grep -i readme) # store name of readme if found
# directory found but no package.json.
if [ -f "$DIR/package.json" ]; then HAS_JSON=true; fi
# directory found with .git. We will get
# project's owner, and repo url from git remote -v
if [ -d "$DIR/.git" ]; then HAS_GIT=true; fi
else
mkdir $DIR
fi
cd $DIR
EMAIL=$(git config user.email || "")
NAME=$(git config user.name || id -F || id -un || whoami)
if $HAS_GIT; then
echo_magenta ".git found"
SSH=`git remote -v | grep -m1 "^origin"`
[ -z "$SSH" ] || SSH=`git remote -v | grep -m1 ''`
HOST=$(sed 's/.*@\(.*\):.*/\1/' <<< "$SSH") # get b/w @ and :
OWNER=$(sed 's/.*:\(.*\)\/.*/\1/' <<< "$SSH") # get b/w : and /
PROJ=$(sed 's/.*\/\(.*\)\.git.*/\1/' <<< "$SSH") # get b/w / and .git
URL="https://$HOST/$OWNER/$PROJ"
else
PROJ=$(basename "$DIR")
if [[ "$NAME" != "${NAME/ /}" ]]; then # if UN has whitepace
# strip whitespace and make all lowercase
OWNER=$(echo "${NAME/ /}" | tr '[:upper:]' '[:lower:]')
else OWNER=$NAME
fi
URL="https://github.com/$OWNER/$PROJ"
fi
# now we have everything we need to create package.json
echo "--------------- write to package.json ------------------------"
if $HAS_JSON; then
echo_magenta "package.json found. Skipping..."
else
echo_blue "Creating package.json file with the following info:"
printf "{\n 'name': '$PROJ',\n 'version': '0.0.1',\n 'description': "
printf "'$DESC',\n 'author': '$OWNER <$EMAIL>',\n 'contributors': [{\n"
printf " 'name': '$NAME',\n 'email': '$EMAIL'\n }],\n 'main': "
printf "'app.js',\n 'repository': {\n 'type': 'git',\n 'url': "
printf "'$URL'\n },\n 'private': 'true',\n 'license': 'MIT'\n}"
cat > $DIR/package.json <<EOL
{
"name": "$PROJ",
"version": "0.0.1",
"description": "$DESC",
"author": "$OWNER <$EMAIL>",
"contributors": [{
"name": "$NAME",
"email": "$EMAIL"
}],
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "$URL"
},
"private": "true",
"license": "MIT"
}
EOL
fi
# before we install from npm we can silence some warnings.
#--------------- README.md -------------------------------#
echo $PROJ
if [ -z "$README" ]; then
echo_blue "Creating README.md"
cat > $DIR/README.md <<EOL
# $PROJ
[version 0.0.1]($URL)
$DESC
EOL
else
# if the readme is empty we'll append it to avoid error:
if [ -s "$DIR/$README" ]; then
echo "README found and not empty. Skipping..."
else
echo "README found, but empty."
# cat > $DIR/$README <<EOL
# # $PROJ
# [version 0.0.1]($URL)
# $DESC
# EOL
fi
fi
exit 0;
echo "################### INSTALLING NODE PACKAGES ###########################"
echo_red "Running npm installers in 10 seconds..."
echo_magenta "(this will only effect node_modules/ and packages.json)"
TMOUT=10
echo -n "Press 'c' and hit enter to skip just enter to proceed right away... "
read response
source <filename>
if [[ $response -eq 'c' ]]; then
echo_blue "Installing local node packages"
echo_green "npm install --save express"
echo `npm install --save express`
echo_green "npm install --save grunt"
echo `npm install --save grunt`
echo_green "npm install --save-dev coffee-script"
echo `npm install --save-dev coffee-script`
echo_green "npm install --save jade"
echo `npm install --save jade`
echo_green "npm install --save grunt-sass"
echo `npm install --save grunt-sass`
echo_green "npm install grunt-contrib-watch --save-dev"
echo `npm install grunt-contrib-watch --save-dev`
echo_green "All packages installed."
else
printf "\nSkipping package installation\n\n"
fi
#################### GENERATE WORKING FILES ###################################
echo_red "Generating project files and folder with boilerplate in 10 seconds..."
echo_magenta "(no files will be overriden)"
TMOUT=10
echo -n "Press 'c' and hit enter to skip just enter to proceed right away... "
read response
if [[ $response -eq 'c' ]]; then
echo_blue "Creating necessary directories..."
mkdir -p $DIR/models
mkdir -p $DIR/public
mkdir -p $DIR/public/css
mkdir -p $DIR/public/images
mkdir -p $DIR/public/js
mkdir -p $DIR/test
mkdir -p $DIR/views
#---------------------- .gitignore -----------------------#
if [ -f "$DIR/.gitigore" ]; then
echo_magenta ".gitignore found. Skipping..."
else
echo_blue "Creating .gitignore"
cat > $DIR/.gitignore <<EOL
# OS generated files
####################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Generated CSS output
#######################
public/stylesheets/*.css
# Package dependencies
######################
node_modules/
bower_components
EOL
fi
#---------------------- Makefile -------------------------#
if [ -f "$DIR/Makefile" ]; then
echo_red "Makefile found. Skipping..."
else
echo_blue "Creating Makefile"
cat > $DIR/Makefile <<EOL
TESTS = test/*.js
test:
@NODE_ENV=test ./node_modules/.bin/mocha \\
--require should \\
--reporter list \\
--slow 20 \\
--growl \\
\$(TESTS)
.PHONY: test
EOL
chmod u+x $DIR/Makefile
fi
#--------------- test/stub.js ----------------------------#
if [ -f "$DIR/test/stub.js" ]; then
echo_red "found test/stub.js. Skipping..."
else
echo_blue "Creating test/stub.js"
mkdir -p $DIR/test
cat > $DIR/test/stub.js <<EOL
describe('stub', function(){
describe('#test', function(){
it('should have some units tests')
})
})
EOL
fi
#--------------- public/js/application.js ----------------#
if [ -f "$DIR/public/js/application.js" ]; then
echo_red "public/js/application.js found. Skipping..."
else
echo_blue "Creating public/js/application.js"
cat > $DIR/public/js/application.js <<EOL
\$(document).ready(function() {
var socket = io.connect();
\$("#sender").bind("click", function() {
socket.emit("message", "Message Sent on " + new Date());
});
socket.on("server_message", function(data){
\$("#receiver").append("<li>" + data + "</li>");
});
});
EOL
fi
#---------------------- views/404.jade -------------------#
if [ -f "$DIR/views/404.jade" ]; then
echo_red "views/404.jade found. Skipping..."
else
echo_blue "Creating views/404.jade"
cat > $DIR/views/404.jade <<EOL
h1='Not Found'
div='Sorry, the page you are looking for does not exist.'
EOL
fi
#---------------------- views/500.jade -------------------#
if [ -f "$DIR/views/500.jade" ]; then
echo_red "views/500.jade found. Skipping..."
else
echo_blue "Creating views/500.jade"
cat > $DIR/views/500.jade <<EOL
!!! 5
html
head
title='500 Error'
body
h1='The Server Encountered and Error'
div=error
EOL
fi
#---------------------- views/index.jade -----------------#
if [ -f "$DIR/views/index.jade" ]; then
echo_red "views/index.jade found. Skipping..."
else
echo_blue "Creating views/index.jade"
cat > $DIR/views/index.jade <<EOL
extends layout
block content
div
a(id='sender')='Send a Message'
ul(id='receiver')
EOL
fi
#---------------------- views/layout.jade ----------------#
if [ -f "$DIR/views/layout.jade" ]; then
echo_red "views/layout.jade found. Skipping..."
else
echo_blue "Creating views/layout.jade"
cat > $DIR/views/layout.jade <<EOL
!!! 5
//if lt IE 7
html.no-js.ie6.oldie(lang='en')
//if IE 7
html.no-js.ie7.oldie(lang='en')
//if IE 8
html.no-js.ie8.oldie(lang='en')
//[if gt IE 8]><!
html.no-js(lang='en')
//<![end if]
head
meta(charset='utf-8')
meta(http-equiv='X-UA-Compatible', content='IE=edge,chrome=1')
title=title
meta(name='description', content=description)
meta(name='author', content=author)
meta(name='viewport', content='width=device-width, initial-scale=1')
link(rel='stylesheet', href='/css/style.css')
//-script(src='js/libs/modernizr-2.0.6.min.js')
body
block header
block content
block footer
footer
script(src='//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js')
script
window.jQuery || document.write('<script src='js/libs/jquery-1.7.1.min.js'><\\\/script>')
//-script(defer, src='js/plugins.js')
script(defer, src='/js/script.js')
script(defer, src='/socket.io/socket.io.js')
script
var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview'],['_trackPageLoadTime']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
//if lt IE 7
script(defer, src='//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js')
script(defer)
window.attachEvent('onload',function(){CFInstall.check({mode:'overlay'})})
EOL
fi
# cp $SD/nodeinit-templates/app/server.js ./server.js
# cp $SD/nodeinit-templates/app/config.json ./config.json
else
printf "\nCanceling actions and skipping to end\n\n"
fi
echo_blue "Setting up dependencies from NPM..."
npm install
echo_blue "SUCCESS!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment