Skip to content

Instantly share code, notes, and snippets.

@durango
Last active December 19, 2015 01:09
Show Gist options
  • Select an option

  • Save durango/5873900 to your computer and use it in GitHub Desktop.

Select an option

Save durango/5873900 to your computer and use it in GitHub Desktop.
easily create centralized git projects on any server
#!/usr/bin/env bash
PROJ_NAME=""
PROJ_GIT_DIR=""
PROJ_DIR=""
PROJ_ROOT=""
PROJ_GIT_ROOT=""
PWD=$(pwd)
function set_config_vars () {
if [ $# -gt 2 ]
then
PROJ_ROOT=$1
PROJ_GIT_ROOT=$2
PROJ_NAME=$3
else
if [ $# -gt 1 ]
then
PROJ_ROOT=$1
PROJ_GIT_ROOT=$PROJ_ROOT.git
PROJ_NAME=$2
else
PROJ_ROOT=$PWD/projects/
PROJ_GIT_ROOT=$PWD/projects.git/
PROJ_NAME=$1
fi
fi
# Make sure we have trailing slashes...
PROJ_ROOT=$(echo $PROJ_ROOT | sed 's/\/$//')/
PROJ_GIT_ROOT="$(echo $PROJ_GIT_ROOT | sed 's/\/$//')/"
PROJ_DIR=$(echo $PROJ_ROOT$PROJ_NAME | sed 's/\/$//')/
PROJ_GIT_DIR=$(echo $PROJ_GIT_ROOT$PROJ_NAME | sed 's/\/$//')/
}
function check_project_name () {
COMPRESSED=$(echo $PROJ_NAME | sed -e 's/[^[:alnum:]|-]//g')
if [ "$COMPRESSED" != "$PROJ_NAME" ]
then
echo "Invalid project name. Alphanumeric characters only."
exit 0
fi
}
function can_create() {
check_project_name
if [ "$PROJ_NAME" = "" -o -z "$PROJ_NAME" -o -d "$PROJ_DIR" -o -d "$PROJ_GIT_DIR" ]
then
echo "Invalid project name. Already exist."
exit 0
fi
}
function check_project_exists () {
check_project_name
if [ -z "$PROJ_NAME" -o ! -d "$PROJ_DIR" -o ! -d "$PROJ_GIT_DIR" ]
then
echo "Invalid project name. Doesn't exist."
exit 0
fi
}
function check_project_dirs () {
if [ ! -d $PROJ_ROOT ]
then
echo "Directory $PROJ_ROOT not found! Creating..."
mkdir $PROJ_ROOT
fi
if [ ! -d "$PROJ_GIT_ROOT" ]
then
echo "Directory $PROJ_GIT_ROOT not found! Creating..."
mkdir $PROJ_GIT_ROOT
fi
}
function build_project () {
echo "Setting up initial directories..."
mkdir $PROJ_DIR $PROJ_GIT_DIR
PROJ_DIR=$(cd $PROJ_DIR; pwd)
PROJ_GIT_DIR=$(cd $PROJ_GIT_DIR; pwd)
echo "Setting up git repos..."
(cd $PROJ_DIR && git init)
(cd $PROJ_GIT_DIR && git init --bare)
echo "Setting up configuration file for repo"
echo -e $(
echo '[remote "hub"]'
echo "\n"
echo " url = $PROJ_GIT_DIR\n"
echo " fetch = +refs/heads/*:refs/remotes/hub/*\n"
) >> $PROJ_DIR/.git/config
echo "Setting up hooks for bare repo/hub"
echo -e $(
echo "#!/bin/sh\n"
echo "echo 'Pulling changes into repo...'\n\n"
echo "cd $(echo $PROJ_DIR | perl -pe 's/\.git\/?$//') || exit\n"
echo "unset GIT_DIR\n"
echo "git pull hub master\n\n"
echo "exec git-update-server-info\n"
) >> $PROJ_GIT_DIR/hooks/post-update
chmod +x $PROJ_GIT_DIR/hooks/post-update
}
function remove_project () {
echo "Removing project "
rm -r $PROJ_DIR $PROJ_GIT_DIR
}
if [ "$1" == -r ]
then
shift
set_config_vars "$@"
check_project_exists
remove_project
else
set_config_vars "$@"
can_create
check_project_dirs
build_project
fi
echo "Done"
echo
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment