afca6da5a0098243f0043ba26152aa8961e572de
[~madcoder/dotfiles.git] / +bin / git-new-workdir
1 #!/bin/sh
2
3 . "$(dirname "$0")/setup.sh"
4
5 usage () {
6         echo "usage:" $@
7         exit 127
8 }
9
10 die () {
11         echo $@
12         exit 128
13 }
14
15 if test $# -lt 2 || test $# -gt 3
16 then
17         usage "$0 <repository> <new_workdir> [<branch>]"
18 fi
19
20 orig_git=$1
21 new_workdir=$2
22 branch=$3
23
24 # want to make sure that what is pointed to has a .git directory ...
25 git_dir=$(cd "$orig_git" 2>/dev/null &&
26   git rev-parse --git-dir 2>/dev/null) ||
27   die "\"$orig_git\" is not a git repository!"
28
29 case "$git_dir" in
30 .git)
31         git_dir="$orig_git/.git"
32         ;;
33 .)
34         git_dir=$orig_git
35         ;;
36 esac
37
38 # don't link to a configured bare repository
39 isbare=$(git --git-dir="$git_dir" config --bool --get core.bare)
40 if test ztrue = z$isbare
41 then
42         die "\"$git_dir\" has core.bare set to true," \
43                 " remove from \"$git_dir/config\" to use $0"
44 fi
45
46 # don't link to a workdir
47 if test -L "$git_dir/config"
48 then
49         die "\"$orig_git\" is a working directory only, please specify" \
50                 "a complete repository."
51 fi
52
53 # don't recreate a workdir over an existing repository
54 if test -e "$new_workdir"
55 then
56         die "destination directory '$new_workdir' already exists."
57 fi
58
59 # make sure the the links use full paths
60 git_dir=$(cd "$git_dir"; pwd)
61
62 # create the workdir
63 mkdir -p "$new_workdir/.git" || die "unable to create \"$new_workdir\"!"
64
65 # create the links to the original repo.  explictly exclude index, HEAD and
66 # logs/HEAD from the list since they are purely related to the current working
67 # directory, and should not be shared.
68 for x in config refs logs/refs objects info hooks packed-refs remotes rr-cache
69 do
70         case $x in
71         */*)
72                 mkdir -p "$(dirname "$new_workdir/.git/$x")"
73                 ;;
74         esac
75         ln -s "$git_dir/$x" "$new_workdir/.git/$x"
76 done
77
78 # now setup the workdir
79 cd "$new_workdir"
80 # copy the HEAD from the original repository as a default branch
81 cp "$git_dir/HEAD" .git/HEAD
82 # checkout the branch (either the same as HEAD from the original repository, or
83 # the one that was asked for)
84 git checkout -f $branch