tg.sh: use command -v instead of which
[topgit/pro.git] / tg.sh
blob7ff675dce0472b89258fea06a6a3e266d2adfeee
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"
21 ## Auxiliary functions
23 # Preserves current $? value while triggering a non-zero set -e exit if active
24 # This works even for shells that sometimes fail to correctly trigger a -e exit
25 check_exit_code()
27 return $?
30 # This is the POSIX equivalent of which
31 cmd_path()
33 { "unset" -f command unset unalias "$1"; } >/dev/null 2>&1 || :
34 { "unalias" -a; } >/dev/null 2>&1 || :
35 command -v "$1"
38 # Output arguments without any possible interpretation
39 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
40 echol()
42 printf '%s\n' "$*"
45 info()
47 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
50 warn()
52 info "warning: $*" >&2
55 err()
57 info "error: $*" >&2
60 die()
62 info "fatal: $*" >&2
63 exit 1
66 vcmp()
68 # Compare $1 to $2 each of which must match \d+(\.\d+)*
69 # An empty string ('') for $1 or $2 is treated like 0
70 # Outputs:
71 # -1 if $1 < $2
72 # 0 if $1 = $2
73 # 1 if $1 > $2
74 # Note that $(vcmp 1.8 1.8.0.0.0.0) correctly outputs 0.
75 while
76 _a="${1%%.*}"
77 _b="${2%%.*}"
78 [ -n "$_a" -o -n "$_b" ]
80 if [ "${_a:-0}" -lt "${_b:-0}" ]; then
81 echo -1
82 return
83 elif [ "${_a:-0}" -gt "${_b:-0}" ]; then
84 echo 1
85 return
87 _a2="${1#$_a}"
88 _b2="${2#$_b}"
89 set -- "${_a2#.}" "${_b2#.}"
90 done
91 echo 0
94 precheck() {
95 if ! git_version="$(git version)"; then
96 die "'git version' failed"
98 case "$git_version" in
99 [Gg]"it version "*) :;;
101 die "'git version' output does not start with 'git version '"
102 esac
103 git_vernum="$(echo "$git_version" | sed -ne 's/^[^0-9]*\([0-9][0-9]*\(\.[0-9][0-9]*\)*\).*$/\1/p')"
105 [ "$(vcmp "$git_vernum" $GIT_MINIMUM_VERSION)" -ge 0 ] ||
106 die "git version >= $GIT_MINIMUM_VERSION required but found git version $git_vernum instead"
109 case "$1" in version|--version|-V)
110 echo "TopGit version $TG_VERSION"
111 exit 0
112 esac
114 precheck
115 [ "$1" = "precheck" ] && exit 0
118 cat_depsmsg_internal()
120 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
121 if [ -s "$tg_cache_dir/$1/.$2" ]; then
122 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
123 _line=
124 while IFS= read -r _line || [ -n "$_line" ]; do
125 printf '%s\n' "$_line"
126 done
127 return 0
128 fi <"$tg_cache_dir/$1/.$2"
130 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null || :
131 if [ -d "$tg_cache_dir/$1" ]; then
132 printf '%s\n' "$_rev" >"$tg_cache_dir/$1/.$2"
133 _line=
134 git cat-file blob "$_rev:.$2" 2>/dev/null |
135 while IFS= read -r _line || [ -n "$_line" ]; do
136 printf '%s\n' "$_line" >&3
137 printf '%s\n' "$_line"
138 done 3>>"$tg_cache_dir/$1/.$2"
139 else
140 git cat-file blob "$_rev:.$2" 2>/dev/null
144 # cat_deps BRANCHNAME
145 # Caches result
146 cat_deps()
148 cat_depsmsg_internal "$1" topdeps
151 # cat_msg BRANCHNAME
152 # Caches result
153 cat_msg()
155 cat_depsmsg_internal "$1" topmsg
158 # cat_file TOPIC:PATH [FROM]
159 # cat the file PATH from branch TOPIC when FROM is empty.
160 # FROM can be -i or -w, than the file will be from the index or worktree,
161 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
162 cat_file()
164 path="$1"
165 case "$2" in
167 cat "$root_dir/${path#*:}"
170 # ':file' means cat from index
171 git cat-file blob ":${path#*:}"
174 case "$path" in
175 refs/heads/*:.topdeps)
176 _temp="${path%:.topdeps}"
177 cat_deps "${_temp#refs/heads/}"
179 refs/heads/*:.topmsg)
180 _temp="${path%:.topmsg}"
181 cat_msg "${_temp#refs/heads/}"
184 git cat-file blob "$path"
186 esac
189 die "Wrong argument to cat_file: '$2'"
191 esac
194 # get tree for the committed topic
195 get_tree_()
197 echo "refs/heads/$1"
200 # get tree for the base
201 get_tree_b()
203 echo "refs/$topbases/$1"
206 # get tree for the index
207 get_tree_i()
209 git write-tree
212 # get tree for the worktree
213 get_tree_w()
215 i_tree=$(git write-tree)
217 # the file for --index-output needs to sit next to the
218 # current index file
219 cd "$root_dir"
220 : ${GIT_INDEX_FILE:="$git_dir/index"}
221 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
222 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
223 GIT_INDEX_FILE="$TMP_INDEX" &&
224 export GIT_INDEX_FILE &&
225 git diff --name-only -z HEAD |
226 git update-index -z --add --remove --stdin &&
227 git write-tree &&
228 rm -f "$TMP_INDEX"
232 # strip_ref "$(git symbolic-ref HEAD)"
233 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
234 strip_ref()
236 case "$1" in
237 refs/heads/*)
238 echol "${1#refs/heads/}"
240 refs/"$topbases"/*)
241 echol "${1#refs/$topbases/}"
244 echol "$1"
245 esac
248 # pretty_tree NAME [-b | -i | -w]
249 # Output tree ID of a cleaned-up tree without tg's artifacts.
250 # NAME will be ignored for -i and -w, but needs to be present
251 pretty_tree()
253 name=$1
254 source=${2#?}
255 git ls-tree --full-tree "$(get_tree_$source "$name")" |
256 LC_ALL=C sed -ne '/ \.top.*$/!p' |
257 git mktree
260 # return an empty-tree root commit -- date is either passed in or current
261 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
262 # An invalid secs causes the current date to be used, an invalid zone offset
263 # causes +0000 to be used
264 make_empty_commit()
266 # the empty tree is guaranteed to always be there even in a repo with
267 # zero objects, but for completeness we force it to exist as a real object
268 SECS=
269 read -r SECS ZONE JUNK <<-EOT || :
272 case "$SECS" in *[!0-9]*) SECS=; esac
273 if [ -z "$SECS" ]; then
274 MTDATE="$(date '+%s %z')"
275 else
276 case "$ZONE" in
277 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
279 [01][0-9][0-5][0-9])
280 ZONE="+$ZONE"
283 ZONE="+0000"
284 esac
285 MTDATE="$SECS $ZONE"
287 EMPTYID="- <-> $MTDATE"
288 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
289 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
290 git hash-object -t commit -w --stdin
293 # setup_hook NAME
294 setup_hook()
296 tgname="$(basename "$0")"
297 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
298 if [ -f "$git_dir/hooks/$1" ] && fgrep -q "$hook_call" "$git_dir/hooks/$1"; then
299 # Another job well done!
300 return
302 # Prepare incantation
303 hook_chain=
304 if [ -s "$git_dir/hooks/$1" -a -x "$git_dir/hooks/$1" ]; then
305 hook_call="$hook_call"' || exit $?'
306 if ! LC_ALL=C sed -n 1p <"$git_dir/hooks/$1" | LC_ALL=C fgrep -qx "#!@SHELL_PATH@"; then
307 chain_num=
308 while [ -e "$git_dir/hooks/$1-chain$chain_num" ]; do
309 chain_num=$(( $chain_num + 1 ))
310 done
311 cp -p "$git_dir/hooks/$1" "$git_dir/hooks/$1-chain$chain_num"
312 hook_chain=1
314 else
315 hook_call="exec $hook_call"
317 # Don't call hook if tg is not installed
318 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
319 # Insert call into the hook
321 echol "#!@SHELL_PATH@"
322 echol "$hook_call"
323 if [ -n "$hook_chain" ]; then
324 echol "exec \"\$0-chain$chain_num\" \"\$@\""
325 else
326 [ ! -s "$git_dir/hooks/$1" ] || cat "$git_dir/hooks/$1"
328 } >"$git_dir/hooks/$1+"
329 chmod a+x "$git_dir/hooks/$1+"
330 mv "$git_dir/hooks/$1+" "$git_dir/hooks/$1"
333 # setup_ours (no arguments)
334 setup_ours()
336 if [ ! -s "$git_dir/info/attributes" ] || ! grep -q topmsg "$git_dir/info/attributes"; then
337 [ -d "$git_dir/info" ] || mkdir "$git_dir/info"
339 echo ".topmsg merge=ours"
340 echo ".topdeps merge=ours"
341 } >>"$git_dir/info/attributes"
343 if ! git config merge.ours.driver >/dev/null; then
344 git config merge.ours.name '"always keep ours" merge driver'
345 git config merge.ours.driver 'touch %A'
349 # measure_branch NAME [BASE] [EXTRAHEAD...]
350 measure_branch()
352 _bname="$1"; _base="$2"
353 shift; shift
354 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
355 # The caller should've verified $name is valid
356 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
357 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
358 if [ $_commits -ne 1 ]; then
359 _suffix="commits"
360 else
361 _suffix="commit"
363 echo "$_commits/$_nmcommits $_suffix"
366 # branch_contains B1 B2
367 # Whether B1 is a superset of B2.
368 branch_contains()
370 _revb1="$(ref_exists_rev "$1")" || return 0
371 _revb2="$(ref_exists_rev "$2")" || return 0
372 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
373 if read _result _rev_matchb1 _rev_matchb2 &&
374 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
375 return $_result
376 fi <"$tg_cache_dir/$1/.bc/$2/.d"
378 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
379 _result=0
380 [ -z "$(git rev-list --max-count=1 ^"$_revb1" "$_revb2" --)" ] || _result=$?
381 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
382 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
384 return $_result
387 create_ref_dirs()
389 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
390 sed -e 's/ .*$//;'"s~^~$tg_tmp_dir/cached/~" <"$tg_ref_cache" | xargs mkdir -p
391 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
394 # If the first argument is non-empty, outputs "1" if this call created the cache
395 create_ref_cache()
397 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
398 _remotespec=
399 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
400 [ -z "$1" ] || printf '1'
401 git for-each-ref --format='%(refname) %(objectname)' \
402 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
403 create_ref_dirs
406 remove_ref_cache()
408 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
409 >"$tg_ref_cache"
412 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
413 rev_parse()
415 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
416 LC_ALL=C awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
417 else
418 [ -z "$tg_ref_cache_only" ] || return 1
419 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
423 # ref_exists_rev REF
424 # Whether REF is a valid ref name
425 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
426 # or, if $base_remote is set, refs/remotes/$base_remote/
427 # Caches result if $tg_read_only and outputs HASH on success
428 ref_exists_rev()
430 case "$1" in
431 refs/*)
433 $octet20)
434 printf '%s' "$1"
435 return;;
437 die "ref_exists_rev requires fully-qualified ref name"
438 esac
439 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
440 _result=
441 _result_rev=
442 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
443 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
444 _result_rev="$(rev_parse "$1")"
445 _result=$?
446 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
447 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
448 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
449 printf '%s' "$_result_rev"
450 return $_result
453 # Same as ref_exists_rev but output is abbreviated hash
454 ref_exists_rev_short()
456 case "$1" in
457 refs/*)
459 $octet20)
462 die "ref_exists_rev_short requires fully-qualified ref name"
463 esac
464 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify --short "$1^0" -- 2>/dev/null; return; }
465 _result=
466 _result_rev=
467 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
468 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
469 _result_rev="$(rev_parse "$1")"
470 _result=$?
471 if [ $_result -eq 0 ]; then
472 _result_rev="$(git rev-parse --verify --short --quiet "$_result_rev" --)"
473 _result=$?
475 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
476 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
477 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
478 printf '%s' "$_result_rev"
479 return $_result
482 # ref_exists REF
483 # Whether REF is a valid ref name
484 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
485 # or, if $base_remote is set, refs/remotes/$base_remote/
486 # Caches result
487 ref_exists()
489 ref_exists_rev "$1" >/dev/null
492 # rev_parse_tree REF
493 # Runs git rev-parse REF^{tree}
494 # Caches result if $tg_read_only
495 rev_parse_tree()
497 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
498 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
499 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
500 printf '%s\n' "$_result"
501 return 0
503 return 1
505 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
506 if [ -d "$tg_tmp_dir/cached/$1" ]; then
507 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
508 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
509 printf '%s\n' "$_result"
510 return 0
512 return 1
514 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
517 # has_remote BRANCH
518 # Whether BRANCH has a remote equivalent (accepts $topbases/ too)
519 has_remote()
521 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
524 # Return the verified TopGit branch name or die with an error.
525 # As a convenience, if HEAD is given and HEAD is a symbolic ref to
526 # refs/heads/... then ... will be verified instead.
527 # if "$2" = "-f" (for fail) then return an error rather than dying.
528 verify_topgit_branch()
530 case "$1" in
531 refs/heads/*)
532 _verifyname="${1#refs/heads/}"
534 refs/"$topbases"/*)
535 _verifyname="${1#refs/$topbases/}"
537 HEAD)
538 _verifyname="$(git symbolic-ref HEAD 2>/dev/null || :)"
539 [ -n "$_verifyname" -o "$2" = "-f" ] || die "HEAD is not a symbolic ref"
540 case "$_verifyname" in refs/heads/*) :;; *)
541 [ "$2" != "-f" ] || return 1
542 die "HEAD is not a symbolic ref to the refs/heads namespace"
543 esac
544 _verifyname="${_verifyname#refs/heads/}"
547 _verifyname="$1"
549 esac
550 if ! ref_exists "refs/heads/$_verifyname"; then
551 [ "$2" != "-f" ] || return 1
552 die "no such branch: $_verifyname"
554 if ! ref_exists "refs/$topbases/$_verifyname"; then
555 [ "$2" != "-f" ] || return 1
556 die "not a TopGit-controlled branch: $_verifyname"
558 printf '%s' "$_verifyname"
561 # Caches result
562 # $1 = branch name (i.e. "t/foo/bar")
563 # $2 = optional result of rev-parse "refs/heads/$1"
564 # $3 = optional result of rev-parse "refs/$topbases/$1"
565 branch_annihilated()
567 _branch_name="$1"
568 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
569 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
571 _result=
572 _result_rev=
573 _result_rev_base=
574 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/$_branch_name/.ann"; } 2>/dev/null || :
575 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
577 # use the merge base in case the base is ahead.
578 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
580 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
581 _result=$?
582 [ -d "$tg_cache_dir/$_branch_name" ] || mkdir -p "$tg_cache_dir/$_branch_name" 2>/dev/null
583 [ ! -d "$tg_cache_dir/$_branch_name" ] ||
584 echo $_result $_rev $_rev_base >"$tg_cache_dir/$_branch_name/.ann" 2>/dev/null || :
585 return $_result
588 non_annihilated_branches()
590 [ $# -gt 0 ] || set -- "refs/$topbases"
591 git for-each-ref --format='%(objectname) %(refname)' "$@" |
592 while read rev ref; do
593 name="${ref#refs/$topbases/}"
594 if branch_annihilated "$name" "" "$rev"; then
595 continue
597 echol "$name"
598 done
601 # Make sure our tree is clean
602 ensure_clean_tree()
604 git update-index --ignore-submodules --refresh ||
605 die "the working directory has uncommitted changes (see above) - first commit or reset them"
606 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
607 die "the index has uncommited changes"
610 # is_sha1 REF
611 # Whether REF is a SHA1 (compared to a symbolic name).
612 is_sha1()
614 case "$1" in $octet20) return 0;; esac
615 return 1
618 # recurse_deps_internal NAME [BRANCHPATH...]
619 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
620 # followed by a 1 if the branch is "tgish" or a 0 if not
621 # then the branch name followed by its depedency chain (which might be empty)
622 # An output line might look like this:
623 # 0 1 t/foo/leaf t/foo/int t/stage
624 # If no_remotes is non-empty, exclude remotes
625 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
626 # any branch names in the space-separated recurse_deps_exclude variable
627 # are skipped (along with their dependencies)
628 recurse_deps_internal()
630 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
631 _ref_hash=
632 if ! _ref_hash="$(ref_exists_rev "refs/heads/$1")"; then
633 [ -z "$2" ] || echo "1 0 $*"
634 return
637 _is_tgish=0
638 _ref_hash_base=
639 ! _ref_hash_base="$(ref_exists_rev "refs/$topbases/$1")" || _is_tgish=1
640 [ -z "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
642 # If no_remotes is unset also check our base against remote base.
643 # Checking our head against remote head has to be done in the helper.
644 if [ -n "$_is_tgish" -a -z "$no_remotes" ] && has_remote "$topbases/$1"; then
645 echo "0 0 refs/remotes/$base_remote/$topbases/$1 $*"
648 # if the branch was annihilated, it is considered to have no dependencies
649 if [ -n "$_is_tgish" ] && ! branch_annihilated "$1" "$_ref_hash" "$_ref_hash_base"; then
650 #TODO: handle nonexisting .topdeps?
651 cat_deps "$1" |
652 while read _dname; do
653 # Avoid depedency loops
654 case " $* " in *" $_dname "*)
655 warn "dependency loop detected in branch $_dname"
656 continue
657 esac
658 # Shoo shoo, leave our environment alone!
659 (recurse_deps_internal "$_dname" "$@")
660 done
663 [ -n "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
666 # do_eval CMD
667 # helper for recurse_deps so that a return statement executed inside CMD
668 # does not return from recurse_deps. This shouldn't be necessary, but it
669 # seems that it actually is.
670 do_eval()
672 eval "$@"
675 # becomes read-only for caching purposes
676 # assigns new value to tg_read_only
677 # become_cacheable/undo_become_cacheable calls may be nested
678 become_cacheable()
680 _old_tg_read_only="$tg_read_only"
681 if [ -z "$tg_read_only" ]; then
682 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
683 tg_read_only=1
685 _my_ref_cache="$(create_ref_cache 1)"
686 _my_ref_cache="${_my_ref_cache:+1}"
687 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
690 # restores tg_read_only and ref_cache to state before become_cacheable call
691 # become_cacheable/undo_bocome_cacheable calls may be nested
692 undo_become_cacheable()
694 case "$tg_read_only" in
695 "undo"[01]"-"*)
696 _suffix="${tg_read_only#undo?-}"
697 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
698 tg_read_only="$_suffix"
699 esac
702 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
703 become_non_cacheable()
705 remove_ref_cache
706 tg_read_only=
707 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
710 # call this to make sure Git will not complain about a missing user/email
711 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
712 ensure_ident_available()
714 [ -z "$TG_IDENT_CHECKED" ] || return 0
715 git var GIT_AUTHOR_IDENT >/dev/null &&
716 git var GIT_COMMITTER_IDENT >/dev/null || exit
717 TG_IDENT_CHECKED=1
718 export TG_IDENT_CHECKED
719 return 0
722 # recurse_deps CMD NAME [BRANCHPATH...]
723 # Recursively eval CMD on all dependencies of NAME.
724 # Dependencies are visited in topological order.
725 # CMD can refer to $_name for queried branch name,
726 # $_dep for dependency name,
727 # $_depchain for space-seperated branch backtrace,
728 # $_dep_missing boolean to check whether $_dep is present
729 # and the $_dep_is_tgish boolean.
730 # It can modify $_ret to affect the return value
731 # of the whole function.
732 # If recurse_deps() hits missing dependencies, it will append
733 # them to space-separated $missing_deps list and skip them
734 # after calling CMD with _dep_missing set.
735 # remote dependencies are processed if no_remotes is unset.
736 # any branch names in the space-separated recurse_deps_exclude variable
737 # are skipped (along with their dependencies)
738 recurse_deps()
740 _cmd="$1"; shift
742 become_cacheable
743 _depsfile="$(get_temp tg-depsfile)"
744 recurse_deps_internal "$@" >>"$_depsfile"
745 undo_become_cacheable
747 _ret=0
748 while read _ismissing _istgish _dep _name _deppath; do
749 _depchain="$_name${_deppath:+ $_deppath}"
750 _dep_is_tgish=
751 [ "$_istgish" = "0" ] || _dep_is_tgish=1
752 _dep_missing=
753 if [ "$_ismissing" != "0" ]; then
754 _dep_missing=1
755 case " $missing_deps " in *" $_dep "*) :;; *)
756 missing_deps="${missing_deps:+$missing_deps }$_dep"
757 esac
759 do_eval "$_cmd"
760 done <"$_depsfile"
761 rm -f "$_depsfile"
762 return $_ret
765 # branch_needs_update
766 # This is a helper function for determining whether given branch
767 # is up-to-date wrt. its dependencies. It expects input as if it
768 # is called as a recurse_deps() helper.
769 # In case the branch does need update, it will echo it together
770 # with the branch backtrace on the output (see needs_update()
771 # description for details) and set $_ret to non-zero.
772 branch_needs_update()
774 if [ -n "$_dep_missing" ]; then
775 echo "! $_dep $_depchain"
776 return 0
779 if [ -n "$_dep_is_tgish" ]; then
780 branch_annihilated "$_dep" && return 0
782 if has_remote "$_dep"; then
783 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
784 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
786 # We want to sync with our base first and should output this before
787 # the remote branch, but the order does not actually matter to tg-update
788 # as it just recurses regardless, but it does matter for tg-info (which
789 # treats out-of-date bases as though they were already merged in) so
790 # we output the remote before the base.
791 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
792 echo ": $_dep $_depchain"
793 _ret=1
794 return
798 if [ -n "$_name" ]; then
799 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
800 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
801 # Some new commits in _dep
802 echo "$_dep $_depchain"
803 _ret=1
808 # needs_update NAME
809 # This function is recursive; it outputs reverse path from NAME
810 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
811 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
812 # if the head is not in sync with the <remote> branch <name>, ':' if
813 # the head is not in sync with the base (in this order of priority)
814 # or '!' if dependency is missing. Note that the remote branch, base
815 # order is reversed from the order they will actually be updated in
816 # order to accomodate tg info which treats out-of-date items that are
817 # only in the base as already being in the head for status purposes.
818 # It will also return non-zero status if NAME needs update.
819 # If needs_update() hits missing dependencies, it will append
820 # them to space-separated $missing_deps list and skip them.
821 needs_update()
823 recurse_deps branch_needs_update "$1"
826 # branch_empty NAME [-i | -w]
827 branch_empty()
829 if [ -z "$2" ]; then
830 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
831 _result=
832 _result_rev=
833 { read -r _result _result_rev <"$tg_cache_dir/$1/.mt"; } 2>/dev/null || :
834 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
835 _result=0
836 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ] || _result=$?
837 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null
838 [ ! -d "$tg_cache_dir/$1" ] || echo $_result $_rev >"$tg_cache_dir/$1/.mt"
839 return $_result
840 else
841 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ]
845 # list_deps [-i | -w] [BRANCH]
846 # -i/-w apply only to HEAD
847 list_deps()
849 head_from=
850 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
851 head="$(git symbolic-ref -q HEAD)" ||
852 head="..detached.."
854 git for-each-ref --format='%(objectname) %(refname)' "refs/$topbases${1:+/$1}" |
855 while read rev ref; do
856 name="${ref#refs/$topbases/}"
857 if branch_annihilated "$name" "" "$rev"; then
858 continue
861 from=$head_from
862 [ "refs/heads/$name" = "$head" ] ||
863 from=
864 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
865 dep_is_tgish=true
866 ref_exists "refs/$topbases/$dep" ||
867 dep_is_tgish=false
868 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
869 echo "$name $dep"
871 done
872 done
875 # switch_to_base NAME [SEED]
876 switch_to_base()
878 _base="refs/$topbases/$1"; _seed="$2"
879 # We have to do all the hard work ourselves :/
880 # This is like git checkout -b "$_base" "$_seed"
881 # (or just git checkout "$_base"),
882 # but does not create a detached HEAD.
883 git read-tree -u -m HEAD "${_seed:-$_base}"
884 [ -z "$_seed" ] || git update-ref "$_base" "$_seed"
885 git symbolic-ref HEAD "$_base"
888 # run editor with arguments
889 # the editor setting will be cached in $tg_editor (which is eval'd)
890 # result non-zero if editor fails or GIT_EDITOR cannot be determined
891 run_editor()
893 tg_editor="$GIT_EDITOR"
894 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
895 eval "$tg_editor" '"$@"'
898 # Show the help messages.
899 do_help()
901 _www=
902 if [ "$1" = "-w" ]; then
903 _www=1
904 shift
906 if [ -z "$1" ] ; then
907 # This is currently invoked in all kinds of circumstances,
908 # including when the user made a usage error. Should we end up
909 # providing more than a short help message, then we should
910 # differentiate.
911 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
913 ## Build available commands list for help output
915 cmds=
916 sep=
917 for cmd in "$TG_INST_CMDDIR"/tg-*; do
918 ! [ -r "$cmd" ] && continue
919 # strip directory part and "tg-" prefix
920 cmd="$(basename "$cmd")"
921 cmd="${cmd#tg-}"
922 cmds="$cmds$sep$cmd"
923 sep="|"
924 done
926 echo "TopGit version $TG_VERSION - A different patch queue manager"
927 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
928 echo " Or: $tgname help [-w] [<command>]"
929 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
930 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
931 if [ -n "$_www" ]; then
932 nohtml=
933 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
934 echo "$(basename "$0"): missing html help file:" \
935 "$TG_INST_SHAREDIR/topgit.html" 1>&2
936 nohtml=1
938 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
939 echo "$(basename "$0"): missing html help file:" \
940 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
941 nohtml=1
943 if [ -n "$nohtml" ]; then
944 echo "$(basename "$0"): use" \
945 "\"$(basename "$0") help $1\" instead" 1>&2
946 exit 1
948 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
949 exit
951 output()
953 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
954 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
955 echo
957 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
958 cat "$TG_INST_SHAREDIR/tg-$1.txt"
961 page output "$1"
962 else
963 echo "$(basename "$0"): no help for $1" 1>&2
964 do_help
965 exit 1
969 ## Pager stuff
971 # isatty FD
972 isatty()
974 test -t $1
977 # pass "diff" to get pager.diff
978 # if pager.$1 is a boolean false returns cat
979 # if set to true or unset fails
980 # otherwise succeeds and returns the value
981 get_pager()
983 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
984 [ "$_x" != "true" ] || return 1
985 echo "cat"
986 return 0
988 if _x="$(git config "pager.$1" 2>/dev/null)"; then
989 echol "$_x"
990 return 0
992 return 1
995 # setup_pager
996 # Set TG_PAGER to a valid executable
997 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
998 # See also the following "page" function for ease of use
999 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1000 # Preference is (same as Git):
1001 # 1. GIT_PAGER
1002 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1003 # 3. core.pager (only if set)
1004 # 4. PAGER
1005 # 5. git var GIT_PAGER
1006 # 6. less
1007 setup_pager()
1009 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1011 emptypager=
1012 if [ -z "$TG_PAGER_IN_USE" ]; then
1013 # TG_PAGER = GIT_PAGER | PAGER | less
1014 # NOTE: GIT_PAGER='' is significant
1015 if [ -n "${GIT_PAGER+set}" ]; then
1016 TG_PAGER="$GIT_PAGER"
1017 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1018 TG_PAGER="$_dp"
1019 elif _cp="$(git config core.pager 2>/dev/null)"; then
1020 TG_PAGER="$_cp"
1021 elif [ -n "${PAGER+set}" ]; then
1022 TG_PAGER="$PAGER"
1023 else
1024 _gp="$(git var GIT_PAGER 2>/dev/null || :)"
1025 [ "$_gp" != ":" ] || _gp=
1026 TG_PAGER="${_gp:-less}"
1028 if [ -z "$TG_PAGER" ]; then
1029 emptypager=1
1030 TG_PAGER=cat
1032 else
1033 emptypager=1
1034 TG_PAGER=cat
1037 # Set pager default environment variables
1038 # see pager.c:setup_pager
1039 if [ -z "${LESS+set}" ]; then
1040 LESS="-FRX"
1041 export LESS
1043 if [ -z "${LV+set}" ]; then
1044 LV="-c"
1045 export LV
1048 # this is needed so e.g. $(git diff) will still colorize it's output if
1049 # requested in ~/.gitconfig with color.diff=auto
1050 GIT_PAGER_IN_USE=1
1051 export GIT_PAGER_IN_USE
1053 # this is needed so we don't get nested pagers
1054 TG_PAGER_IN_USE=1
1055 export TG_PAGER_IN_USE
1058 # page eval_arg [arg ...]
1060 # Calls setup_pager then evals the first argument passing it all the rest
1061 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1062 # by setup_pager (in which case the output is left as-is).
1064 # To handle arbitrary paging duties, collect lines to be paged into a
1065 # function and then call page with the function name or perhaps func_name "$@".
1067 # If no arguments at all are passed in do nothing (return with success).
1068 page()
1070 [ $# -gt 0 ] || return 0
1071 setup_pager
1072 _evalarg="$1"; shift
1073 if [ -n "$emptypager" ]; then
1074 eval "$_evalarg" '"$@"'
1075 else
1076 eval "$_evalarg" '"$@"' | eval "$TG_PAGER"
1080 # get_temp NAME [-d]
1081 # creates a new temporary file (or directory with -d) in the global
1082 # temporary directory $tg_tmp_dir with pattern prefix NAME
1083 get_temp()
1085 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1088 # automatically called by strftime
1089 # does nothing if already setup
1090 # may be called explicitly if the first call would otherwise be in a subshell
1091 # so that the setup is only done once before subshells start being spawned
1092 setup_strftime()
1094 [ -z "$strftime_is_setup" ] || return 0
1096 # date option to format raw epoch seconds values
1097 daterawopt=
1098 _testes='951807788'
1099 _testdt='2000-02-29 07:03:08 UTC'
1100 _testfm='%Y-%m-%d %H:%M:%S %Z'
1101 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1102 daterawopt='-d@'
1103 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1104 daterawopt='-r'
1106 strftime_is_setup=1
1109 # $1 => strftime format string to use
1110 # $2 => raw timestamp as seconds since epoch
1111 # $3 => optional time zone string (empty/absent for local time zone)
1112 strftime()
1114 setup_strftime
1115 if [ -n "$daterawopt" ]; then
1116 if [ -n "$3" ]; then
1117 TZ="$3" date "$daterawopt$2" "+$1"
1118 else
1119 date "$daterawopt$2" "+$1"
1121 else
1122 if [ -n "$3" ]; then
1123 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1124 else
1125 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1130 ## Initial setup
1131 initial_setup()
1133 # suppress the merge log editor feature since git 1.7.10
1135 GIT_MERGE_AUTOEDIT=no
1136 export GIT_MERGE_AUTOEDIT
1138 auhopt=
1139 [ "$(vcmp "$git_vernum" 2.9)" -lt 0 ] || auhopt="--allow-unrelated-histories"
1140 git_dir="$(git rev-parse --git-dir)"
1141 root_dir="$(git rev-parse --show-cdup)"; root_dir="${root_dir:-.}"
1142 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null || :)"
1143 [ "$logrefupdates" = "true" ] || logrefupdates=
1144 tgsequester="$(git config --bool topgit.sequester 2>/dev/null || :)"
1145 tgnosequester=
1146 [ "$tgsequester" != "false" ] || tgnosequester=1
1147 unset tgsequester
1149 # make sure root_dir doesn't end with a trailing slash.
1151 root_dir="${root_dir%/}"
1152 [ -n "$base_remote" ] || base_remote="$(git config topgit.remote 2>/dev/null)" || :
1154 # make sure global cache directory exists inside GIT_DIR
1156 tg_cache_dir="$git_dir/tg-cache"
1157 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir"
1159 # create global temporary directories, inside GIT_DIR
1161 tg_tmp_dir=
1162 trap 'rm -rf "$tg_tmp_dir"' EXIT
1163 trap 'exit 129' HUP
1164 trap 'exit 130' INT
1165 trap 'exit 131' QUIT
1166 trap 'exit 134' ABRT
1167 trap 'exit 143' TERM
1168 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX")"
1169 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1171 # refer to "top-bases" in a refname with $topbases
1173 topbases="top-bases"
1176 # return the "realpath" for the item except the leaf is not resolved if it's
1177 # a symbolic link. The directory part must exist, but the basename need not.
1178 get_abs_path()
1180 [ -n "$1" -a -d "$(dirname "$1")" ] || return 1
1181 printf '%s' "$(cd -- "$(dirname "$1")" && pwd -P)/$(basename "$1")"
1184 ## Startup
1186 : "${TG_INST_CMDDIR:=@cmddir@}"
1187 : "${TG_INST_SHAREDIR:=@sharedir@}"
1188 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1190 [ -d "$TG_INST_CMDDIR" ] ||
1191 die "No command directory: '$TG_INST_CMDDIR'"
1193 if [ -n "$tg__include" ]; then
1195 # We were sourced from another script for our utility functions;
1196 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1197 # work as expected in every shell. See http://bugs.debian.org/516188
1199 # ensure setup happens
1201 initial_setup
1203 else
1205 set -e
1207 tg="$0"
1208 tgdir="$(dirname "$tg")/"
1209 tgname="$(basename "$tg")"
1210 [ "$0" != "$tgname" ] || tgdir=""
1212 # If tg contains a '/' but does not start with one then replace it with an absolute path
1214 case "$0" in /*) :;; */*)
1215 tgdir="$(cd "$(dirname "$0")" && pwd -P)/"
1216 tg="$tgdir$tgname"
1217 esac
1219 # If the tg in the PATH is the same as "$tg" just display the basename
1220 # tgdisplay will include any explicit -C <dir> option whereas tg will not
1222 tgdisplaydir="$tgdir"
1223 tgdisplay="$tg"
1224 if [ "$(get_abs_path "$tg")" = "$(get_abs_path "$(cmd_path "$tgname" || :)" || :)" ]; then
1225 tgdisplaydir=""
1226 tgdisplay="$tgname"
1229 explicit_remote=
1230 explicit_dir=
1231 gitcdopt=
1232 noremote=
1234 cmd=
1235 while :; do case "$1" in
1237 help|--help|-h)
1238 cmd=help
1239 shift
1240 break;;
1242 --hooks-path)
1243 cmd=hooks-path
1244 shift
1245 break;;
1248 shift
1249 if [ -z "$1" ]; then
1250 echo "Option -r requires an argument." >&2
1251 do_help
1252 exit 1
1254 unset noremote
1255 base_remote="$1"
1256 explicit_remote="$base_remote"
1257 tg="$tgdir$tgname -r $explicit_remote"
1258 tgdisplay="$tgdisplaydir$tgname"
1259 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1260 tgdisplay="$tgdisplay -r $explicit_remote"
1261 shift;;
1264 unset base_remote explicit_remote
1265 noremote=1
1266 tg="$tgdir$tgname -u"
1267 tgdisplay="$tgdisplaydir$tgname"
1268 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1269 tgdisplay="$tgdisplay -u"
1270 shift;;
1273 shift
1274 if [ -z "$1" ]; then
1275 echo "Option -C requires an argument." >&2
1276 do_help
1277 exit 1
1279 cd "$1"
1280 unset GIT_DIR
1281 explicit_dir="$1"
1282 gitcdopt=" -C \"$explicit_dir\""
1283 tg="$tgdir$tgname"
1284 tgdisplay="$tgdisplaydir$tgname -C \"$explicit_dir\""
1285 [ -z "$explicit_remote" ] || tg="$tg -r $explicit_remote"
1286 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
1287 [ -z "$noremote" ] || tg="$tg -u"
1288 [ -z "$noremote" ] || tg="$tgdisplay -u"
1289 shift;;
1292 shift
1293 if [ -z "$1" ]; then
1294 echo "Option -c requires an argument." >&2
1295 do_help
1296 exit 1
1298 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
1299 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
1300 export GIT_CONFIG_PARAMETERS
1301 shift;;
1304 shift
1305 break;;
1308 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
1309 do_help
1310 exit 1;;
1313 break;;
1315 esac; done
1317 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
1319 ## Dispatch
1321 [ -n "$cmd" ] || { do_help; exit 1; }
1323 case "$cmd" in
1325 help)
1326 do_help "$@"
1327 exit 0;;
1329 hooks-path)
1330 # Internal command
1331 echol "$TG_INST_HOOKSDIR";;
1334 [ -r "$TG_INST_CMDDIR"/tg-$cmd ] || {
1335 echo "Unknown subcommand: $cmd" >&2
1336 do_help
1337 exit 1
1340 initial_setup
1341 [ -z "$noremote" ] || unset base_remote
1343 nomergesetup=
1344 case "$cmd" in info|log|summary|rebase|revert|tag)
1345 # avoid merge setup where not necessary
1347 nomergesetup=1
1348 esac
1350 if [ -z "$nomergesetup" ]; then
1351 # make sure merging the .top* files will always behave sanely
1353 setup_ours
1354 setup_hook "pre-commit"
1357 _use_ref_cache=
1358 tg_read_only=1
1359 case "$cmd" in
1360 summary|info|export|tag)
1361 _use_ref_cache=1;;
1362 annihilate|create|delete|depend|import|update)
1363 tg_read_only=;;
1364 esac
1365 [ -z "$_use_ref_cache" ] || create_ref_cache
1367 . "$TG_INST_CMDDIR"/tg-$cmd;;
1368 esac
1372 # vim:noet