git-serve: Serve a Git Repository from a Remote Server

Have a small Bash shell function to serve the current Git distributed version control system repository from a remote host.  The second time I needed to do this, it was time to add a function tomy .bash_site file. Enjoy:

# Serve this repository from a remote host.
# Run without arguments from the current directory, puts a new repository
# on $remote_host, and let's you do "git push" commands.   Thanks to
# ToolManTim who wrote http://toolmantim.com/thoughts/setting_up_a_new_remote_git_repository
# a few years back.
git-serve () {
    # set remote_host to name in your .ssh/config file.
    remote_host='dream'
    repo_name=$(basename $PWD)
    # if current directory a git repo and name not taken on remote.
    if [ -d .git ] && [ $(ssh $remote_host "ls git/$repo_name 2> /dev/null" | wc -c) -eq 0 ]
    then
        ssh $remote_host "mkdir -p git/$repo_name && cd git/$repo_name && git init --bare"
        git remote add origin $remote_host:git/$repo_name
        git push origin master
        echo '[branch "master"]
      remote = origin
      merge = refs/heads/master
' >> .git/config
      echo "Set up the repository on $remote_host in git/$repo_name.  Please double check your .git/config file:"
      cat .git/config
    else
      echo "Current directory not a repository (no .git) or name taken at $remote_host:git/$repo_name"
    fi
    unset remote_host repo_name
}


So here is an example working with a small, existing repository:

chasm:(master)~/junk$ ls -a
.  ..  .git  hello

chasm:(master)~/junk$ git-serve
Initialized empty Git repository in /home/gizbot/git/junk/
Counting objects: 3, done.
Writing objects: 100% (3/3), 217 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To dream:git/junk
 * [new branch]      master -> master
Set up the repository on dream in git/junk.  Please double check your .git/config file:
[core]
	repositoryformatversion = 0
	filemode = true
	bare = false
	logallrefupdates = true
[remote "origin"]
	url = dream:git/junk
	fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
      remote = origin
      merge = refs/heads/master

chasm:(master)~/junk$ echo "Hi" > hello; git commit -a -m "Hi."
[master dbdcb0a] Hi.
 1 files changed, 1 insertions(+), 1 deletions(-)

chasm:(master)~/junk$ git push
Counting objects: 5, done.
Writing objects: 100% (3/3), 239 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To dream:git/junk
   bb04a32..dbdcb0a  master -> master

chasm:(master)~/junk$ git-serve
Current directory not a repository (no .git) or name taken at dream:git/junk

chasm:(master)~/junk$

0 comments ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment