tg: replace `...` with $(...)
[topgit/pro.git] / tg.sh
blob950d338645b9bf91540e98d98717213a4cd4b1b4
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 if you add any code that requires a newer version of git
11 GIT_MINIMUM_VERSION=1.8.5
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 # Output arguments without any possible interpretation
31 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
32 echol()
34 printf '%s\n' "$*"
37 info()
39 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
42 warn()
44 info "warning: $*" >&2
47 err()
49 info "error: $*" >&2
52 die()
54 info "fatal: $*" >&2
55 exit 1
58 wc_l()
60 echo $(wc -l)
63 vcmp()
65 # Compare $1 to $2 each of which must match \d+(\.\d+)*
66 # An empty string ('') for $1 or $2 is treated like 0
67 # Outputs:
68 # -1 if $1 < $2
69 # 0 if $1 = $2
70 # 1 if $1 > $2
71 # Note that $(vcmp 1.8 1.8.0.0.0.0) correctly outputs 0.
72 while
73 _a="${1%%.*}"
74 _b="${2%%.*}"
75 [ -n "$_a" -o -n "$_b" ]
77 if [ "${_a:-0}" -lt "${_b:-0}" ]; then
78 echo -1
79 return
80 elif [ "${_a:-0}" -gt "${_b:-0}" ]; then
81 echo 1
82 return
84 _a2="${1#$_a}"
85 _b2="${2#$_b}"
86 set -- "${_a2#.}" "${_b2#.}"
87 done
88 echo 0
91 precheck() {
92 if ! git_version="$(git version)"; then
93 die "'git version' failed"
95 case "$git_version" in
96 [Gg]"it version "*) :;;
98 die "'git version' output does not start with 'git version '"
99 esac
100 git_vernum="$(echo "$git_version" | sed -ne 's/^[^0-9]*\([0-9][0-9]*\(\.[0-9][0-9]*\)*\).*$/\1/p')"
102 [ "$(vcmp "$git_vernum" $GIT_MINIMUM_VERSION)" -ge 0 ] ||
103 die "git version >= $GIT_MINIMUM_VERSION required but found git version $git_vernum instead"
106 case "$1" in version|--version|-V)
107 echo "TopGit version $TG_VERSION"
108 exit 0
109 esac
111 precheck
112 [ "$1" = "precheck" ] && exit 0
115 cat_depsmsg_internal()
117 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
118 if [ -s "$tg_cache_dir/$1/.$2" ]; then
119 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
120 _line=
121 while IFS= read -r _line || [ -n "$_line" ]; do
122 printf '%s\n' "$_line"
123 done
124 return 0
125 fi <"$tg_cache_dir/$1/.$2"
127 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null || :
128 if [ -d "$tg_cache_dir/$1" ]; then
129 printf '%s\n' "$_rev" >"$tg_cache_dir/$1/.$2"
130 _line=
131 git cat-file blob "$_rev:.$2" 2>/dev/null |
132 while IFS= read -r _line || [ -n "$_line" ]; do
133 printf '%s\n' "$_line" >&3
134 printf '%s\n' "$_line"
135 done 3>>"$tg_cache_dir/$1/.$2"
136 else
137 git cat-file blob "$_rev:.$2" 2>/dev/null
141 # cat_deps BRANCHNAME
142 # Caches result
143 cat_deps()
145 cat_depsmsg_internal "$1" topdeps
148 # cat_msg BRANCHNAME
149 # Caches result
150 cat_msg()
152 cat_depsmsg_internal "$1" topmsg
155 # cat_file TOPIC:PATH [FROM]
156 # cat the file PATH from branch TOPIC when FROM is empty.
157 # FROM can be -i or -w, than the file will be from the index or worktree,
158 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
159 cat_file()
161 path="$1"
162 case "$2" in
164 cat "$root_dir/${path#*:}"
167 # ':file' means cat from index
168 git cat-file blob ":${path#*:}"
171 case "$path" in
172 refs/heads/*:.topdeps)
173 _temp="${path%:.topdeps}"
174 cat_deps "${_temp#refs/heads/}"
176 refs/heads/*:.topmsg)
177 _temp="${path%:.topmsg}"
178 cat_msg "${_temp#refs/heads/}"
181 git cat-file blob "$path"
183 esac
186 die "Wrong argument to cat_file: '$2'"
188 esac
191 # get tree for the committed topic
192 get_tree_()
194 echo "refs/heads/$1"
197 # get tree for the base
198 get_tree_b()
200 echo "refs/$topbases/$1"
203 # get tree for the index
204 get_tree_i()
206 git write-tree
209 # get tree for the worktree
210 get_tree_w()
212 i_tree=$(git write-tree)
214 # the file for --index-output needs to sit next to the
215 # current index file
216 cd "$root_dir"
217 : ${GIT_INDEX_FILE:="$git_dir/index"}
218 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
219 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
220 GIT_INDEX_FILE="$TMP_INDEX" &&
221 export GIT_INDEX_FILE &&
222 git diff --name-only -z HEAD |
223 git update-index -z --add --remove --stdin &&
224 git write-tree &&
225 rm -f "$TMP_INDEX"
229 # strip_ref "$(git symbolic-ref HEAD)"
230 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
231 strip_ref()
233 case "$1" in
234 refs/heads/*)
235 echol "${1#refs/heads/}"
237 refs/"$topbases"/*)
238 echol "${1#refs/$topbases/}"
241 echol "$1"
242 esac
245 # pretty_tree NAME [-b | -i | -w]
246 # Output tree ID of a cleaned-up tree without tg's artifacts.
247 # NAME will be ignored for -i and -w, but needs to be present
248 pretty_tree()
250 name=$1
251 source=${2#?}
252 git ls-tree --full-tree "$(get_tree_$source "$name")" |
253 LC_ALL=C sed -ne '/ \.top.*$/!p' |
254 git mktree
257 # return an empty-tree root commit -- date is either passed in or current
258 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
259 # An invalid secs causes the current date to be used, an invalid zone offset
260 # causes +0000 to be used
261 make_empty_commit()
263 # the empty tree is guaranteed to always be there even in a repo with
264 # zero objects, but for completeness we force it to exist as a real object
265 SECS=
266 read -r SECS ZONE JUNK <<-EOT || :
269 case "$SECS" in *[!0-9]*) SECS=; esac
270 if [ -z "$SECS" ]; then
271 MTDATE="$(date '+%s %z')"
272 else
273 case "$ZONE" in
274 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
276 [01][0-9][0-5][0-9])
277 ZONE="+$ZONE"
280 ZONE="+0000"
281 esac
282 MTDATE="$SECS $ZONE"
284 EMPTYID="- <-> $MTDATE"
285 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
286 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
287 git hash-object -t commit -w --stdin
290 # setup_hook NAME
291 setup_hook()
293 tgname="$(basename "$0")"
294 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
295 if [ -f "$git_dir/hooks/$1" ] && fgrep -q "$hook_call" "$git_dir/hooks/$1"; then
296 # Another job well done!
297 return
299 # Prepare incantation
300 hook_chain=
301 if [ -s "$git_dir/hooks/$1" -a -x "$git_dir/hooks/$1" ]; then
302 hook_call="$hook_call"' || exit $?'
303 if ! LC_ALL=C sed -n 1p <"$git_dir/hooks/$1" | LC_ALL=C fgrep -qx "#!@SHELL_PATH@"; then
304 chain_num=
305 while [ -e "$git_dir/hooks/$1-chain$chain_num" ]; do
306 chain_num=$(( $chain_num + 1 ))
307 done
308 cp -p "$git_dir/hooks/$1" "$git_dir/hooks/$1-chain$chain_num"
309 hook_chain=1
311 else
312 hook_call="exec $hook_call"
314 # Don't call hook if tg is not installed
315 hook_call="if which \"$tgname\" > /dev/null; then $hook_call; fi"
316 # Insert call into the hook
318 echol "#!@SHELL_PATH@"
319 echol "$hook_call"
320 if [ -n "$hook_chain" ]; then
321 echol "exec \"\$0-chain$chain_num\" \"\$@\""
322 else
323 [ ! -s "$git_dir/hooks/$1" ] || cat "$git_dir/hooks/$1"
325 } >"$git_dir/hooks/$1+"
326 chmod a+x "$git_dir/hooks/$1+"
327 mv "$git_dir/hooks/$1+" "$git_dir/hooks/$1"
330 # setup_ours (no arguments)
331 setup_ours()
333 if [ ! -s "$git_dir/info/attributes" ] || ! grep -q topmsg "$git_dir/info/attributes"; then
334 [ -d "$git_dir/info" ] || mkdir "$git_dir/info"
336 echo ".topmsg merge=ours"
337 echo ".topdeps merge=ours"
338 } >>"$git_dir/info/attributes"
340 if ! git config merge.ours.driver >/dev/null; then
341 git config merge.ours.name '"always keep ours" merge driver'
342 git config merge.ours.driver 'touch %A'
346 # measure_branch NAME [BASE] [EXTRAHEAD...]
347 measure_branch()
349 _bname="$1"; _base="$2"
350 shift; shift
351 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
352 # The caller should've verified $name is valid
353 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
354 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
355 if [ $_commits -ne 1 ]; then
356 _suffix="commits"
357 else
358 _suffix="commit"
360 echo "$_commits/$_nmcommits $_suffix"
363 # branch_contains B1 B2
364 # Whether B1 is a superset of B2.
365 branch_contains()
367 _revb1="$(ref_exists_rev "$1")" || return 0
368 _revb2="$(ref_exists_rev "$2")" || return 0
369 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
370 if read _result _rev_matchb1 _rev_matchb2 &&
371 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
372 return $_result
373 fi <"$tg_cache_dir/$1/.bc/$2/.d"
375 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
376 _result=0
377 [ -z "$(git rev-list --max-count=1 ^"$_revb1" "$_revb2" --)" ] || _result=$?
378 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
379 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
381 return $_result
384 create_ref_dirs()
386 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
387 sed -e 's/ .*$//;'"s~^~$tg_tmp_dir/cached/~" <"$tg_ref_cache" | xargs mkdir -p
388 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
391 # If the first argument is non-empty, outputs "1" if this call created the cache
392 create_ref_cache()
394 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
395 _remotespec=
396 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
397 [ -z "$1" ] || printf '1'
398 git for-each-ref --format='%(refname) %(objectname)' \
399 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
400 create_ref_dirs
403 remove_ref_cache()
405 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
406 >"$tg_ref_cache"
409 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
410 rev_parse()
412 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
413 LC_ALL=C awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
414 else
415 [ -z "$tg_ref_cache_only" ] || return 1
416 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
420 # ref_exists_rev REF
421 # Whether REF is a valid ref name
422 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
423 # or, if $base_remote is set, refs/remotes/$base_remote/
424 # Caches result if $tg_read_only and outputs HASH on success
425 ref_exists_rev()
427 case "$1" in
428 refs/*)
430 $octet20)
431 printf '%s' "$1"
432 return;;
434 die "ref_exists_rev requires fully-qualified ref name"
435 esac
436 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
437 _result=
438 _result_rev=
439 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
440 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
441 _result_rev="$(rev_parse "$1")"
442 _result=$?
443 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
444 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
445 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
446 printf '%s' "$_result_rev"
447 return $_result
450 # Same as ref_exists_rev but output is abbreviated hash
451 ref_exists_rev_short()
453 case "$1" in
454 refs/*)
456 $octet20)
459 die "ref_exists_rev_short requires fully-qualified ref name"
460 esac
461 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify --short "$1^0" -- 2>/dev/null; return; }
462 _result=
463 _result_rev=
464 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
465 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
466 _result_rev="$(rev_parse "$1")"
467 _result=$?
468 if [ $_result -eq 0 ]; then
469 _result_rev="$(git rev-parse --verify --short --quiet "$_result_rev" --)"
470 _result=$?
472 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
473 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
474 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
475 printf '%s' "$_result_rev"
476 return $_result
479 # ref_exists REF
480 # Whether REF is a valid ref name
481 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
482 # or, if $base_remote is set, refs/remotes/$base_remote/
483 # Caches result
484 ref_exists()
486 ref_exists_rev "$1" >/dev/null
489 # rev_parse_tree REF
490 # Runs git rev-parse REF^{tree}
491 # Caches result if $tg_read_only
492 rev_parse_tree()
494 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
495 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
496 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
497 printf '%s\n' "$_result"
498 return 0
500 return 1
502 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
503 if [ -d "$tg_tmp_dir/cached/$1" ]; then
504 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
505 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
506 printf '%s\n' "$_result"
507 return 0
509 return 1
511 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
514 # has_remote BRANCH
515 # Whether BRANCH has a remote equivalent (accepts $topbases/ too)
516 has_remote()
518 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
521 # Return the verified TopGit branch name or die with an error.
522 # As a convenience, if HEAD is given and HEAD is a symbolic ref to
523 # refs/heads/... then ... will be verified instead.
524 # if "$2" = "-f" (for fail) then return an error rather than dying.
525 verify_topgit_branch()
527 case "$1" in
528 refs/heads/*)
529 _verifyname="${1#refs/heads/}"
531 refs/"$topbases"/*)
532 _verifyname="${1#refs/$topbases/}"
534 HEAD)
535 _verifyname="$(git symbolic-ref HEAD 2>/dev/null || :)"
536 [ -n "$_verifyname" -o "$2" = "-f" ] || die "HEAD is not a symbolic ref"
537 case "$_verifyname" in refs/heads/*) :;; *)
538 [ "$2" != "-f" ] || return 1
539 die "HEAD is not a symbolic ref to the refs/heads namespace"
540 esac
541 _verifyname="${_verifyname#refs/heads/}"
544 _verifyname="$1"
546 esac
547 if ! ref_exists "refs/heads/$_verifyname"; then
548 [ "$2" != "-f" ] || return 1
549 die "no such branch: $_verifyname"
551 if ! ref_exists "refs/$topbases/$_verifyname"; then
552 [ "$2" != "-f" ] || return 1
553 die "not a TopGit-controlled branch: $_verifyname"
555 printf '%s' "$_verifyname"
558 # Caches result
559 # $1 = branch name (i.e. "t/foo/bar")
560 # $2 = optional result of rev-parse "refs/heads/$1"
561 # $3 = optional result of rev-parse "refs/$topbases/$1"
562 branch_annihilated()
564 _branch_name="$1"
565 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
566 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
568 _result=
569 _result_rev=
570 _result_rev_base=
571 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/$_branch_name/.ann"; } 2>/dev/null || :
572 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
574 # use the merge base in case the base is ahead.
575 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
577 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
578 _result=$?
579 [ -d "$tg_cache_dir/$_branch_name" ] || mkdir -p "$tg_cache_dir/$_branch_name" 2>/dev/null
580 [ ! -d "$tg_cache_dir/$_branch_name" ] ||
581 echo $_result $_rev $_rev_base >"$tg_cache_dir/$_branch_name/.ann" 2>/dev/null || :
582 return $_result
585 non_annihilated_branches()
587 [ $# -gt 0 ] || set -- "refs/$topbases"
588 git for-each-ref --format='%(objectname) %(refname)' "$@" |
589 while read rev ref; do
590 name="${ref#refs/$topbases/}"
591 if branch_annihilated "$name" "" "$rev"; then
592 continue
594 echol "$name"
595 done
598 # Make sure our tree is clean
599 ensure_clean_tree()
601 git update-index --ignore-submodules --refresh ||
602 die "the working directory has uncommitted changes (see above) - first commit or reset them"
603 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
604 die "the index has uncommited changes"
607 # is_sha1 REF
608 # Whether REF is a SHA1 (compared to a symbolic name).
609 is_sha1()
611 case "$1" in $octet20) return 0;; esac
612 return 1
615 # recurse_deps_internal NAME [BRANCHPATH...]
616 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
617 # followed by a 1 if the branch is "tgish" or a 0 if not
618 # then the branch name followed by its depedency chain (which might be empty)
619 # An output line might look like this:
620 # 0 1 t/foo/leaf t/foo/int t/stage
621 # If no_remotes is non-empty, exclude remotes
622 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
623 # any branch names in the space-separated recurse_deps_exclude variable
624 # are skipped (along with their dependencies)
625 recurse_deps_internal()
627 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
628 _ref_hash=
629 if ! _ref_hash="$(ref_exists_rev "refs/heads/$1")"; then
630 [ -z "$2" ] || echo "1 0 $*"
631 return
634 _is_tgish=0
635 _ref_hash_base=
636 ! _ref_hash_base="$(ref_exists_rev "refs/$topbases/$1")" || _is_tgish=1
637 [ -z "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
639 # If no_remotes is unset also check our base against remote base.
640 # Checking our head against remote head has to be done in the helper.
641 if [ -n "$_is_tgish" -a -z "$no_remotes" ] && has_remote "$topbases/$1"; then
642 echo "0 0 refs/remotes/$base_remote/$topbases/$1 $*"
645 # if the branch was annihilated, it is considered to have no dependencies
646 if [ -n "$_is_tgish" ] && ! branch_annihilated "$1" "$_ref_hash" "$_ref_hash_base"; then
647 #TODO: handle nonexisting .topdeps?
648 cat_deps "$1" |
649 while read _dname; do
650 # Avoid depedency loops
651 case " $* " in *" $_dname "*)
652 warn "dependency loop detected in branch $_dname"
653 continue
654 esac
655 # Shoo shoo, leave our environment alone!
656 (recurse_deps_internal "$_dname" "$@")
657 done
660 [ -n "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
663 # do_eval CMD
664 # helper for recurse_deps so that a return statement executed inside CMD
665 # does not return from recurse_deps. This shouldn't be necessary, but it
666 # seems that it actually is.
667 do_eval()
669 eval "$@"
672 # becomes read-only for caching purposes
673 # assigns new value to tg_read_only
674 # become_cacheable/undo_become_cacheable calls may be nested
675 become_cacheable()
677 _old_tg_read_only="$tg_read_only"
678 if [ -z "$tg_read_only" ]; then
679 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
680 tg_read_only=1
682 _my_ref_cache="$(create_ref_cache 1)"
683 _my_ref_cache="${_my_ref_cache:+1}"
684 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
687 # restores tg_read_only and ref_cache to state before become_cacheable call
688 # become_cacheable/undo_bocome_cacheable calls may be nested
689 undo_become_cacheable()
691 case "$tg_read_only" in
692 "undo"[01]"-"*)
693 _suffix="${tg_read_only#undo?-}"
694 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
695 tg_read_only="$_suffix"
696 esac
699 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
700 become_non_cacheable()
702 remove_ref_cache
703 tg_read_only=
704 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
707 # call this to make sure Git will not complain about a missing user/email
708 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
709 ensure_ident_available()
711 [ -z "$TG_IDENT_CHECKED" ] || return 0
712 git var GIT_AUTHOR_IDENT >/dev/null &&
713 git var GIT_COMMITTER_IDENT >/dev/null || exit
714 TG_IDENT_CHECKED=1
715 export TG_IDENT_CHECKED
716 return 0
719 # recurse_deps CMD NAME [BRANCHPATH...]
720 # Recursively eval CMD on all dependencies of NAME.
721 # Dependencies are visited in topological order.
722 # CMD can refer to $_name for queried branch name,
723 # $_dep for dependency name,
724 # $_depchain for space-seperated branch backtrace,
725 # $_dep_missing boolean to check whether $_dep is present
726 # and the $_dep_is_tgish boolean.
727 # It can modify $_ret to affect the return value
728 # of the whole function.
729 # If recurse_deps() hits missing dependencies, it will append
730 # them to space-separated $missing_deps list and skip them
731 # after calling CMD with _dep_missing set.
732 # remote dependencies are processed if no_remotes is unset.
733 # any branch names in the space-separated recurse_deps_exclude variable
734 # are skipped (along with their dependencies)
735 recurse_deps()
737 _cmd="$1"; shift
739 become_cacheable
740 _depsfile="$(get_temp tg-depsfile)"
741 recurse_deps_internal "$@" >>"$_depsfile"
742 undo_become_cacheable
744 _ret=0
745 while read _ismissing _istgish _dep _name _deppath; do
746 _depchain="$_name${_deppath:+ $_deppath}"
747 _dep_is_tgish=
748 [ "$_istgish" = "0" ] || _dep_is_tgish=1
749 _dep_missing=
750 if [ "$_ismissing" != "0" ]; then
751 _dep_missing=1
752 case " $missing_deps " in *" $_dep "*) :;; *)
753 missing_deps="${missing_deps:+$missing_deps }$_dep"
754 esac
756 do_eval "$_cmd"
757 done <"$_depsfile"
758 rm -f "$_depsfile"
759 return $_ret
762 # branch_needs_update
763 # This is a helper function for determining whether given branch
764 # is up-to-date wrt. its dependencies. It expects input as if it
765 # is called as a recurse_deps() helper.
766 # In case the branch does need update, it will echo it together
767 # with the branch backtrace on the output (see needs_update()
768 # description for details) and set $_ret to non-zero.
769 branch_needs_update()
771 if [ -n "$_dep_missing" ]; then
772 echo "! $_dep $_depchain"
773 return 0
776 if [ -n "$_dep_is_tgish" ]; then
777 branch_annihilated "$_dep" && return 0
779 if has_remote "$_dep"; then
780 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
781 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
783 # We want to sync with our base first and should output this before
784 # the remote branch, but the order does not actually matter to tg-update
785 # as it just recurses regardless, but it does matter for tg-info (which
786 # treats out-of-date bases as though they were already merged in) so
787 # we output the remote before the base.
788 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
789 echo ": $_dep $_depchain"
790 _ret=1
791 return
795 if [ -n "$_name" ]; then
796 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
797 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
798 # Some new commits in _dep
799 echo "$_dep $_depchain"
800 _ret=1
805 # needs_update NAME
806 # This function is recursive; it outputs reverse path from NAME
807 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
808 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
809 # if the head is not in sync with the <remote> branch <name>, ':' if
810 # the head is not in sync with the base (in this order of priority)
811 # or '!' if dependency is missing. Note that the remote branch, base
812 # order is reversed from the order they will actually be updated in
813 # order to accomodate tg info which treats out-of-date items that are
814 # only in the base as already being in the head for status purposes.
815 # It will also return non-zero status if NAME needs update.
816 # If needs_update() hits missing dependencies, it will append
817 # them to space-separated $missing_deps list and skip them.
818 needs_update()
820 recurse_deps branch_needs_update "$1"
823 # branch_empty NAME [-i | -w]
824 branch_empty()
826 if [ -z "$2" ]; then
827 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
828 _result=
829 _result_rev=
830 { read -r _result _result_rev <"$tg_cache_dir/$1/.mt"; } 2>/dev/null || :
831 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
832 _result=0
833 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ] || _result=$?
834 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null
835 [ ! -d "$tg_cache_dir/$1" ] || echo $_result $_rev >"$tg_cache_dir/$1/.mt"
836 return $_result
837 else
838 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ]
842 # list_deps [-i | -w] [BRANCH]
843 # -i/-w apply only to HEAD
844 list_deps()
846 head_from=
847 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
848 head="$(git symbolic-ref -q HEAD)" ||
849 head="..detached.."
851 git for-each-ref --format='%(objectname) %(refname)' "refs/$topbases${1:+/$1}" |
852 while read rev ref; do
853 name="${ref#refs/$topbases/}"
854 if branch_annihilated "$name" "" "$rev"; then
855 continue
858 from=$head_from
859 [ "refs/heads/$name" = "$head" ] ||
860 from=
861 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
862 dep_is_tgish=true
863 ref_exists "refs/$topbases/$dep" ||
864 dep_is_tgish=false
865 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
866 echo "$name $dep"
868 done
869 done
872 # switch_to_base NAME [SEED]
873 switch_to_base()
875 _base="refs/$topbases/$1"; _seed="$2"
876 # We have to do all the hard work ourselves :/
877 # This is like git checkout -b "$_base" "$_seed"
878 # (or just git checkout "$_base"),
879 # but does not create a detached HEAD.
880 git read-tree -u -m HEAD "${_seed:-$_base}"
881 [ -z "$_seed" ] || git update-ref "$_base" "$_seed"
882 git symbolic-ref HEAD "$_base"
885 # run editor with arguments
886 # the editor setting will be cached in $tg_editor (which is eval'd)
887 # result non-zero if editor fails or GIT_EDITOR cannot be determined
888 run_editor()
890 tg_editor="$GIT_EDITOR"
891 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
892 eval "$tg_editor" '"$@"'
895 # Show the help messages.
896 do_help()
898 _www=
899 if [ "$1" = "-w" ]; then
900 _www=1
901 shift
903 if [ -z "$1" ] ; then
904 # This is currently invoked in all kinds of circumstances,
905 # including when the user made a usage error. Should we end up
906 # providing more than a short help message, then we should
907 # differentiate.
908 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
910 ## Build available commands list for help output
912 cmds=
913 sep=
914 for cmd in "@cmddir@"/tg-*; do
915 ! [ -r "$cmd" ] && continue
916 # strip directory part and "tg-" prefix
917 cmd="$(basename "$cmd")"
918 cmd="${cmd#tg-}"
919 cmds="$cmds$sep$cmd"
920 sep="|"
921 done
923 echo "TopGit version $TG_VERSION - A different patch queue manager"
924 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
925 echo " Or: $tgname help [-w] [<command>]"
926 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
927 elif [ -r "@cmddir@"/tg-$1 -o -r "@sharedir@/tg-$1.txt" ] ; then
928 if [ -n "$_www" ]; then
929 nohtml=
930 if ! [ -r "@sharedir@/topgit.html" ]; then
931 echo "$(basename "$0"): missing html help file:" \
932 "@sharedir@/topgit.html" 1>&2
933 nohtml=1
935 if ! [ -r "@sharedir@/tg-$1.html" ]; then
936 echo "$(basename "$0"): missing html help file:" \
937 "@sharedir@/tg-$1.html" 1>&2
938 nohtml=1
940 if [ -n "$nohtml" ]; then
941 echo "$(basename "$0"): use" \
942 "\"$(basename "$0") help $1\" instead" 1>&2
943 exit 1
945 git web--browse -c help.browser "@sharedir@/tg-$1.html"
946 exit
948 output()
950 if [ -r "@cmddir@"/tg-$1 ] ; then
951 "@cmddir@"/tg-$1 -h 2>&1 || :
952 echo
954 if [ -r "@sharedir@/tg-$1.txt" ] ; then
955 cat "@sharedir@/tg-$1.txt"
958 page output "$1"
959 else
960 echo "$(basename "$0"): no help for $1" 1>&2
961 do_help
962 exit 1
966 ## Pager stuff
968 # isatty FD
969 isatty()
971 test -t $1
974 # pass "diff" to get pager.diff
975 # if pager.$1 is a boolean false returns cat
976 # if set to true or unset fails
977 # otherwise succeeds and returns the value
978 get_pager()
980 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
981 [ "$_x" != "true" ] || return 1
982 echo "cat"
983 return 0
985 if _x="$(git config "pager.$1" 2>/dev/null)"; then
986 echol "$_x"
987 return 0
989 return 1
992 # setup_pager
993 # Set TG_PAGER to a valid executable
994 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
995 # See also the following "page" function for ease of use
996 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
997 # Preference is (same as Git):
998 # 1. GIT_PAGER
999 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1000 # 3. core.pager (only if set)
1001 # 4. PAGER
1002 # 5. git var GIT_PAGER
1003 # 6. less
1004 setup_pager()
1006 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1008 emptypager=
1009 if [ -z "$TG_PAGER_IN_USE" ]; then
1010 # TG_PAGER = GIT_PAGER | PAGER | less
1011 # NOTE: GIT_PAGER='' is significant
1012 if [ -n "${GIT_PAGER+set}" ]; then
1013 TG_PAGER="$GIT_PAGER"
1014 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1015 TG_PAGER="$_dp"
1016 elif _cp="$(git config core.pager 2>/dev/null)"; then
1017 TG_PAGER="$_cp"
1018 elif [ -n "${PAGER+set}" ]; then
1019 TG_PAGER="$PAGER"
1020 else
1021 _gp="$(git var GIT_PAGER 2>/dev/null || :)"
1022 [ "$_gp" != ":" ] || _gp=
1023 TG_PAGER="${_gp:-less}"
1025 if [ -z "$TG_PAGER" ]; then
1026 emptypager=1
1027 TG_PAGER=cat
1029 else
1030 emptypager=1
1031 TG_PAGER=cat
1034 # Set pager default environment variables
1035 # see pager.c:setup_pager
1036 if [ -z "${LESS+set}" ]; then
1037 LESS="-FRX"
1038 export LESS
1040 if [ -z "${LV+set}" ]; then
1041 LV="-c"
1042 export LV
1045 # this is needed so e.g. $(git diff) will still colorize it's output if
1046 # requested in ~/.gitconfig with color.diff=auto
1047 GIT_PAGER_IN_USE=1
1048 export GIT_PAGER_IN_USE
1050 # this is needed so we don't get nested pagers
1051 TG_PAGER_IN_USE=1
1052 export TG_PAGER_IN_USE
1055 # page eval_arg [arg ...]
1057 # Calls setup_pager then evals the first argument passing it all the rest
1058 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1059 # by setup_pager (in which case the output is left as-is).
1061 # To handle arbitrary paging duties, collect lines to be paged into a
1062 # function and then call page with the function name or perhaps func_name "$@".
1064 # If no arguments at all are passed in do nothing (return with success).
1065 page()
1067 [ $# -gt 0 ] || return 0
1068 setup_pager
1069 _evalarg="$1"; shift
1070 if [ -n "$emptypager" ]; then
1071 eval "$_evalarg" '"$@"'
1072 else
1073 eval "$_evalarg" '"$@"' | eval "$TG_PAGER"
1077 # get_temp NAME [-d]
1078 # creates a new temporary file (or directory with -d) in the global
1079 # temporary directory $tg_tmp_dir with pattern prefix NAME
1080 get_temp()
1082 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1085 # automatically called by strftime
1086 # does nothing if already setup
1087 # may be called explicitly if the first call would otherwise be in a subshell
1088 # so that the setup is only done once before subshells start being spawned
1089 setup_strftime()
1091 [ -z "$strftime_is_setup" ] || return 0
1093 # date option to format raw epoch seconds values
1094 daterawopt=
1095 _testes='951807788'
1096 _testdt='2000-02-29 07:03:08 UTC'
1097 _testfm='%Y-%m-%d %H:%M:%S %Z'
1098 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1099 daterawopt='-d@'
1100 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1101 daterawopt='-r'
1103 strftime_is_setup=1
1106 # $1 => strftime format string to use
1107 # $2 => raw timestamp as seconds since epoch
1108 # $3 => optional time zone string (empty/absent for local time zone)
1109 strftime()
1111 setup_strftime
1112 if [ -n "$daterawopt" ]; then
1113 if [ -n "$3" ]; then
1114 TZ="$3" date "$daterawopt$2" "+$1"
1115 else
1116 date "$daterawopt$2" "+$1"
1118 else
1119 if [ -n "$3" ]; then
1120 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1121 else
1122 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1127 ## Initial setup
1128 initial_setup()
1130 # suppress the merge log editor feature since git 1.7.10
1132 GIT_MERGE_AUTOEDIT=no
1133 export GIT_MERGE_AUTOEDIT
1135 auhopt=
1136 [ "$(vcmp "$git_vernum" 2.9)" -lt 0 ] || auhopt="--allow-unrelated-histories"
1137 git_dir="$(git rev-parse --git-dir)"
1138 root_dir="$(git rev-parse --show-cdup)"; root_dir="${root_dir:-.}"
1139 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null || :)"
1140 [ "$logrefupdates" = "true" ] || logrefupdates=
1141 tgsequester="$(git config --bool topgit.sequester 2>/dev/null || :)"
1142 tgnosequester=
1143 [ "$tgsequester" != "false" ] || tgnosequester=1
1144 unset tgsequester
1146 # make sure root_dir doesn't end with a trailing slash.
1148 root_dir="${root_dir%/}"
1149 [ -n "$base_remote" ] || base_remote="$(git config topgit.remote 2>/dev/null)" || :
1151 # make sure global cache directory exists inside GIT_DIR
1153 tg_cache_dir="$git_dir/tg-cache"
1154 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir"
1156 # create global temporary directories, inside GIT_DIR
1158 tg_tmp_dir=
1159 trap 'rm -rf "$tg_tmp_dir"' EXIT
1160 trap 'exit 129' HUP
1161 trap 'exit 130' INT
1162 trap 'exit 131' QUIT
1163 trap 'exit 134' ABRT
1164 trap 'exit 143' TERM
1165 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX")"
1166 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1168 # refer to "top-bases" in a refname with $topbases
1170 topbases="top-bases"
1173 # return the "realpath" for the item except the leaf is not resolved if it's
1174 # a symbolic link. The directory part must exist, but the basename need not.
1175 get_abs_path()
1177 [ -n "$1" -a -d "$(dirname "$1")" ] || return 1
1178 printf '%s' "$(cd -- "$(dirname "$1")" && pwd -P)/$(basename "$1")"
1181 ## Startup
1183 [ -d "@cmddir@" ] ||
1184 die "No command directory: '@cmddir@'"
1186 if [ -n "$tg__include" ]; then
1188 # We were sourced from another script for our utility functions;
1189 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1190 # work as expected in every shell. See http://bugs.debian.org/516188
1192 # ensure setup happens
1194 initial_setup
1196 else
1198 set -e
1200 tg="$0"
1201 tgdir="$(dirname "$tg")/"
1202 tgname="$(basename "$tg")"
1203 [ "$0" != "$tgname" ] || tgdir=""
1205 # If tg contains a '/' but does not start with one then replace it with an absolute path
1207 case "$0" in /*) :;; */*)
1208 tgdir="$(cd "$(dirname "$0")" && pwd -P)/"
1209 tg="$tgdir$tgname"
1210 esac
1212 # If the tg in the PATH is the same as "$tg" just display the basename
1213 # tgdisplay will include any explicit -C <dir> option whereas tg will not
1215 tgdisplaydir="$tgdir"
1216 tgdisplay="$tg"
1217 if [ "$(get_abs_path "$tg")" = "$(get_abs_path "$(which "$tgname" || :)" || :)" ]; then
1218 tgdisplaydir=""
1219 tgdisplay="$tgname"
1222 explicit_remote=
1223 explicit_dir=
1224 gitcdopt=
1225 noremote=
1227 cmd=
1228 while :; do case "$1" in
1230 help|--help|-h)
1231 cmd=help
1232 shift
1233 break;;
1235 --hooks-path)
1236 cmd=hooks-path
1237 shift
1238 break;;
1241 shift
1242 if [ -z "$1" ]; then
1243 echo "Option -r requires an argument." >&2
1244 do_help
1245 exit 1
1247 unset noremote
1248 base_remote="$1"
1249 explicit_remote="$base_remote"
1250 tg="$tgdir$tgname -r $explicit_remote"
1251 tgdisplay="$tgdisplaydir$tgname"
1252 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1253 tgdisplay="$tgdisplay -r $explicit_remote"
1254 shift;;
1257 unset base_remote explicit_remote
1258 noremote=1
1259 tg="$tgdir$tgname -u"
1260 tgdisplay="$tgdisplaydir$tgname"
1261 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1262 tgdisplay="$tgdisplay -u"
1263 shift;;
1266 shift
1267 if [ -z "$1" ]; then
1268 echo "Option -C requires an argument." >&2
1269 do_help
1270 exit 1
1272 cd "$1"
1273 unset GIT_DIR
1274 explicit_dir="$1"
1275 gitcdopt=" -C \"$explicit_dir\""
1276 tg="$tgdir$tgname"
1277 tgdisplay="$tgdisplaydir$tgname -C \"$explicit_dir\""
1278 [ -z "$explicit_remote" ] || tg="$tg -r $explicit_remote"
1279 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
1280 [ -z "$noremote" ] || tg="$tg -u"
1281 [ -z "$noremote" ] || tg="$tgdisplay -u"
1282 shift;;
1285 shift
1286 if [ -z "$1" ]; then
1287 echo "Option -c requires an argument." >&2
1288 do_help
1289 exit 1
1291 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
1292 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
1293 export GIT_CONFIG_PARAMETERS
1294 shift;;
1297 shift
1298 break;;
1301 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
1302 do_help
1303 exit 1;;
1306 break;;
1308 esac; done
1310 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
1312 ## Dispatch
1314 [ -n "$cmd" ] || { do_help; exit 1; }
1316 case "$cmd" in
1318 help)
1319 do_help "$@"
1320 exit 0;;
1322 hooks-path)
1323 # Internal command
1324 echol "@hooksdir@";;
1327 [ -r "@cmddir@"/tg-$cmd ] || {
1328 echo "Unknown subcommand: $cmd" >&2
1329 do_help
1330 exit 1
1333 initial_setup
1334 [ -z "$noremote" ] || unset base_remote
1336 nomergesetup=
1337 case "$cmd" in info|log|summary|rebase|revert|tag)
1338 # avoid merge setup where not necessary
1340 nomergesetup=1
1341 esac
1343 if [ -z "$nomergesetup" ]; then
1344 # make sure merging the .top* files will always behave sanely
1346 setup_ours
1347 setup_hook "pre-commit"
1350 _use_ref_cache=
1351 tg_read_only=1
1352 case "$cmd" in
1353 summary|info|export|tag)
1354 _use_ref_cache=1;;
1355 annihilate|create|delete|depend|import|update)
1356 tg_read_only=;;
1357 esac
1358 [ -z "$_use_ref_cache" ] || create_ref_cache
1360 . "@cmddir@"/tg-$cmd;;
1361 esac
1365 # vim:noet