Skip to content

Instantly share code, notes, and snippets.

@k33g
Forked from francoisromain/project-create.sh
Last active November 28, 2018 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k33g/685529b4df577d94261b7d1d48a876cd to your computer and use it in GitHub Desktop.
Save k33g/685529b4df577d94261b7d1d48a876cd to your computer and use it in GitHub Desktop.
A bash script to create a Git post-receive hook to deploy after a Git push
#!/bin/sh
# Call this file with `bash ./project-create.sh project-name [service-name]`
# project-name is mandatory
# service-name is optional
# This will creates 3 directories and a git `post-receive` hook.
# - $GIT: a git repo
# - $TMP: a temporary directory for deployment
# - $WWW: a directory for the actual production files
# When you push your code to the git repo,
# the `post-receive` hook will deploy the code
# in the $TMP directory, then copy it to $WWW.
# Global directories (require Git user access)
DIR_GIT=/srv/git/
DIR_TMP=/srv/tmp/
DIR_WWW=/srv/www/
dir_create() {
sudo mkdir -p $1
cd $1
# Define group recursively to "users", on the directories
sudo chgrp -R users .
# Define permissions recursively, on the sub-directories
# g = group, + add rights, r = read, w = write, X = directories only
# . = curent directory as a reference
sudo chmod -R g+rwX .
}
if [ $# -eq 0 ]
then
echo 'No project name provided (mandatory)'
exit 1
else
echo "- Project name:" $1
fi
if [ -z "$2" ]
then
echo '- Service name (optional): not provided'
GIT=$DIR_GIT$1.git
TMP=$DIR_TMP$1
WWW=$DIR_WWW$1
else
echo "- Service name (optional):" $2
GIT=$DIR_GIT$1.$2.git
TMP=$DIR_TMP$1.$2
WWW=$DIR_WWW$1/$2
# Create $WWW parent directory
dir_create $DIR_WWW$1
fi
echo "- Git: " $GIT
echo "- Tmp: " $TMP
echo "- Www: " $WWW
export GIT
export TMP
export WWW
# Create a directory and init as an empty git repo
sudo mkdir -p $GIT
cd $GIT
sudo git init --bare
# Set permissions
sudo chgrp -R users .
sudo chmod -R g+rwX .
# Sets the setgid bit on all the directories
# https://www.gnu.org/software/coreutils/manual/html_node/Directory-Setuid-and-Setgid.html
sudo find . -type d -exec chmod g+s '{}' +
# Make the directory a shared repo
sudo git config core.sharedRepository group
# create a post-receive file
cd hooks
sudo tee > post-receive << EOF
#!/bin/sh
# The production directory
WWW="${WWW}"
# A temporary directory for deployment
TMP="${TMP}"
# The Git repo
GIT="${GIT}"
# Deploy the content to the temporary directory
mkdir -p \$TMP
git --work-tree=\$TMP --git-dir=\$GIT checkout -f
# Do stuffs, like npm install…
cd \$TMP
# Replace the content of the production directory
# with the temporary directory
cd /
rm -rf \$WWW
mv \$TMP \$WWW
EOF
# make the post-receive file executable
sudo chmod +x post-receive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment