# updated gitvi script


The script in
[using git and vi
together](/2008/december/27/using_git_and_vi_together/index.html)
was a little bit borked, as too many git repo's were created. Hence a
new and improved version. This one will look up the directory tree to
spot an existing git repository - is nothing found a new one will be
created in `$PWD`.

# code

    #!/bin/zsh
    # a wrapper around git and vi
    # expands $Hash$ to $Hash: file short_hash epoch committer $
    # git checkout HEAD $file? when would I need this
    # TODO: spaces in filename

    [[ ! -x =git ]] && exit 1

    who=$SUDO_USER
    who=${who:-$LOGNAME}

    function search_git_dir {
        gpath="$1"

        [[ -d "$gpath/.git" ]] && echo "$gpath" && return
        [[ -z "$gpath" ]] && echo "" && return

        # strip that last path component and try again
        search_git_dir "${gpath%/*}"
    }

    for file in "$@"; do
	dir=$(dirname $file); cd $dir
	base=$(basename $file)

	if [[ -z $(search_git_dir $PWD) ]]; then
	    # make a new one in $PWD
	    git init || exit 1
	else
	    #echo FOUND ONE
	fi
	chmod +w $base 2> /dev/null

	if vi $base; then
	    [[ ! -e $base ]] && exit 0
	    git add $base
	    # collapse $Hash: id $ line
	    sed -i -e 's/\$Hash:.*\$/$Hash$/' $base
	    git commit $base
	fi

	id=$(git-show -s --pretty=format:$base\ %h\ %ct\ $who%n -- $base) 
	[[ -z $id ]] && exit 1

	# re-add $Hash: sha1hash$ line
	sed -i -e 's/\$Hash\$'/\$Hash:\ $id\ \$/ $base

	chmod a-w $base 2> /dev/null
    done

 manpage
And ofcourse the manpage.

    '\" t
    .TH GITVI 1 "27 Dec 2008" "0.1.0" "gitvi"

    .SH NAME
    gitvi \- a wrapper around git and vi(m)

    .SH SYNOPSIS
    gitvi [\fIFILE\fR]

    .SH DESCRIPTION
    Edit files and commit them to a git repository. If FILE is not
    given nothing is done.

    All the directories from the current one up to the root are
    search for a previous .git directory. If no directory is found
    a new git repository is created in the current directory. A
    new repository will never be created in the root directory.
    .PP
    The special sequence $Hash$ is expanded by \fBgit-vi\fR to 

    .RS
    $Hash: sha1hash filename epoch committer $
    .RE
    .PP
    This expanded $Hash$ syntax is \fInot\fR commited to git, this
    is done after the commit has taken place.

    .SH OPTIONS
    There are no options as of yet.

    .SH AUTHOR
    Miek Gieben <miek@miek.nl>

    .SH SEE ALSO
    vim(1), git(1).

