Saturday, September 13, 2008

Quick Remote Git Repository Creation Script

If you are using Git for your source code management, GitHub is an awesome tool. It especially shines for public projects where you freely allow others to fork your code and possibly pull patches back in.

Sometimes I'm just working on a project that I would prefer to keep in a private repository. GitHub provides paying accounts with such an option. However, I already have hosting accounts that are terribly underused. Here is a little script I use to create a remote git repository on one of my VPS accounts that I can then pull from and push to.

Prerequisites
A hosting account which you can ssh / scp into.

The Script

$ vim new_repo

#! /bin/sh
PWD=`pwd`

# You must adjust these variables for your specifc hosting account.
# Remote user you will connect as.
REMOTE_USER="admin"
# The IP address you will SSH / SCP to.
REMOTE_HOST="123.456.123.456"
# The remote path you wish to store your .git repositories in.
REMOTE_REPO_PATH="/home/admin/repos/"

if [ -d $1 ]; then
  echo "EXITING: Local directory '$1' already exists."
  exit 0
else
  mkdir $1
  cd $1
  git init-db
  touch README
  git add .
  git commit -m "Initial Repository Creation"
  cd ..
  git clone --bare $1/.git $1.git
  echo "** Copying new repository $1.git to $REMOTE_HOST:$REMOTE_REPO_PATH"
  scp -r $1.git $REMOTE_USER@$REMOTE_HOST:$REMOTE_REPO_PATH
  rm -rf $1.git
  rm -rf $1
  echo "** Cloning locally at $PWD/$1"
  git clone $REMOTE_USER@$REMOTE_HOST:$REMOTE_REPO_PATH$1.git
fi

exit 0

Or get it from GitHub

http://github.com/jpease/git-o-mator

Configuration

Of course, you will need to REMOTE_USER="admin" with an actual user on your hosting account, adjust REMOTE_HOST="123.456.123.456" to point to your accounts IP address, and edit REMOTE_REPO_PATH="/home/admin/repos/" with whatever path you wish to contain your Git repositories.

Once that is done, provide executable permissions.

$ chmod +x new_repo

That's it. Now if you execute:

$ ./new_repo testing

You will end up with /home/user/repos/testing.git on your remote host, and ./testing locally. From ./testing you can git push to send commits to the remote repository, and git pull to retrieve from the remote repository.

If you see room for improvement, I'm sure there is some, please leave a comment with your revision!

2 comments:

  1. this was excellent, havn't thought about streamlining it like this and now I've nothing holding me back to using git for all my versioning needs! :)

    /Björn

    ReplyDelete
  2. Björn,

    Thanks for the comment! Inspired me to rewrite the script a bit. Now all the variables are handled at the top of the script, and there is a conditional to prevent over-writing a local directory if one exists with the same name. Enjoy!

    ReplyDelete