···1010 exit 128
1111}
12121313+failed () {
1414+ die "unable to create new workdir '$new_workdir'!"
1515+}
1616+1317if test $# -lt 2 || test $# -gt 3
1418then
1519 usage "$0 <repository> <new_workdir> [<branch>]"
···35393640# don't link to a configured bare repository
3741isbare=$(git --git-dir="$git_dir" config --bool --get core.bare)
3838-if test ztrue = z$isbare
4242+if test ztrue = "z$isbare"
3943then
4044 die "\"$git_dir\" has core.bare set to true," \
4145 " remove from \"$git_dir/config\" to use $0"
···4852 "a complete repository."
4953fi
50545151-# don't recreate a workdir over an existing repository
5252-if test -e "$new_workdir"
5555+# make sure the links in the workdir have full paths to the original repo
5656+git_dir=$(cd "$git_dir" && pwd) || exit 1
5757+5858+# don't recreate a workdir over an existing directory, unless it's empty
5959+if test -d "$new_workdir"
5360then
5454- die "destination directory '$new_workdir' already exists."
6161+ if test $(ls -a1 "$new_workdir/." | wc -l) -ne 2
6262+ then
6363+ die "destination directory '$new_workdir' is not empty."
6464+ fi
6565+ cleandir="$new_workdir/.git"
6666+else
6767+ cleandir="$new_workdir"
5568fi
56695757-# make sure the links use full paths
5858-git_dir=$(cd "$git_dir"; pwd)
7070+mkdir -p "$new_workdir/.git" || failed
7171+cleandir=$(cd "$cleandir" && pwd) || failed
59726060-# create the workdir
6161-mkdir -p "$new_workdir/.git" || die "unable to create \"$new_workdir\"!"
7373+cleanup () {
7474+ rm -rf "$cleandir"
7575+}
7676+siglist="0 1 2 15"
7777+trap cleanup $siglist
62786379# create the links to the original repo. explicitly exclude index, HEAD and
6480# logs/HEAD from the list since they are purely related to the current working
6581# directory, and should not be shared.
6682for x in config refs logs/refs objects info hooks packed-refs remotes rr-cache svn
6783do
8484+ # create a containing directory if needed
6885 case $x in
6986 */*)
7070- mkdir -p "$(dirname "$new_workdir/.git/$x")"
8787+ mkdir -p "$new_workdir/.git/${x%/*}"
7188 ;;
7289 esac
7373- ln -s "$git_dir/$x" "$new_workdir/.git/$x"
9090+9191+ ln -s "$git_dir/$x" "$new_workdir/.git/$x" || failed
7492done
75937676-# now setup the workdir
7777-cd "$new_workdir"
9494+# commands below this are run in the context of the new workdir
9595+cd "$new_workdir" || failed
9696+7897# copy the HEAD from the original repository as a default branch
7979-cp "$git_dir/HEAD" .git/HEAD
8080-# checkout the branch (either the same as HEAD from the original repository, or
8181-# the one that was asked for)
9898+cp "$git_dir/HEAD" .git/HEAD || failed
9999+100100+# the workdir is set up. if the checkout fails, the user can fix it.
101101+trap - $siglist
102102+103103+# checkout the branch (either the same as HEAD from the original repository,
104104+# or the one that was asked for)
82105git checkout -f $branch