tg-depend.sh: expunge use of tsort
[topgit/pro.git] / tg.sh
blob308b61a1412d7acd3adbeae23686503f5405b4c0
1 #!/bin/sh
2 # TopGit - A different patch queue manager
3 # Copyright (C) Petr Baudis <pasky@suse.cz> 2008
4 # Copyright (C) Kyle J. McKay <mackyle@gmail.com> 2014,2015,2016
5 # All rights reserved.
6 # GPLv2
8 TG_VERSION=0.19.4
10 # Update in Makefile if you add any code that requires a newer version of git
11 GIT_MINIMUM_VERSION="@mingitver@"
13 ## SHA-1 pattern
15 octet='[0-9a-f][0-9a-f]'
16 octet4="$octet$octet$octet$octet"
17 octet19="$octet4$octet4$octet4$octet4$octet$octet$octet"
18 octet20="$octet4$octet4$octet4$octet4$octet4"
19 nullsha="0000000000000000000000000000000000000000"
20 tab=' '
21 lf='
24 ## Auxiliary functions
26 # Preserves current $? value while triggering a non-zero set -e exit if active
27 # This works even for shells that sometimes fail to correctly trigger a -e exit
28 check_exit_code()
30 return $?
33 # This is the POSIX equivalent of which
34 cmd_path()
36 { "unset" -f command unset unalias "$1"; } >/dev/null 2>&1 || :
37 { "unalias" -a; } >/dev/null 2>&1 || :
38 command -v "$1"
41 # Output arguments without any possible interpretation
42 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
43 echol()
45 printf '%s\n' "$*"
48 info()
50 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
53 warn()
55 info "warning: $*" >&2
58 err()
60 info "error: $*" >&2
63 die()
65 info "fatal: $*" >&2
66 exit 1
69 # shift off first arg then return "$*" properly quoted in single-quotes
70 # if $1 was '' output goes to stdout otherwise it's assigned to $1
71 # the final \n, if any, is omitted from the result but any others are included
72 v_quotearg()
74 _quotearg_v="$1"
75 shift
76 set -- "$_quotearg_v" \
77 "sed \"s/'/'\\\\\\''/g;1s/^/'/;\\\$s/\\\$/'/;s/'''/'/g;1s/^''\\(.\\)/\\1/\"" "$*"
78 unset _quotearg_v
79 if [ -z "$3" ]; then
80 if [ -z "$1" ]; then
81 echo "''"
82 else
83 eval "$1=\"''\""
85 else
86 if [ -z "$1" ]; then
87 printf "%s$4" "$3" | eval "$2"
88 else
89 eval "$1="'"$(printf "%s$4" "$3" | eval "$2")"'
94 # same as v_quotearg except there's no extra $1 so output always goes to stdout
95 quotearg()
97 v_quotearg '' "$@"
100 vcmp()
102 # Compare $1 to $3 each of which must match ^[^0-9]*\d*(\.\d*)*.*$
103 # where only the "\d*" parts in the regex participate in the comparison
104 # Since EVERY string matches that regex this function is easy to use
105 # An empty string ('') for $1 or $3 or any "\d*" part is treated as 0
106 # $2 is a compare op '<', '<=', '=', '==', '!=', '>=', '>'
107 # Return code is 0 for true, 1 for false (or unknown compare op)
108 # There is NO difference in behavior between '=' and '=='
109 # Note that "vcmp 1.8 == 1.8.0.0.0.0" correctly returns 0
110 set -- "$1" "$2" "$3" "${1%%[0-9]*}" "${3%%[0-9]*}"
111 set -- "${1#"$4"}" "$2" "${3#"$5"}"
112 set -- "${1%%[!0-9.]*}" "$2" "${3%%[!0-9.]*}"
113 while
114 vcmp_a_="${1%%.*}"
115 vcmp_b_="${3%%.*}"
116 [ "z$vcmp_a_" != "z" -o "z$vcmp_b_" != "z" ]
118 if [ "${vcmp_a_:-0}" -lt "${vcmp_b_:-0}" ]; then
119 unset vcmp_a_ vcmp_b_
120 case "$2" in "<"|"<="|"!=") return 0; esac
121 return 1
122 elif [ "${vcmp_a_:-0}" -gt "${vcmp_b_:-0}" ]; then
123 unset vcmp_a_ vcmp_b_
124 case "$2" in ">"|">="|"!=") return 0; esac
125 return 1;
127 vcmp_a_="${1#$vcmp_a_}"
128 vcmp_b_="${3#$vcmp_b_}"
129 set -- "${vcmp_a_#.}" "$2" "${vcmp_b_#.}"
130 done
131 unset vcmp_a_ vcmp_b_
132 case "$2" in "="|"=="|"<="|">=") return 0; esac
133 return 1
136 precheck() {
137 if ! git_version="$(git version)"; then
138 die "'git version' failed"
140 case "$git_version" in [Gg]"it version "*);;*)
141 die "'git version' output does not start with 'git version '"
142 esac
144 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
145 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
148 case "$1" in version|--version|-V)
149 echo "TopGit version $TG_VERSION"
150 exit 0
151 esac
153 precheck
154 [ "$1" = "precheck" ] && exit 0
157 cat_depsmsg_internal()
159 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
160 if [ -s "$tg_cache_dir/$1/.$2" ]; then
161 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
162 _line=
163 while IFS= read -r _line || [ -n "$_line" ]; do
164 printf '%s\n' "$_line"
165 done
166 return 0
167 fi <"$tg_cache_dir/$1/.$2"
169 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null || :
170 if [ -d "$tg_cache_dir/$1" ]; then
171 printf '%s\n' "$_rev" >"$tg_cache_dir/$1/.$2"
172 _line=
173 git cat-file blob "$_rev:.$2" 2>/dev/null |
174 while IFS= read -r _line || [ -n "$_line" ]; do
175 printf '%s\n' "$_line" >&3
176 printf '%s\n' "$_line"
177 done 3>>"$tg_cache_dir/$1/.$2"
178 else
179 git cat-file blob "$_rev:.$2" 2>/dev/null
183 # cat_deps BRANCHNAME
184 # Caches result
185 cat_deps()
187 cat_depsmsg_internal "$1" topdeps
190 # cat_msg BRANCHNAME
191 # Caches result
192 cat_msg()
194 cat_depsmsg_internal "$1" topmsg
197 # cat_file TOPIC:PATH [FROM]
198 # cat the file PATH from branch TOPIC when FROM is empty.
199 # FROM can be -i or -w, than the file will be from the index or worktree,
200 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
201 cat_file()
203 path="$1"
204 case "$2" in
206 cat "$root_dir/${path#*:}"
209 # ':file' means cat from index
210 git cat-file blob ":${path#*:}"
213 case "$path" in
214 refs/heads/*:.topdeps)
215 _temp="${path%:.topdeps}"
216 cat_deps "${_temp#refs/heads/}"
218 refs/heads/*:.topmsg)
219 _temp="${path%:.topmsg}"
220 cat_msg "${_temp#refs/heads/}"
223 git cat-file blob "$path"
225 esac
228 die "Wrong argument to cat_file: '$2'"
230 esac
233 # get tree for the committed topic
234 get_tree_()
236 echo "refs/heads/$1"
239 # get tree for the base
240 get_tree_b()
242 echo "refs/$topbases/$1"
245 # get tree for the index
246 get_tree_i()
248 git write-tree
251 # get tree for the worktree
252 get_tree_w()
254 i_tree=$(git write-tree)
256 # the file for --index-output needs to sit next to the
257 # current index file
258 cd "$root_dir"
259 : ${GIT_INDEX_FILE:="$git_dir/index"}
260 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
261 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
262 GIT_INDEX_FILE="$TMP_INDEX" &&
263 export GIT_INDEX_FILE &&
264 git diff --name-only -z HEAD |
265 git update-index -z --add --remove --stdin &&
266 git write-tree &&
267 rm -f "$TMP_INDEX"
271 # strip_ref "$(git symbolic-ref HEAD)"
272 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
273 strip_ref()
275 case "$1" in
276 refs/"$topbases"/*)
277 echol "${1#refs/$topbases/}"
279 refs/heads/*)
280 echol "${1#refs/heads/}"
283 echol "$1"
284 esac
287 # pretty_tree NAME [-b | -i | -w]
288 # Output tree ID of a cleaned-up tree without tg's artifacts.
289 # NAME will be ignored for -i and -w, but needs to be present
290 pretty_tree()
292 name=$1
293 source=${2#?}
294 git ls-tree --full-tree "$(get_tree_$source "$name")" |
295 LC_ALL=C sed -ne '/ \.top.*$/!p' |
296 git mktree
299 # return an empty-tree root commit -- date is either passed in or current
300 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
301 # An invalid secs causes the current date to be used, an invalid zone offset
302 # causes +0000 to be used
303 make_empty_commit()
305 # the empty tree is guaranteed to always be there even in a repo with
306 # zero objects, but for completeness we force it to exist as a real object
307 SECS=
308 read -r SECS ZONE JUNK <<-EOT || :
311 case "$SECS" in *[!0-9]*) SECS=; esac
312 if [ -z "$SECS" ]; then
313 MTDATE="$(date '+%s %z')"
314 else
315 case "$ZONE" in
316 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
318 [01][0-9][0-5][0-9])
319 ZONE="+$ZONE"
322 ZONE="+0000"
323 esac
324 MTDATE="$SECS $ZONE"
326 EMPTYID="- <-> $MTDATE"
327 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
328 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
329 git hash-object -t commit -w --stdin
332 # setup_hook NAME
333 setup_hook()
335 tgname="${0##*/}"
336 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
337 if [ -f "$git_common_dir/hooks/$1" ] && LC_ALL=C grep -Fq "$hook_call" "$git_common_dir/hooks/$1"; then
338 # Another job well done!
339 return
341 # Prepare incantation
342 hook_chain=
343 if [ -s "$git_common_dir/hooks/$1" -a -x "$git_common_dir/hooks/$1" ]; then
344 hook_call="$hook_call"' || exit $?'
345 if [ -L "$git_common_dir/hooks/$1" ] || ! LC_ALL=C sed -n 1p <"$git_common_dir/hooks/$1" | LC_ALL=C grep -Fqx "#!@SHELL_PATH@"; then
346 chain_num=
347 while [ -e "$git_common_dir/hooks/$1-chain$chain_num" ]; do
348 chain_num=$(( $chain_num + 1 ))
349 done
350 mv -f "$git_common_dir/hooks/$1" "$git_common_dir/hooks/$1-chain$chain_num"
351 hook_chain=1
353 else
354 hook_call="exec $hook_call"
355 [ -d "$git_common_dir/hooks" ] || mkdir "$git_common_dir/hooks" || :
357 # Don't call hook if tg is not installed
358 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
359 # Insert call into the hook
361 echol "#!@SHELL_PATH@"
362 echol "$hook_call"
363 if [ -n "$hook_chain" ]; then
364 echol "exec \"\$0-chain$chain_num\" \"\$@\""
365 else
366 [ ! -s "$git_common_dir/hooks/$1" ] || cat "$git_common_dir/hooks/$1"
368 } >"$git_common_dir/hooks/$1+"
369 chmod a+x "$git_common_dir/hooks/$1+"
370 mv "$git_common_dir/hooks/$1+" "$git_common_dir/hooks/$1"
373 # setup_ours (no arguments)
374 setup_ours()
376 if [ ! -s "$git_common_dir/info/attributes" ] || ! grep -q topmsg "$git_common_dir/info/attributes"; then
377 [ -d "$git_common_dir/info" ] || mkdir "$git_common_dir/info"
379 echo ".topmsg merge=ours"
380 echo ".topdeps merge=ours"
381 } >>"$git_common_dir/info/attributes"
383 if ! git config merge.ours.driver >/dev/null; then
384 git config merge.ours.name '"always keep ours" merge driver'
385 git config merge.ours.driver 'touch %A'
389 # measure_branch NAME [BASE] [EXTRAHEAD...]
390 measure_branch()
392 _bname="$1"; _base="$2"
393 shift; shift
394 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
395 # The caller should've verified $name is valid
396 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
397 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
398 if [ $_commits -ne 1 ]; then
399 _suffix="commits"
400 else
401 _suffix="commit"
403 echo "$_commits/$_nmcommits $_suffix"
406 # branch_contains B1 B2
407 # Whether B1 is a superset of B2.
408 branch_contains()
410 _revb1="$(ref_exists_rev "$1")" || return 0
411 _revb2="$(ref_exists_rev "$2")" || return 0
412 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
413 if read _result _rev_matchb1 _rev_matchb2 &&
414 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
415 return $_result
416 fi <"$tg_cache_dir/$1/.bc/$2/.d"
418 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
419 _result=0
420 [ "$(git rev-list --count --max-count=1 "$_revb2" --not "$_revb1" --)" = "0" ] || _result=1
421 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
422 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
424 return $_result
427 create_ref_dirs()
429 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
430 sed -e 's/ .*$//;'"s~^~$tg_tmp_dir/cached/~" <"$tg_ref_cache" | xargs mkdir -p
431 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
434 # If the first argument is non-empty, stores "1" there if this call created the cache
435 v_create_ref_cache()
437 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
438 _remotespec=
439 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
440 [ -z "$1" ] || eval "$1=1"
441 git for-each-ref --format='%(refname) %(objectname)' \
442 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
443 create_ref_dirs
446 remove_ref_cache()
448 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
449 >"$tg_ref_cache"
452 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
453 rev_parse()
455 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
456 LC_ALL=C awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
457 else
458 [ -z "$tg_ref_cache_only" ] || return 1
459 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
463 # ref_exists_rev REF
464 # Whether REF is a valid ref name
465 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
466 # or, if $base_remote is set, refs/remotes/$base_remote/
467 # Caches result if $tg_read_only and outputs HASH on success
468 ref_exists_rev()
470 case "$1" in
471 refs/*)
473 $octet20)
474 printf '%s' "$1"
475 return;;
477 die "ref_exists_rev requires fully-qualified ref name"
478 esac
479 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
480 _result=
481 _result_rev=
482 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
483 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
484 _result_rev="$(rev_parse "$1")"
485 _result=$?
486 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
487 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
488 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
489 printf '%s' "$_result_rev"
490 return $_result
493 # Same as ref_exists_rev but output is abbreviated hash
494 # Optional second argument defaults to --short but may be any --short=.../--no-short option
495 ref_exists_rev_short()
497 case "$1" in
498 refs/*)
500 $octet20)
503 die "ref_exists_rev_short requires fully-qualified ref name"
504 esac
505 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
506 _result=
507 _result_rev=
508 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
509 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
510 _result_rev="$(rev_parse "$1")"
511 _result=$?
512 if [ $_result -eq 0 ]; then
513 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev" --)"
514 _result=$?
516 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
517 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
518 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
519 printf '%s' "$_result_rev"
520 return $_result
523 # ref_exists REF
524 # Whether REF is a valid ref name
525 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
526 # or, if $base_remote is set, refs/remotes/$base_remote/
527 # Caches result
528 ref_exists()
530 ref_exists_rev "$1" >/dev/null
533 # rev_parse_tree REF
534 # Runs git rev-parse REF^{tree}
535 # Caches result if $tg_read_only
536 rev_parse_tree()
538 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
539 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
540 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
541 printf '%s\n' "$_result"
542 return 0
544 return 1
546 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
547 if [ -d "$tg_tmp_dir/cached/$1" ]; then
548 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
549 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
550 printf '%s\n' "$_result"
551 return 0
553 return 1
555 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
558 # has_remote BRANCH
559 # Whether BRANCH has a remote equivalent (accepts $topbases/ too)
560 has_remote()
562 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
565 # Return the verified TopGit branch name or die with an error.
566 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
567 # refs/heads/... then ... will be verified instead.
568 # if "$2" = "-f" (for fail) then return an error rather than dying.
569 verify_topgit_branch()
571 case "$1" in
572 refs/"$topbases"/*)
573 _verifyname="${1#refs/$topbases/}"
575 refs/heads/*)
576 _verifyname="${1#refs/heads/}"
578 HEAD|@)
579 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
580 [ -n "$_verifyname" -o "$2" = "-f" ] || die "HEAD is not a symbolic ref"
581 case "$_verifyname" in refs/heads/*);;*)
582 [ "$2" != "-f" ] || return 1
583 die "HEAD is not a symbolic ref to the refs/heads namespace"
584 esac
585 _verifyname="${_verifyname#refs/heads/}"
588 _verifyname="$1"
590 esac
591 if ! ref_exists "refs/heads/$_verifyname"; then
592 [ "$2" != "-f" ] || return 1
593 die "no such branch: $_verifyname"
595 if ! ref_exists "refs/$topbases/$_verifyname"; then
596 [ "$2" != "-f" ] || return 1
597 die "not a TopGit-controlled branch: $_verifyname"
599 printf '%s' "$_verifyname"
602 # Caches result
603 # $1 = branch name (i.e. "t/foo/bar")
604 # $2 = optional result of rev-parse "refs/heads/$1"
605 # $3 = optional result of rev-parse "refs/$topbases/$1"
606 branch_annihilated()
608 _branch_name="$1"
609 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
610 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
612 _result=
613 _result_rev=
614 _result_rev_base=
615 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/$_branch_name/.ann"; } 2>/dev/null || :
616 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
618 # use the merge base in case the base is ahead.
619 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
621 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
622 _result=$?
623 [ -d "$tg_cache_dir/$_branch_name" ] || mkdir -p "$tg_cache_dir/$_branch_name" 2>/dev/null
624 [ ! -d "$tg_cache_dir/$_branch_name" ] ||
625 echo $_result $_rev $_rev_base >"$tg_cache_dir/$_branch_name/.ann" 2>/dev/null || :
626 return $_result
629 non_annihilated_branches()
631 [ $# -gt 0 ] || set -- "refs/$topbases"
632 git for-each-ref --format='%(objectname) %(refname)' "$@" |
633 while read rev ref; do
634 name="${ref#refs/$topbases/}"
635 if branch_annihilated "$name" "" "$rev"; then
636 continue
638 echol "$name"
639 done
642 # Make sure our tree is clean
643 ensure_clean_tree()
645 check_status
646 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
647 git update-index --ignore-submodules --refresh ||
648 die "the working directory has uncommitted changes (see above) - first commit or reset them"
649 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
650 die "the index has uncommited changes"
653 # is_sha1 REF
654 # Whether REF is a SHA1 (compared to a symbolic name).
655 is_sha1()
657 case "$1" in $octet20) return 0;; esac
658 return 1
661 # recurse_deps_internal NAME [BRANCHPATH...]
662 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
663 # followed by a 1 if the branch is "tgish" or a 0 if not
664 # then the branch name followed by its depedency chain (which might be empty)
665 # An output line might look like this:
666 # 0 1 t/foo/leaf t/foo/int t/stage
667 # If no_remotes is non-empty, exclude remotes
668 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
669 # any branch names in the space-separated recurse_deps_exclude variable
670 # are skipped (along with their dependencies)
671 recurse_deps_internal()
673 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
674 _ref_hash=
675 if ! _ref_hash="$(ref_exists_rev "refs/heads/$1")"; then
676 [ -z "$2" ] || echo "1 0 $*"
677 return
680 _is_tgish=0
681 _ref_hash_base=
682 ! _ref_hash_base="$(ref_exists_rev "refs/$topbases/$1")" || _is_tgish=1
683 [ -z "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
685 # If no_remotes is unset also check our base against remote base.
686 # Checking our head against remote head has to be done in the helper.
687 if [ -n "$_is_tgish" -a -z "$no_remotes" ] && has_remote "$topbases/$1"; then
688 echo "0 0 refs/remotes/$base_remote/$topbases/$1 $*"
691 # if the branch was annihilated, it is considered to have no dependencies
692 if [ -n "$_is_tgish" ] && ! branch_annihilated "$1" "$_ref_hash" "$_ref_hash_base"; then
693 #TODO: handle nonexisting .topdeps?
694 cat_deps "$1" |
695 while read _dname; do
696 # Avoid depedency loops
697 case " $* " in *" $_dname "*)
698 warn "dependency loop detected in branch $_dname"
699 continue
700 esac
701 # Shoo shoo, leave our environment alone!
702 (recurse_deps_internal "$_dname" "$@")
703 done
706 [ -n "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
709 # do_eval CMD
710 # helper for recurse_deps so that a return statement executed inside CMD
711 # does not return from recurse_deps. This shouldn't be necessary, but it
712 # seems that it actually is.
713 do_eval()
715 eval "$@"
718 # becomes read-only for caching purposes
719 # assigns new value to tg_read_only
720 # become_cacheable/undo_become_cacheable calls may be nested
721 become_cacheable()
723 _old_tg_read_only="$tg_read_only"
724 if [ -z "$tg_read_only" ]; then
725 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
726 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
727 tg_read_only=1
729 _my_ref_cache=
730 v_create_ref_cache _my_ref_cache
731 _my_ref_cache="${_my_ref_cache:+1}"
732 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
735 # restores tg_read_only and ref_cache to state before become_cacheable call
736 # become_cacheable/undo_bocome_cacheable calls may be nested
737 undo_become_cacheable()
739 case "$tg_read_only" in
740 "undo"[01]"-"*)
741 _suffix="${tg_read_only#undo?-}"
742 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
743 tg_read_only="$_suffix"
744 esac
747 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
748 become_non_cacheable()
750 remove_ref_cache
751 tg_read_only=
752 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
753 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
756 # call this to make sure Git will not complain about a missing user/email
757 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
758 ensure_ident_available()
760 [ -z "$TG_IDENT_CHECKED" ] || return 0
761 git var GIT_AUTHOR_IDENT >/dev/null &&
762 git var GIT_COMMITTER_IDENT >/dev/null || exit
763 TG_IDENT_CHECKED=1
764 export TG_IDENT_CHECKED
765 return 0
768 # recurse_deps CMD NAME [BRANCHPATH...]
769 # Recursively eval CMD on all dependencies of NAME.
770 # Dependencies are visited in topological order.
771 # CMD can refer to $_name for queried branch name,
772 # $_dep for dependency name,
773 # $_depchain for space-seperated branch backtrace,
774 # $_dep_missing boolean to check whether $_dep is present
775 # and the $_dep_is_tgish boolean.
776 # It can modify $_ret to affect the return value
777 # of the whole function.
778 # If recurse_deps() hits missing dependencies, it will append
779 # them to space-separated $missing_deps list and skip them
780 # after calling CMD with _dep_missing set.
781 # remote dependencies are processed if no_remotes is unset.
782 # any branch names in the space-separated recurse_deps_exclude variable
783 # are skipped (along with their dependencies)
784 recurse_deps()
786 _cmd="$1"; shift
788 become_cacheable
789 _depsfile="$(get_temp tg-depsfile)"
790 recurse_deps_internal "$@" >>"$_depsfile"
791 undo_become_cacheable
793 _ret=0
794 while read _ismissing _istgish _dep _name _deppath; do
795 _depchain="$_name${_deppath:+ $_deppath}"
796 _dep_is_tgish=
797 [ "$_istgish" = "0" ] || _dep_is_tgish=1
798 _dep_missing=
799 if [ "$_ismissing" != "0" ]; then
800 _dep_missing=1
801 case " $missing_deps " in *" $_dep "*);;*)
802 missing_deps="${missing_deps:+$missing_deps }$_dep"
803 esac
805 do_eval "$_cmd"
806 done <"$_depsfile"
807 rm -f "$_depsfile"
808 return $_ret
811 # branch_needs_update
812 # This is a helper function for determining whether given branch
813 # is up-to-date wrt. its dependencies. It expects input as if it
814 # is called as a recurse_deps() helper.
815 # In case the branch does need update, it will echo it together
816 # with the branch backtrace on the output (see needs_update()
817 # description for details) and set $_ret to non-zero.
818 branch_needs_update()
820 if [ -n "$_dep_missing" ]; then
821 echo "! $_dep $_depchain"
822 return 0
825 if [ -n "$_dep_is_tgish" ]; then
826 branch_annihilated "$_dep" && return 0
828 if has_remote "$_dep"; then
829 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
830 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
832 # We want to sync with our base first and should output this before
833 # the remote branch, but the order does not actually matter to tg-update
834 # as it just recurses regardless, but it does matter for tg-info (which
835 # treats out-of-date bases as though they were already merged in) so
836 # we output the remote before the base.
837 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
838 echo ": $_dep $_depchain"
839 _ret=1
840 return
844 if [ -n "$_name" ]; then
845 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
846 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
847 # Some new commits in _dep
848 echo "$_dep $_depchain"
849 _ret=1
854 # needs_update NAME
855 # This function is recursive; it outputs reverse path from NAME
856 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
857 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
858 # if the head is not in sync with the <remote> branch <name>, ':' if
859 # the head is not in sync with the base (in this order of priority)
860 # or '!' if dependency is missing. Note that the remote branch, base
861 # order is reversed from the order they will actually be updated in
862 # order to accomodate tg info which treats out-of-date items that are
863 # only in the base as already being in the head for status purposes.
864 # It will also return non-zero status if NAME needs update.
865 # If needs_update() hits missing dependencies, it will append
866 # them to space-separated $missing_deps list and skip them.
867 needs_update()
869 recurse_deps branch_needs_update "$1"
872 # branch_empty NAME [-i | -w]
873 branch_empty()
875 if [ -z "$2" ]; then
876 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
877 _result=
878 _result_rev=
879 { read -r _result _result_rev <"$tg_cache_dir/$1/.mt"; } 2>/dev/null || :
880 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
881 _result=0
882 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ] || _result=$?
883 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null
884 [ ! -d "$tg_cache_dir/$1" ] || echo $_result $_rev >"$tg_cache_dir/$1/.mt"
885 return $_result
886 else
887 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ]
891 # list_deps [-i | -w] [BRANCH]
892 # -i/-w apply only to HEAD
893 list_deps()
895 head_from=
896 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
897 head="$(git symbolic-ref -q HEAD)" ||
898 head="..detached.."
900 git for-each-ref --format='%(objectname) %(refname)' "refs/$topbases${1:+/$1}" |
901 while read rev ref; do
902 name="${ref#refs/$topbases/}"
903 if branch_annihilated "$name" "" "$rev"; then
904 continue
907 from=$head_from
908 [ "refs/heads/$name" = "$head" ] ||
909 from=
910 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
911 dep_is_tgish=true
912 ref_exists "refs/$topbases/$dep" ||
913 dep_is_tgish=false
914 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
915 echo "$name $dep"
917 done
918 done
921 # switch_to_base NAME [SEED]
922 switch_to_base()
924 _base="refs/$topbases/$1"; _seed="$2"
925 # We have to do all the hard work ourselves :/
926 # This is like git checkout -b "$_base" "$_seed"
927 # (or just git checkout "$_base"),
928 # but does not create a detached HEAD.
929 git read-tree -u -m HEAD "${_seed:-$_base}"
930 [ -z "$_seed" ] || git update-ref "$_base" "$_seed"
931 git symbolic-ref HEAD "$_base"
934 # run editor with arguments
935 # the editor setting will be cached in $tg_editor (which is eval'd)
936 # result non-zero if editor fails or GIT_EDITOR cannot be determined
937 run_editor()
939 tg_editor="$GIT_EDITOR"
940 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
941 eval "$tg_editor" '"$@"'
944 # Show the help messages.
945 do_help()
947 _www=
948 if [ "$1" = "-w" ]; then
949 _www=1
950 shift
952 if [ -z "$1" ] ; then
953 # This is currently invoked in all kinds of circumstances,
954 # including when the user made a usage error. Should we end up
955 # providing more than a short help message, then we should
956 # differentiate.
957 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
959 ## Build available commands list for help output
961 cmds=
962 sep=
963 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
964 ! [ -r "$cmd" ] && continue
965 # strip directory part and "tg-" prefix
966 cmd="${cmd##*/}"
967 cmd="${cmd#tg-}"
968 [ "$cmd" != "summary" ] || cmd="status|$cmd"
969 cmds="$cmds$sep$cmd"
970 sep="|"
971 done
973 echo "TopGit version $TG_VERSION - A different patch queue manager"
974 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
975 echo " Or: $tgname help [-w] [<command>]"
976 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
977 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
978 if [ -n "$_www" ]; then
979 nohtml=
980 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
981 echo "${0##*/}: missing html help file:" \
982 "$TG_INST_SHAREDIR/topgit.html" 1>&2
983 nohtml=1
985 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
986 echo "${0##*/}: missing html help file:" \
987 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
988 nohtml=1
990 if [ -n "$nohtml" ]; then
991 echo "${0##*/}: use" \
992 "\"${0##*/} help $1\" instead" 1>&2
993 exit 1
995 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
996 exit
998 output()
1000 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1001 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1002 echo
1004 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1005 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1008 page output "$1"
1009 else
1010 echo "${0##*/}: no help for $1" 1>&2
1011 do_help
1012 exit 1
1016 check_status()
1018 git_state=
1019 git_remove=
1020 if [ -e "$git_dir/MERGE_HEAD" ]; then
1021 git_state="merge"
1022 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1023 git_state="am"
1024 git_remove="$git_dir/rebase-apply"
1025 elif [ -e "$git_dir/rebase-apply" ]; then
1026 git_state="rebase"
1027 git_remove="$git_dir/rebase-apply"
1028 elif [ -e "$git_dir/rebase-merge" ]; then
1029 git_state="rebase"
1030 git_remove="$git_dir/rebase-merge"
1031 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1032 git_state="cherry-pick"
1033 elif [ -e "$git_dir/BISECT_LOG" ]; then
1034 git_state="bisect"
1035 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1036 git_state="revert"
1038 git_remove="${git_remove#./}"
1040 tg_state=
1041 tg_remove=
1042 if [ -e "$git_dir/tg-update" ]; then
1043 tg_state="update"
1044 tg_remove="$git_dir/tg-update"
1045 elif [ -e "$git_dir/tg-create" ]; then
1046 tg_state="create"
1047 tg_remove="$git_dir/tg-create"
1049 tg_remove="${tg_remove#./}"
1052 # Show status information
1053 do_status()
1055 check_status
1056 symref="$(git symbolic-ref --quiet HEAD)" || :
1057 headrv="$(git rev-parse --quiet --verify --short HEAD --)" || :
1058 if [ -n "$symref" ]; then
1059 echol "HEAD -> $symref (${headrv:-unborn})"
1060 else
1061 echol "HEAD -> ${headrv:-?}"
1063 if [ -n "$tg_state" ]; then
1064 extra=
1065 if [ "$tg_state" = "update" ]; then
1066 IFS= read -r uname <"$git_dir/tg-update/name" || :
1067 [ -z "$uname" ] ||
1068 extra="; currently updating branch '$uname'"
1070 echol "tg $tg_state in progress$extra"
1071 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1072 printf 'You are currently updating as a result of:\n '
1073 cat "$git_dir/tg-update/fullcmd"
1074 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1075 if [ $bcnt -gt 1 ]; then
1076 pcnt=0
1077 ! [ -s "$git_dir/tg-update/processed" ] ||
1078 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1079 echo "$pcnt of $bcnt branches updated so far"
1082 if [ "$tg_state" = "update" ]; then
1083 echol ' (use "tg update --continue" to continue)'
1084 echol ' (use "tg update --skip" to skip this branch and continue)'
1085 echol ' (use "tg update --stop" to stop and retain updates so far)'
1086 echol ' (use "tg update --abort" to restore pre-update state)'
1089 [ -z "$git_state" ] || echo "git $git_state in progress"
1090 if [ "$git_state" = "merge" ]; then
1091 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1092 if [ $ucnt -gt 0 ]; then
1093 echo 'fix conflicts and then "git commit" the result'
1094 else
1095 echo 'all conflicts fixed; run "git commit" to record result'
1098 if [ -z "$git_state" ]; then
1099 ccnt="$(( $(git status --porcelain -uno | wc -l) ))"
1100 untr=
1101 if [ "$ccnt" -eq 0 ]; then
1102 if git status --porcelain | grep -q '^[?]'; then
1103 untr="; non-ignored, untracked files present"
1105 echo "working directory is clean$untr"
1106 else
1107 echo "working directory is DIRTY"
1112 ## Pager stuff
1114 # isatty FD
1115 isatty()
1117 test -t $1
1120 # pass "diff" to get pager.diff
1121 # if pager.$1 is a boolean false returns cat
1122 # if set to true or unset fails
1123 # otherwise succeeds and returns the value
1124 get_pager()
1126 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1127 [ "$_x" != "true" ] || return 1
1128 echo "cat"
1129 return 0
1131 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1132 echol "$_x"
1133 return 0
1135 return 1
1138 # setup_pager
1139 # Set TG_PAGER to a valid executable
1140 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1141 # See also the following "page" function for ease of use
1142 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1143 # Preference is (same as Git):
1144 # 1. GIT_PAGER
1145 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1146 # 3. core.pager (only if set)
1147 # 4. PAGER
1148 # 5. git var GIT_PAGER
1149 # 6. less
1150 setup_pager()
1152 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1154 emptypager=
1155 if [ -z "$TG_PAGER_IN_USE" ]; then
1156 # TG_PAGER = GIT_PAGER | PAGER | less
1157 # NOTE: GIT_PAGER='' is significant
1158 if [ -n "${GIT_PAGER+set}" ]; then
1159 TG_PAGER="$GIT_PAGER"
1160 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1161 TG_PAGER="$_dp"
1162 elif _cp="$(git config core.pager 2>/dev/null)"; then
1163 TG_PAGER="$_cp"
1164 elif [ -n "${PAGER+set}" ]; then
1165 TG_PAGER="$PAGER"
1166 else
1167 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1168 [ "$_gp" != ":" ] || _gp=
1169 TG_PAGER="${_gp:-less}"
1171 if [ -z "$TG_PAGER" ]; then
1172 emptypager=1
1173 TG_PAGER=cat
1175 else
1176 emptypager=1
1177 TG_PAGER=cat
1180 # Set pager default environment variables
1181 # see pager.c:setup_pager
1182 if [ -z "${LESS+set}" ]; then
1183 LESS="-FRX"
1184 export LESS
1186 if [ -z "${LV+set}" ]; then
1187 LV="-c"
1188 export LV
1191 # this is needed so e.g. $(git diff) will still colorize it's output if
1192 # requested in ~/.gitconfig with color.diff=auto
1193 GIT_PAGER_IN_USE=1
1194 export GIT_PAGER_IN_USE
1196 # this is needed so we don't get nested pagers
1197 TG_PAGER_IN_USE=1
1198 export TG_PAGER_IN_USE
1201 # page eval_arg [arg ...]
1203 # Calls setup_pager then evals the first argument passing it all the rest
1204 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1205 # by setup_pager (in which case the output is left as-is).
1207 # To handle arbitrary paging duties, collect lines to be paged into a
1208 # function and then call page with the function name or perhaps func_name "$@".
1210 # If no arguments at all are passed in do nothing (return with success).
1211 page()
1213 [ $# -gt 0 ] || return 0
1214 setup_pager
1215 _evalarg="$1"; shift
1216 if [ -n "$emptypager" ]; then
1217 eval "$_evalarg" '"$@"'
1218 else
1219 eval "$_evalarg" '"$@"' | eval "$TG_PAGER"
1223 # get_temp NAME [-d]
1224 # creates a new temporary file (or directory with -d) in the global
1225 # temporary directory $tg_tmp_dir with pattern prefix NAME
1226 get_temp()
1228 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1231 # automatically called by strftime
1232 # does nothing if already setup
1233 # may be called explicitly if the first call would otherwise be in a subshell
1234 # so that the setup is only done once before subshells start being spawned
1235 setup_strftime()
1237 [ -z "$strftime_is_setup" ] || return 0
1239 # date option to format raw epoch seconds values
1240 daterawopt=
1241 _testes='951807788'
1242 _testdt='2000-02-29 07:03:08 UTC'
1243 _testfm='%Y-%m-%d %H:%M:%S %Z'
1244 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1245 daterawopt='-d@'
1246 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1247 daterawopt='-r'
1249 strftime_is_setup=1
1252 # $1 => strftime format string to use
1253 # $2 => raw timestamp as seconds since epoch
1254 # $3 => optional time zone string (empty/absent for local time zone)
1255 strftime()
1257 setup_strftime
1258 if [ -n "$daterawopt" ]; then
1259 if [ -n "$3" ]; then
1260 TZ="$3" date "$daterawopt$2" "+$1"
1261 else
1262 date "$daterawopt$2" "+$1"
1264 else
1265 if [ -n "$3" ]; then
1266 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1267 else
1268 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1273 setup_git_dirs()
1275 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1276 if [ -z "$git_common_dir" ]; then
1277 if vcmp "$git_version" '>=' "2.5"; then
1278 git_common_dir="$(git rev-parse --git-common-dir)"
1279 else
1280 git_common_dir="$git_dir"
1283 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1284 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1287 basic_setup()
1289 setup_git_dirs
1290 [ -n "$base_remote" ] || base_remote="$(git config topgit.remote 2>/dev/null)" || :
1291 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1292 tgnosequester=
1293 [ "$tgsequester" != "false" ] || tgnosequester=1
1294 unset tgsequester
1296 # catch errors if topbases is used without being set
1297 unset tg_topbases_set
1298 topbases="programmer*:error"
1299 topbasesrx="programmer*:error}"
1300 oldbases="$topbases"
1303 ## Initial setup
1304 initial_setup()
1306 # suppress the merge log editor feature since git 1.7.10
1308 GIT_MERGE_AUTOEDIT=no
1309 export GIT_MERGE_AUTOEDIT
1311 basic_setup
1312 auhopt=
1313 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1314 root_dir="$(git rev-parse --show-cdup)"; root_dir="${root_dir:-.}"
1315 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1316 [ "$logrefupdates" = "true" ] || logrefupdates=
1318 # make sure root_dir doesn't end with a trailing slash.
1320 root_dir="${root_dir%/}"
1322 # make sure global cache directory exists inside GIT_DIR
1324 tg_cache_dir="$git_common_dir/tg-cache"
1325 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir"
1327 # create global temporary directories, inside GIT_DIR
1329 tg_tmp_dir=
1330 trap 'rm -rf "$tg_tmp_dir"' EXIT
1331 trap 'exit 129' HUP
1332 trap 'exit 130' INT
1333 trap 'exit 131' QUIT
1334 trap 'exit 134' ABRT
1335 trap 'exit 143' TERM
1336 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX")"
1337 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1340 set_topbases()
1342 # refer to "top-bases" in a refname with $topbases
1344 [ -z "$tg_topbases_set" ] || return 0
1346 # See if topgit.top-bases is set to heads or refs
1347 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
1348 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
1349 if [ -n "$1" ]; then
1350 # never die on the hook script
1351 unset tgtb
1352 else
1353 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
1356 if [ -n "$tgtb" ]; then
1357 case "$tgtb" in
1358 heads)
1359 topbases="heads/{top-bases}"
1360 topbasesrx="heads/[{]top-bases[}]"
1361 oldbases="top-bases";;
1362 refs)
1363 topbases="top-bases"
1364 topbasesrx="top-bases"
1365 oldbases="heads/{top-bases}";;
1366 esac
1367 # MUST NOT be exported
1368 unset tgtb tg_topbases_set
1369 tg_topbases_set=1
1370 return 0
1372 unset tgtb
1374 # check heads and top-bases and see what state the current
1375 # repository is in. remotes are ignored.
1377 hblist=" "
1378 topbases=
1379 both=
1380 newtb="heads/{top-bases}"
1381 while read -r rn && [ -n "$rn" ]; do case "$rn" in
1382 "refs/heads/{top-bases}"/*)
1383 case "$hblist" in *" ${rn#refs/$newtb/} "*)
1384 if [ "$topbases" != "heads/{top-bases}" ] && [ -n "$topbases" ]; then
1385 both=1
1386 break;
1387 else
1388 topbases="heads/{top-bases}"
1389 topbasesrx="heads/[{]top-bases[}]"
1390 oldbases="top-bases"
1392 esac;;
1393 "refs/top-bases"/*)
1394 case "$hblist" in *" ${rn#refs/top-bases/} "*)
1395 if [ "$topbases" != "top-bases" ] && [ -n "$topbases" ]; then
1396 both=1
1397 break;
1398 else
1399 topbases="top-bases"
1400 topbasesrx="top-bases"
1401 oldbases="heads/{top-bases}"
1403 esac;;
1404 "refs/heads"/*)
1405 hblist="$hblist${rn#refs/heads/} ";;
1406 esac; done <<-EOT
1407 $(git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases")
1409 if [ -n "$both" ]; then
1410 if [ -n "$1" ]; then
1411 # hook script always prefers newer without complaint
1412 topbases="heads/{top-bases}"
1413 topbasesrx="heads/[{]top-bases[}]"
1414 oldbases="top-bases"
1415 else
1416 # Complain and die
1417 err "repository contains existing TopGit branches"
1418 err "but some use refs/top-bases/... for the base"
1419 err "and some use refs/heads/{top-bases}/... for the base"
1420 err "with the latter being the new, preferred location"
1421 err "set \"topgit.top-bases\" to either \"heads\" to use"
1422 err "the new heads/{top-bases} location or \"refs\" to use"
1423 err "the old top-bases location."
1424 die "schizophrenic repository requires topgit.top-bases setting"
1428 [ -n "$topbases" ] || {
1429 # default is still top-bases for now
1430 topbases="top-bases"
1431 topbasesrx="top-bases"
1432 oldbases="heads/{top-bases}"
1434 # MUST NOT be exported
1435 unset hblist both newtb rn tg_topases_set
1436 tg_topbases_set=1
1437 return 0
1440 # init_reflog "ref"
1441 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
1442 # an empty log file to exist so that ref changes will be logged
1443 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
1444 # However, if "$1" is "refs/tgstash" then always make the reflog
1445 # The only ref not under refs/ that Git will write a reflog for is HEAD;
1446 # no matter what, it will NOT update a reflog for any other bare refs so
1447 # just quietly succeed when passed TG_STASH without doing anything.
1448 init_reflog()
1450 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
1451 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
1452 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
1453 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
1454 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
1457 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
1458 # a symbolic link. The directory part must exist, but the basename need not.
1459 v_get_abs_path()
1461 [ -n "$1" ] && [ -n "$2" ] || return 1
1462 set -- "$1" "$2" "${2%/}"
1463 case "$3" in
1464 */*) set -- "$1" "$2" "${3%/*}";;
1465 * ) set -- "$1" "$2" ".";;
1466 esac
1467 [ -d "$3" ] || return 1
1468 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}"'
1471 ## Startup
1473 : "${TG_INST_CMDDIR:=@cmddir@}"
1474 : "${TG_INST_SHAREDIR:=@sharedir@}"
1475 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1477 [ -d "$TG_INST_CMDDIR" ] ||
1478 die "No command directory: '$TG_INST_CMDDIR'"
1480 if [ -n "$tg__include" ]; then
1482 # We were sourced from another script for our utility functions;
1483 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1484 # work as expected in every shell. See http://bugs.debian.org/516188
1486 # ensure setup happens
1488 initial_setup
1489 set_topbases 1
1491 else
1493 set -e
1495 tg="$0"
1496 tgdir="${tg%/}"
1497 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
1498 tgdir="${tgdir%/*}/"
1499 tgname="${tg##*/}"
1500 [ "$0" != "$tgname" ] || tgdir=""
1502 # If tg contains a '/' but does not start with one then replace it with an absolute path
1504 case "$0" in /*) ;; */*)
1505 tgdir="$(cd "${0%/*}" && pwd -P)/"
1506 tg="$tgdir$tgname"
1507 esac
1509 # If the tg in the PATH is the same as "$tg" just display the basename
1510 # tgdisplay will include any explicit -C <dir> option whereas tg will not
1512 tgdisplaydir="$tgdir"
1513 tgdisplay="$tg"
1515 v_get_abs_path _tgabs "$tg" &&
1516 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
1517 [ "$_tgabs" = "$_tgnameabs" ]
1518 then
1519 tgdisplaydir=""
1520 tgdisplay="$tgname"
1522 unset _tgabs _tgnameabs
1524 explicit_remote=
1525 explicit_dir=
1526 gitcdopt=
1527 noremote=
1529 cmd=
1530 while :; do case "$1" in
1532 help|--help|-h)
1533 cmd=help
1534 shift
1535 break;;
1537 status|--status)
1538 cmd=status
1539 shift
1540 break;;
1542 --hooks-path)
1543 cmd=hooks-path
1544 shift
1545 break;;
1547 --top-bases)
1548 cmd=top-bases
1549 shift
1550 break;;
1553 shift
1554 if [ -z "$1" ]; then
1555 echo "Option -r requires an argument." >&2
1556 do_help
1557 exit 1
1559 unset noremote
1560 base_remote="$1"
1561 explicit_remote="$base_remote"
1562 tg="$tgdir$tgname -r $explicit_remote"
1563 tgdisplay="$tgdisplaydir$tgname"
1564 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1565 tgdisplay="$tgdisplay -r $explicit_remote"
1566 shift;;
1569 unset base_remote explicit_remote
1570 noremote=1
1571 tg="$tgdir$tgname -u"
1572 tgdisplay="$tgdisplaydir$tgname"
1573 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1574 tgdisplay="$tgdisplay -u"
1575 shift;;
1578 shift
1579 if [ -z "$1" ]; then
1580 echo "Option -C requires an argument." >&2
1581 do_help
1582 exit 1
1584 cd "$1"
1585 unset GIT_DIR GIT_COMMON_DIR
1586 explicit_dir="$1"
1587 gitcdopt=" -C \"$explicit_dir\""
1588 tg="$tgdir$tgname"
1589 tgdisplay="$tgdisplaydir$tgname -C \"$explicit_dir\""
1590 [ -z "$explicit_remote" ] || tg="$tg -r $explicit_remote"
1591 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
1592 [ -z "$noremote" ] || tg="$tg -u"
1593 [ -z "$noremote" ] || tg="$tgdisplay -u"
1594 shift;;
1597 shift
1598 if [ -z "$1" ]; then
1599 echo "Option -c requires an argument." >&2
1600 do_help
1601 exit 1
1603 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
1604 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
1605 export GIT_CONFIG_PARAMETERS
1606 shift;;
1609 shift
1610 break;;
1613 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
1614 do_help
1615 exit 1;;
1618 break;;
1620 esac; done
1622 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
1624 ## Dispatch
1626 [ -n "$cmd" ] || { do_help; exit 1; }
1628 case "$cmd" in
1630 help)
1631 do_help "$@"
1632 exit 0;;
1634 status)
1635 unset base_remote
1636 basic_setup
1637 set_topbases
1638 do_status "$@"
1639 exit 0;;
1641 hooks-path)
1642 # Internal command
1643 echol "$TG_INST_HOOKSDIR";;
1645 top-bases)
1646 # Maintenance command
1647 setup_git_dirs
1648 set_topbases
1649 echol "refs/$topbases";;
1652 [ -r "$TG_INST_CMDDIR"/tg-$cmd ] || {
1653 echo "Unknown subcommand: $cmd" >&2
1654 do_help
1655 exit 1
1658 initial_setup
1659 [ -z "$noremote" ] || unset base_remote
1661 nomergesetup=
1662 case "$cmd" in info|log|summary|rebase|revert|tag)
1663 # avoid merge setup where not necessary
1665 nomergesetup=1
1666 esac
1668 if [ -z "$nomergesetup" ]; then
1669 # make sure merging the .top* files will always behave sanely
1671 setup_ours
1672 setup_hook "pre-commit"
1675 # everything but rebase needs topbases set
1676 [ "$cmd" = "rebase" ] || set_topbases
1678 _use_ref_cache=
1679 tg_read_only=1
1680 case "$cmd" in
1681 summary|info|export|tag)
1682 _use_ref_cache=1;;
1683 annihilate|create|delete|depend|import|update)
1684 tg_read_only=;;
1685 esac
1686 [ -z "$_use_ref_cache" ] || v_create_ref_cache
1688 fullcmd="${tgname:-tg} $cmd $*"
1689 . "$TG_INST_CMDDIR"/tg-$cmd;;
1690 esac
1694 # vim:noet