Makefile: switch from TG-PREFIX to TG-BUILD-SETTINGS
[topgit/pro.git] / tg.sh
blob5ba2d7f1d58b81509f0da5f5f37150ff5dad5542
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 # 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 vcmp()
60 # Compare $1 to $2 each of which must match \d+(\.\d+)*
61 # An empty string ('') for $1 or $2 is treated like 0
62 # Outputs:
63 # -1 if $1 < $2
64 # 0 if $1 = $2
65 # 1 if $1 > $2
66 # Note that $(vcmp 1.8 1.8.0.0.0.0) correctly outputs 0.
67 while
68 _a="${1%%.*}"
69 _b="${2%%.*}"
70 [ -n "$_a" -o -n "$_b" ]
72 if [ "${_a:-0}" -lt "${_b:-0}" ]; then
73 echo -1
74 return
75 elif [ "${_a:-0}" -gt "${_b:-0}" ]; then
76 echo 1
77 return
79 _a2="${1#$_a}"
80 _b2="${2#$_b}"
81 set -- "${_a2#.}" "${_b2#.}"
82 done
83 echo 0
86 precheck() {
87 if ! git_version="$(git version)"; then
88 die "'git version' failed"
90 case "$git_version" in
91 [Gg]"it version "*) :;;
93 die "'git version' output does not start with 'git version '"
94 esac
95 git_vernum="$(echo "$git_version" | sed -ne 's/^[^0-9]*\([0-9][0-9]*\(\.[0-9][0-9]*\)*\).*$/\1/p')"
97 [ "$(vcmp "$git_vernum" $GIT_MINIMUM_VERSION)" -ge 0 ] ||
98 die "git version >= $GIT_MINIMUM_VERSION required but found git version $git_vernum instead"
101 case "$1" in version|--version|-V)
102 echo "TopGit version $TG_VERSION"
103 exit 0
104 esac
106 precheck
107 [ "$1" = "precheck" ] && exit 0
110 cat_depsmsg_internal()
112 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
113 if [ -s "$tg_cache_dir/$1/.$2" ]; then
114 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
115 _line=
116 while IFS= read -r _line || [ -n "$_line" ]; do
117 printf '%s\n' "$_line"
118 done
119 return 0
120 fi <"$tg_cache_dir/$1/.$2"
122 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null || :
123 if [ -d "$tg_cache_dir/$1" ]; then
124 printf '%s\n' "$_rev" >"$tg_cache_dir/$1/.$2"
125 _line=
126 git cat-file blob "$_rev:.$2" 2>/dev/null |
127 while IFS= read -r _line || [ -n "$_line" ]; do
128 printf '%s\n' "$_line" >&3
129 printf '%s\n' "$_line"
130 done 3>>"$tg_cache_dir/$1/.$2"
131 else
132 git cat-file blob "$_rev:.$2" 2>/dev/null
136 # cat_deps BRANCHNAME
137 # Caches result
138 cat_deps()
140 cat_depsmsg_internal "$1" topdeps
143 # cat_msg BRANCHNAME
144 # Caches result
145 cat_msg()
147 cat_depsmsg_internal "$1" topmsg
150 # cat_file TOPIC:PATH [FROM]
151 # cat the file PATH from branch TOPIC when FROM is empty.
152 # FROM can be -i or -w, than the file will be from the index or worktree,
153 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
154 cat_file()
156 path="$1"
157 case "$2" in
159 cat "$root_dir/${path#*:}"
162 # ':file' means cat from index
163 git cat-file blob ":${path#*:}"
166 case "$path" in
167 refs/heads/*:.topdeps)
168 _temp="${path%:.topdeps}"
169 cat_deps "${_temp#refs/heads/}"
171 refs/heads/*:.topmsg)
172 _temp="${path%:.topmsg}"
173 cat_msg "${_temp#refs/heads/}"
176 git cat-file blob "$path"
178 esac
181 die "Wrong argument to cat_file: '$2'"
183 esac
186 # get tree for the committed topic
187 get_tree_()
189 echo "refs/heads/$1"
192 # get tree for the base
193 get_tree_b()
195 echo "refs/$topbases/$1"
198 # get tree for the index
199 get_tree_i()
201 git write-tree
204 # get tree for the worktree
205 get_tree_w()
207 i_tree=$(git write-tree)
209 # the file for --index-output needs to sit next to the
210 # current index file
211 cd "$root_dir"
212 : ${GIT_INDEX_FILE:="$git_dir/index"}
213 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
214 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
215 GIT_INDEX_FILE="$TMP_INDEX" &&
216 export GIT_INDEX_FILE &&
217 git diff --name-only -z HEAD |
218 git update-index -z --add --remove --stdin &&
219 git write-tree &&
220 rm -f "$TMP_INDEX"
224 # strip_ref "$(git symbolic-ref HEAD)"
225 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
226 strip_ref()
228 case "$1" in
229 refs/heads/*)
230 echol "${1#refs/heads/}"
232 refs/"$topbases"/*)
233 echol "${1#refs/$topbases/}"
236 echol "$1"
237 esac
240 # pretty_tree NAME [-b | -i | -w]
241 # Output tree ID of a cleaned-up tree without tg's artifacts.
242 # NAME will be ignored for -i and -w, but needs to be present
243 pretty_tree()
245 name=$1
246 source=${2#?}
247 git ls-tree --full-tree "$(get_tree_$source "$name")" |
248 LC_ALL=C sed -ne '/ \.top.*$/!p' |
249 git mktree
252 # return an empty-tree root commit -- date is either passed in or current
253 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
254 # An invalid secs causes the current date to be used, an invalid zone offset
255 # causes +0000 to be used
256 make_empty_commit()
258 # the empty tree is guaranteed to always be there even in a repo with
259 # zero objects, but for completeness we force it to exist as a real object
260 SECS=
261 read -r SECS ZONE JUNK <<-EOT || :
264 case "$SECS" in *[!0-9]*) SECS=; esac
265 if [ -z "$SECS" ]; then
266 MTDATE="$(date '+%s %z')"
267 else
268 case "$ZONE" in
269 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
271 [01][0-9][0-5][0-9])
272 ZONE="+$ZONE"
275 ZONE="+0000"
276 esac
277 MTDATE="$SECS $ZONE"
279 EMPTYID="- <-> $MTDATE"
280 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
281 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
282 git hash-object -t commit -w --stdin
285 # setup_hook NAME
286 setup_hook()
288 tgname="$(basename "$0")"
289 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
290 if [ -f "$git_dir/hooks/$1" ] && fgrep -q "$hook_call" "$git_dir/hooks/$1"; then
291 # Another job well done!
292 return
294 # Prepare incantation
295 hook_chain=
296 if [ -s "$git_dir/hooks/$1" -a -x "$git_dir/hooks/$1" ]; then
297 hook_call="$hook_call"' || exit $?'
298 if ! LC_ALL=C sed -n 1p <"$git_dir/hooks/$1" | LC_ALL=C fgrep -qx "#!@SHELL_PATH@"; then
299 chain_num=
300 while [ -e "$git_dir/hooks/$1-chain$chain_num" ]; do
301 chain_num=$(( $chain_num + 1 ))
302 done
303 cp -p "$git_dir/hooks/$1" "$git_dir/hooks/$1-chain$chain_num"
304 hook_chain=1
306 else
307 hook_call="exec $hook_call"
309 # Don't call hook if tg is not installed
310 hook_call="if which \"$tgname\" > /dev/null; then $hook_call; fi"
311 # Insert call into the hook
313 echol "#!@SHELL_PATH@"
314 echol "$hook_call"
315 if [ -n "$hook_chain" ]; then
316 echol "exec \"\$0-chain$chain_num\" \"\$@\""
317 else
318 [ ! -s "$git_dir/hooks/$1" ] || cat "$git_dir/hooks/$1"
320 } >"$git_dir/hooks/$1+"
321 chmod a+x "$git_dir/hooks/$1+"
322 mv "$git_dir/hooks/$1+" "$git_dir/hooks/$1"
325 # setup_ours (no arguments)
326 setup_ours()
328 if [ ! -s "$git_dir/info/attributes" ] || ! grep -q topmsg "$git_dir/info/attributes"; then
329 [ -d "$git_dir/info" ] || mkdir "$git_dir/info"
331 echo ".topmsg merge=ours"
332 echo ".topdeps merge=ours"
333 } >>"$git_dir/info/attributes"
335 if ! git config merge.ours.driver >/dev/null; then
336 git config merge.ours.name '"always keep ours" merge driver'
337 git config merge.ours.driver 'touch %A'
341 # measure_branch NAME [BASE] [EXTRAHEAD...]
342 measure_branch()
344 _bname="$1"; _base="$2"
345 shift; shift
346 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
347 # The caller should've verified $name is valid
348 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
349 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
350 if [ $_commits -ne 1 ]; then
351 _suffix="commits"
352 else
353 _suffix="commit"
355 echo "$_commits/$_nmcommits $_suffix"
358 # branch_contains B1 B2
359 # Whether B1 is a superset of B2.
360 branch_contains()
362 _revb1="$(ref_exists_rev "$1")" || return 0
363 _revb2="$(ref_exists_rev "$2")" || return 0
364 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
365 if read _result _rev_matchb1 _rev_matchb2 &&
366 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
367 return $_result
368 fi <"$tg_cache_dir/$1/.bc/$2/.d"
370 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
371 _result=0
372 [ -z "$(git rev-list --max-count=1 ^"$_revb1" "$_revb2" --)" ] || _result=$?
373 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
374 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
376 return $_result
379 create_ref_dirs()
381 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
382 sed -e 's/ .*$//;'"s~^~$tg_tmp_dir/cached/~" <"$tg_ref_cache" | xargs mkdir -p
383 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
386 # If the first argument is non-empty, outputs "1" if this call created the cache
387 create_ref_cache()
389 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
390 _remotespec=
391 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
392 [ -z "$1" ] || printf '1'
393 git for-each-ref --format='%(refname) %(objectname)' \
394 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
395 create_ref_dirs
398 remove_ref_cache()
400 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
401 >"$tg_ref_cache"
404 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
405 rev_parse()
407 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
408 LC_ALL=C awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
409 else
410 [ -z "$tg_ref_cache_only" ] || return 1
411 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
415 # ref_exists_rev REF
416 # Whether REF is a valid ref name
417 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
418 # or, if $base_remote is set, refs/remotes/$base_remote/
419 # Caches result if $tg_read_only and outputs HASH on success
420 ref_exists_rev()
422 case "$1" in
423 refs/*)
425 $octet20)
426 printf '%s' "$1"
427 return;;
429 die "ref_exists_rev requires fully-qualified ref name"
430 esac
431 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
432 _result=
433 _result_rev=
434 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
435 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
436 _result_rev="$(rev_parse "$1")"
437 _result=$?
438 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
439 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
440 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
441 printf '%s' "$_result_rev"
442 return $_result
445 # Same as ref_exists_rev but output is abbreviated hash
446 ref_exists_rev_short()
448 case "$1" in
449 refs/*)
451 $octet20)
454 die "ref_exists_rev_short requires fully-qualified ref name"
455 esac
456 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify --short "$1^0" -- 2>/dev/null; return; }
457 _result=
458 _result_rev=
459 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
460 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
461 _result_rev="$(rev_parse "$1")"
462 _result=$?
463 if [ $_result -eq 0 ]; then
464 _result_rev="$(git rev-parse --verify --short --quiet "$_result_rev" --)"
465 _result=$?
467 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
468 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
469 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
470 printf '%s' "$_result_rev"
471 return $_result
474 # ref_exists REF
475 # Whether REF is a valid ref name
476 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
477 # or, if $base_remote is set, refs/remotes/$base_remote/
478 # Caches result
479 ref_exists()
481 ref_exists_rev "$1" >/dev/null
484 # rev_parse_tree REF
485 # Runs git rev-parse REF^{tree}
486 # Caches result if $tg_read_only
487 rev_parse_tree()
489 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
490 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
491 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
492 printf '%s\n' "$_result"
493 return 0
495 return 1
497 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
498 if [ -d "$tg_tmp_dir/cached/$1" ]; then
499 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
500 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
501 printf '%s\n' "$_result"
502 return 0
504 return 1
506 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
509 # has_remote BRANCH
510 # Whether BRANCH has a remote equivalent (accepts $topbases/ too)
511 has_remote()
513 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
516 # Return the verified TopGit branch name or die with an error.
517 # As a convenience, if HEAD is given and HEAD is a symbolic ref to
518 # refs/heads/... then ... will be verified instead.
519 # if "$2" = "-f" (for fail) then return an error rather than dying.
520 verify_topgit_branch()
522 case "$1" in
523 refs/heads/*)
524 _verifyname="${1#refs/heads/}"
526 refs/"$topbases"/*)
527 _verifyname="${1#refs/$topbases/}"
529 HEAD)
530 _verifyname="$(git symbolic-ref HEAD 2>/dev/null || :)"
531 [ -n "$_verifyname" -o "$2" = "-f" ] || die "HEAD is not a symbolic ref"
532 case "$_verifyname" in refs/heads/*) :;; *)
533 [ "$2" != "-f" ] || return 1
534 die "HEAD is not a symbolic ref to the refs/heads namespace"
535 esac
536 _verifyname="${_verifyname#refs/heads/}"
539 _verifyname="$1"
541 esac
542 if ! ref_exists "refs/heads/$_verifyname"; then
543 [ "$2" != "-f" ] || return 1
544 die "no such branch: $_verifyname"
546 if ! ref_exists "refs/$topbases/$_verifyname"; then
547 [ "$2" != "-f" ] || return 1
548 die "not a TopGit-controlled branch: $_verifyname"
550 printf '%s' "$_verifyname"
553 # Caches result
554 # $1 = branch name (i.e. "t/foo/bar")
555 # $2 = optional result of rev-parse "refs/heads/$1"
556 # $3 = optional result of rev-parse "refs/$topbases/$1"
557 branch_annihilated()
559 _branch_name="$1"
560 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
561 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
563 _result=
564 _result_rev=
565 _result_rev_base=
566 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/$_branch_name/.ann"; } 2>/dev/null || :
567 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
569 # use the merge base in case the base is ahead.
570 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
572 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
573 _result=$?
574 [ -d "$tg_cache_dir/$_branch_name" ] || mkdir -p "$tg_cache_dir/$_branch_name" 2>/dev/null
575 [ ! -d "$tg_cache_dir/$_branch_name" ] ||
576 echo $_result $_rev $_rev_base >"$tg_cache_dir/$_branch_name/.ann" 2>/dev/null || :
577 return $_result
580 non_annihilated_branches()
582 [ $# -gt 0 ] || set -- "refs/$topbases"
583 git for-each-ref --format='%(objectname) %(refname)' "$@" |
584 while read rev ref; do
585 name="${ref#refs/$topbases/}"
586 if branch_annihilated "$name" "" "$rev"; then
587 continue
589 echol "$name"
590 done
593 # Make sure our tree is clean
594 ensure_clean_tree()
596 git update-index --ignore-submodules --refresh ||
597 die "the working directory has uncommitted changes (see above) - first commit or reset them"
598 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
599 die "the index has uncommited changes"
602 # is_sha1 REF
603 # Whether REF is a SHA1 (compared to a symbolic name).
604 is_sha1()
606 case "$1" in $octet20) return 0;; esac
607 return 1
610 # recurse_deps_internal NAME [BRANCHPATH...]
611 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
612 # followed by a 1 if the branch is "tgish" or a 0 if not
613 # then the branch name followed by its depedency chain (which might be empty)
614 # An output line might look like this:
615 # 0 1 t/foo/leaf t/foo/int t/stage
616 # If no_remotes is non-empty, exclude remotes
617 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
618 # any branch names in the space-separated recurse_deps_exclude variable
619 # are skipped (along with their dependencies)
620 recurse_deps_internal()
622 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
623 _ref_hash=
624 if ! _ref_hash="$(ref_exists_rev "refs/heads/$1")"; then
625 [ -z "$2" ] || echo "1 0 $*"
626 return
629 _is_tgish=0
630 _ref_hash_base=
631 ! _ref_hash_base="$(ref_exists_rev "refs/$topbases/$1")" || _is_tgish=1
632 [ -z "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
634 # If no_remotes is unset also check our base against remote base.
635 # Checking our head against remote head has to be done in the helper.
636 if [ -n "$_is_tgish" -a -z "$no_remotes" ] && has_remote "$topbases/$1"; then
637 echo "0 0 refs/remotes/$base_remote/$topbases/$1 $*"
640 # if the branch was annihilated, it is considered to have no dependencies
641 if [ -n "$_is_tgish" ] && ! branch_annihilated "$1" "$_ref_hash" "$_ref_hash_base"; then
642 #TODO: handle nonexisting .topdeps?
643 cat_deps "$1" |
644 while read _dname; do
645 # Avoid depedency loops
646 case " $* " in *" $_dname "*)
647 warn "dependency loop detected in branch $_dname"
648 continue
649 esac
650 # Shoo shoo, leave our environment alone!
651 (recurse_deps_internal "$_dname" "$@")
652 done
655 [ -n "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
658 # do_eval CMD
659 # helper for recurse_deps so that a return statement executed inside CMD
660 # does not return from recurse_deps. This shouldn't be necessary, but it
661 # seems that it actually is.
662 do_eval()
664 eval "$@"
667 # becomes read-only for caching purposes
668 # assigns new value to tg_read_only
669 # become_cacheable/undo_become_cacheable calls may be nested
670 become_cacheable()
672 _old_tg_read_only="$tg_read_only"
673 if [ -z "$tg_read_only" ]; then
674 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
675 tg_read_only=1
677 _my_ref_cache="$(create_ref_cache 1)"
678 _my_ref_cache="${_my_ref_cache:+1}"
679 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
682 # restores tg_read_only and ref_cache to state before become_cacheable call
683 # become_cacheable/undo_bocome_cacheable calls may be nested
684 undo_become_cacheable()
686 case "$tg_read_only" in
687 "undo"[01]"-"*)
688 _suffix="${tg_read_only#undo?-}"
689 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
690 tg_read_only="$_suffix"
691 esac
694 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
695 become_non_cacheable()
697 remove_ref_cache
698 tg_read_only=
699 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
702 # call this to make sure Git will not complain about a missing user/email
703 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
704 ensure_ident_available()
706 [ -z "$TG_IDENT_CHECKED" ] || return 0
707 git var GIT_AUTHOR_IDENT >/dev/null &&
708 git var GIT_COMMITTER_IDENT >/dev/null || exit
709 TG_IDENT_CHECKED=1
710 export TG_IDENT_CHECKED
711 return 0
714 # recurse_deps CMD NAME [BRANCHPATH...]
715 # Recursively eval CMD on all dependencies of NAME.
716 # Dependencies are visited in topological order.
717 # CMD can refer to $_name for queried branch name,
718 # $_dep for dependency name,
719 # $_depchain for space-seperated branch backtrace,
720 # $_dep_missing boolean to check whether $_dep is present
721 # and the $_dep_is_tgish boolean.
722 # It can modify $_ret to affect the return value
723 # of the whole function.
724 # If recurse_deps() hits missing dependencies, it will append
725 # them to space-separated $missing_deps list and skip them
726 # after calling CMD with _dep_missing set.
727 # remote dependencies are processed if no_remotes is unset.
728 # any branch names in the space-separated recurse_deps_exclude variable
729 # are skipped (along with their dependencies)
730 recurse_deps()
732 _cmd="$1"; shift
734 become_cacheable
735 _depsfile="$(get_temp tg-depsfile)"
736 recurse_deps_internal "$@" >>"$_depsfile"
737 undo_become_cacheable
739 _ret=0
740 while read _ismissing _istgish _dep _name _deppath; do
741 _depchain="$_name${_deppath:+ $_deppath}"
742 _dep_is_tgish=
743 [ "$_istgish" = "0" ] || _dep_is_tgish=1
744 _dep_missing=
745 if [ "$_ismissing" != "0" ]; then
746 _dep_missing=1
747 case " $missing_deps " in *" $_dep "*) :;; *)
748 missing_deps="${missing_deps:+$missing_deps }$_dep"
749 esac
751 do_eval "$_cmd"
752 done <"$_depsfile"
753 rm -f "$_depsfile"
754 return $_ret
757 # branch_needs_update
758 # This is a helper function for determining whether given branch
759 # is up-to-date wrt. its dependencies. It expects input as if it
760 # is called as a recurse_deps() helper.
761 # In case the branch does need update, it will echo it together
762 # with the branch backtrace on the output (see needs_update()
763 # description for details) and set $_ret to non-zero.
764 branch_needs_update()
766 if [ -n "$_dep_missing" ]; then
767 echo "! $_dep $_depchain"
768 return 0
771 if [ -n "$_dep_is_tgish" ]; then
772 branch_annihilated "$_dep" && return 0
774 if has_remote "$_dep"; then
775 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
776 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
778 # We want to sync with our base first and should output this before
779 # the remote branch, but the order does not actually matter to tg-update
780 # as it just recurses regardless, but it does matter for tg-info (which
781 # treats out-of-date bases as though they were already merged in) so
782 # we output the remote before the base.
783 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
784 echo ": $_dep $_depchain"
785 _ret=1
786 return
790 if [ -n "$_name" ]; then
791 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
792 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
793 # Some new commits in _dep
794 echo "$_dep $_depchain"
795 _ret=1
800 # needs_update NAME
801 # This function is recursive; it outputs reverse path from NAME
802 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
803 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
804 # if the head is not in sync with the <remote> branch <name>, ':' if
805 # the head is not in sync with the base (in this order of priority)
806 # or '!' if dependency is missing. Note that the remote branch, base
807 # order is reversed from the order they will actually be updated in
808 # order to accomodate tg info which treats out-of-date items that are
809 # only in the base as already being in the head for status purposes.
810 # It will also return non-zero status if NAME needs update.
811 # If needs_update() hits missing dependencies, it will append
812 # them to space-separated $missing_deps list and skip them.
813 needs_update()
815 recurse_deps branch_needs_update "$1"
818 # branch_empty NAME [-i | -w]
819 branch_empty()
821 if [ -z "$2" ]; then
822 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
823 _result=
824 _result_rev=
825 { read -r _result _result_rev <"$tg_cache_dir/$1/.mt"; } 2>/dev/null || :
826 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
827 _result=0
828 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ] || _result=$?
829 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null
830 [ ! -d "$tg_cache_dir/$1" ] || echo $_result $_rev >"$tg_cache_dir/$1/.mt"
831 return $_result
832 else
833 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ]
837 # list_deps [-i | -w] [BRANCH]
838 # -i/-w apply only to HEAD
839 list_deps()
841 head_from=
842 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
843 head="$(git symbolic-ref -q HEAD)" ||
844 head="..detached.."
846 git for-each-ref --format='%(objectname) %(refname)' "refs/$topbases${1:+/$1}" |
847 while read rev ref; do
848 name="${ref#refs/$topbases/}"
849 if branch_annihilated "$name" "" "$rev"; then
850 continue
853 from=$head_from
854 [ "refs/heads/$name" = "$head" ] ||
855 from=
856 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
857 dep_is_tgish=true
858 ref_exists "refs/$topbases/$dep" ||
859 dep_is_tgish=false
860 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
861 echo "$name $dep"
863 done
864 done
867 # switch_to_base NAME [SEED]
868 switch_to_base()
870 _base="refs/$topbases/$1"; _seed="$2"
871 # We have to do all the hard work ourselves :/
872 # This is like git checkout -b "$_base" "$_seed"
873 # (or just git checkout "$_base"),
874 # but does not create a detached HEAD.
875 git read-tree -u -m HEAD "${_seed:-$_base}"
876 [ -z "$_seed" ] || git update-ref "$_base" "$_seed"
877 git symbolic-ref HEAD "$_base"
880 # run editor with arguments
881 # the editor setting will be cached in $tg_editor (which is eval'd)
882 # result non-zero if editor fails or GIT_EDITOR cannot be determined
883 run_editor()
885 tg_editor="$GIT_EDITOR"
886 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
887 eval "$tg_editor" '"$@"'
890 # Show the help messages.
891 do_help()
893 _www=
894 if [ "$1" = "-w" ]; then
895 _www=1
896 shift
898 if [ -z "$1" ] ; then
899 # This is currently invoked in all kinds of circumstances,
900 # including when the user made a usage error. Should we end up
901 # providing more than a short help message, then we should
902 # differentiate.
903 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
905 ## Build available commands list for help output
907 cmds=
908 sep=
909 for cmd in "$TG_INST_CMDDIR"/tg-*; do
910 ! [ -r "$cmd" ] && continue
911 # strip directory part and "tg-" prefix
912 cmd="$(basename "$cmd")"
913 cmd="${cmd#tg-}"
914 cmds="$cmds$sep$cmd"
915 sep="|"
916 done
918 echo "TopGit version $TG_VERSION - A different patch queue manager"
919 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
920 echo " Or: $tgname help [-w] [<command>]"
921 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
922 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
923 if [ -n "$_www" ]; then
924 nohtml=
925 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
926 echo "$(basename "$0"): missing html help file:" \
927 "$TG_INST_SHAREDIR/topgit.html" 1>&2
928 nohtml=1
930 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
931 echo "$(basename "$0"): missing html help file:" \
932 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
933 nohtml=1
935 if [ -n "$nohtml" ]; then
936 echo "$(basename "$0"): use" \
937 "\"$(basename "$0") help $1\" instead" 1>&2
938 exit 1
940 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
941 exit
943 output()
945 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
946 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
947 echo
949 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
950 cat "$TG_INST_SHAREDIR/tg-$1.txt"
953 page output "$1"
954 else
955 echo "$(basename "$0"): no help for $1" 1>&2
956 do_help
957 exit 1
961 ## Pager stuff
963 # isatty FD
964 isatty()
966 test -t $1
969 # pass "diff" to get pager.diff
970 # if pager.$1 is a boolean false returns cat
971 # if set to true or unset fails
972 # otherwise succeeds and returns the value
973 get_pager()
975 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
976 [ "$_x" != "true" ] || return 1
977 echo "cat"
978 return 0
980 if _x="$(git config "pager.$1" 2>/dev/null)"; then
981 echol "$_x"
982 return 0
984 return 1
987 # setup_pager
988 # Set TG_PAGER to a valid executable
989 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
990 # See also the following "page" function for ease of use
991 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
992 # Preference is (same as Git):
993 # 1. GIT_PAGER
994 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
995 # 3. core.pager (only if set)
996 # 4. PAGER
997 # 5. git var GIT_PAGER
998 # 6. less
999 setup_pager()
1001 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1003 emptypager=
1004 if [ -z "$TG_PAGER_IN_USE" ]; then
1005 # TG_PAGER = GIT_PAGER | PAGER | less
1006 # NOTE: GIT_PAGER='' is significant
1007 if [ -n "${GIT_PAGER+set}" ]; then
1008 TG_PAGER="$GIT_PAGER"
1009 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1010 TG_PAGER="$_dp"
1011 elif _cp="$(git config core.pager 2>/dev/null)"; then
1012 TG_PAGER="$_cp"
1013 elif [ -n "${PAGER+set}" ]; then
1014 TG_PAGER="$PAGER"
1015 else
1016 _gp="$(git var GIT_PAGER 2>/dev/null || :)"
1017 [ "$_gp" != ":" ] || _gp=
1018 TG_PAGER="${_gp:-less}"
1020 if [ -z "$TG_PAGER" ]; then
1021 emptypager=1
1022 TG_PAGER=cat
1024 else
1025 emptypager=1
1026 TG_PAGER=cat
1029 # Set pager default environment variables
1030 # see pager.c:setup_pager
1031 if [ -z "${LESS+set}" ]; then
1032 LESS="-FRX"
1033 export LESS
1035 if [ -z "${LV+set}" ]; then
1036 LV="-c"
1037 export LV
1040 # this is needed so e.g. $(git diff) will still colorize it's output if
1041 # requested in ~/.gitconfig with color.diff=auto
1042 GIT_PAGER_IN_USE=1
1043 export GIT_PAGER_IN_USE
1045 # this is needed so we don't get nested pagers
1046 TG_PAGER_IN_USE=1
1047 export TG_PAGER_IN_USE
1050 # page eval_arg [arg ...]
1052 # Calls setup_pager then evals the first argument passing it all the rest
1053 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1054 # by setup_pager (in which case the output is left as-is).
1056 # To handle arbitrary paging duties, collect lines to be paged into a
1057 # function and then call page with the function name or perhaps func_name "$@".
1059 # If no arguments at all are passed in do nothing (return with success).
1060 page()
1062 [ $# -gt 0 ] || return 0
1063 setup_pager
1064 _evalarg="$1"; shift
1065 if [ -n "$emptypager" ]; then
1066 eval "$_evalarg" '"$@"'
1067 else
1068 eval "$_evalarg" '"$@"' | eval "$TG_PAGER"
1072 # get_temp NAME [-d]
1073 # creates a new temporary file (or directory with -d) in the global
1074 # temporary directory $tg_tmp_dir with pattern prefix NAME
1075 get_temp()
1077 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1080 # automatically called by strftime
1081 # does nothing if already setup
1082 # may be called explicitly if the first call would otherwise be in a subshell
1083 # so that the setup is only done once before subshells start being spawned
1084 setup_strftime()
1086 [ -z "$strftime_is_setup" ] || return 0
1088 # date option to format raw epoch seconds values
1089 daterawopt=
1090 _testes='951807788'
1091 _testdt='2000-02-29 07:03:08 UTC'
1092 _testfm='%Y-%m-%d %H:%M:%S %Z'
1093 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1094 daterawopt='-d@'
1095 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1096 daterawopt='-r'
1098 strftime_is_setup=1
1101 # $1 => strftime format string to use
1102 # $2 => raw timestamp as seconds since epoch
1103 # $3 => optional time zone string (empty/absent for local time zone)
1104 strftime()
1106 setup_strftime
1107 if [ -n "$daterawopt" ]; then
1108 if [ -n "$3" ]; then
1109 TZ="$3" date "$daterawopt$2" "+$1"
1110 else
1111 date "$daterawopt$2" "+$1"
1113 else
1114 if [ -n "$3" ]; then
1115 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1116 else
1117 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1122 ## Initial setup
1123 initial_setup()
1125 # suppress the merge log editor feature since git 1.7.10
1127 GIT_MERGE_AUTOEDIT=no
1128 export GIT_MERGE_AUTOEDIT
1130 auhopt=
1131 [ "$(vcmp "$git_vernum" 2.9)" -lt 0 ] || auhopt="--allow-unrelated-histories"
1132 git_dir="$(git rev-parse --git-dir)"
1133 root_dir="$(git rev-parse --show-cdup)"; root_dir="${root_dir:-.}"
1134 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null || :)"
1135 [ "$logrefupdates" = "true" ] || logrefupdates=
1136 tgsequester="$(git config --bool topgit.sequester 2>/dev/null || :)"
1137 tgnosequester=
1138 [ "$tgsequester" != "false" ] || tgnosequester=1
1139 unset tgsequester
1141 # make sure root_dir doesn't end with a trailing slash.
1143 root_dir="${root_dir%/}"
1144 [ -n "$base_remote" ] || base_remote="$(git config topgit.remote 2>/dev/null)" || :
1146 # make sure global cache directory exists inside GIT_DIR
1148 tg_cache_dir="$git_dir/tg-cache"
1149 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir"
1151 # create global temporary directories, inside GIT_DIR
1153 tg_tmp_dir=
1154 trap 'rm -rf "$tg_tmp_dir"' EXIT
1155 trap 'exit 129' HUP
1156 trap 'exit 130' INT
1157 trap 'exit 131' QUIT
1158 trap 'exit 134' ABRT
1159 trap 'exit 143' TERM
1160 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX")"
1161 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1163 # refer to "top-bases" in a refname with $topbases
1165 topbases="top-bases"
1168 # return the "realpath" for the item except the leaf is not resolved if it's
1169 # a symbolic link. The directory part must exist, but the basename need not.
1170 get_abs_path()
1172 [ -n "$1" -a -d "$(dirname "$1")" ] || return 1
1173 printf '%s' "$(cd -- "$(dirname "$1")" && pwd -P)/$(basename "$1")"
1176 ## Startup
1178 : "${TG_INST_CMDDIR:=@cmddir@}"
1179 : "${TG_INST_SHAREDIR:=@sharedir@}"
1180 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1182 [ -d "$TG_INST_CMDDIR" ] ||
1183 die "No command directory: '$TG_INST_CMDDIR'"
1185 if [ -n "$tg__include" ]; then
1187 # We were sourced from another script for our utility functions;
1188 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1189 # work as expected in every shell. See http://bugs.debian.org/516188
1191 # ensure setup happens
1193 initial_setup
1195 else
1197 set -e
1199 tg="$0"
1200 tgdir="$(dirname "$tg")/"
1201 tgname="$(basename "$tg")"
1202 [ "$0" != "$tgname" ] || tgdir=""
1204 # If tg contains a '/' but does not start with one then replace it with an absolute path
1206 case "$0" in /*) :;; */*)
1207 tgdir="$(cd "$(dirname "$0")" && pwd -P)/"
1208 tg="$tgdir$tgname"
1209 esac
1211 # If the tg in the PATH is the same as "$tg" just display the basename
1212 # tgdisplay will include any explicit -C <dir> option whereas tg will not
1214 tgdisplaydir="$tgdir"
1215 tgdisplay="$tg"
1216 if [ "$(get_abs_path "$tg")" = "$(get_abs_path "$(which "$tgname" || :)" || :)" ]; then
1217 tgdisplaydir=""
1218 tgdisplay="$tgname"
1221 explicit_remote=
1222 explicit_dir=
1223 gitcdopt=
1224 noremote=
1226 cmd=
1227 while :; do case "$1" in
1229 help|--help|-h)
1230 cmd=help
1231 shift
1232 break;;
1234 --hooks-path)
1235 cmd=hooks-path
1236 shift
1237 break;;
1240 shift
1241 if [ -z "$1" ]; then
1242 echo "Option -r requires an argument." >&2
1243 do_help
1244 exit 1
1246 unset noremote
1247 base_remote="$1"
1248 explicit_remote="$base_remote"
1249 tg="$tgdir$tgname -r $explicit_remote"
1250 tgdisplay="$tgdisplaydir$tgname"
1251 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1252 tgdisplay="$tgdisplay -r $explicit_remote"
1253 shift;;
1256 unset base_remote explicit_remote
1257 noremote=1
1258 tg="$tgdir$tgname -u"
1259 tgdisplay="$tgdisplaydir$tgname"
1260 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1261 tgdisplay="$tgdisplay -u"
1262 shift;;
1265 shift
1266 if [ -z "$1" ]; then
1267 echo "Option -C requires an argument." >&2
1268 do_help
1269 exit 1
1271 cd "$1"
1272 unset GIT_DIR
1273 explicit_dir="$1"
1274 gitcdopt=" -C \"$explicit_dir\""
1275 tg="$tgdir$tgname"
1276 tgdisplay="$tgdisplaydir$tgname -C \"$explicit_dir\""
1277 [ -z "$explicit_remote" ] || tg="$tg -r $explicit_remote"
1278 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
1279 [ -z "$noremote" ] || tg="$tg -u"
1280 [ -z "$noremote" ] || tg="$tgdisplay -u"
1281 shift;;
1284 shift
1285 if [ -z "$1" ]; then
1286 echo "Option -c requires an argument." >&2
1287 do_help
1288 exit 1
1290 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
1291 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
1292 export GIT_CONFIG_PARAMETERS
1293 shift;;
1296 shift
1297 break;;
1300 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
1301 do_help
1302 exit 1;;
1305 break;;
1307 esac; done
1309 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
1311 ## Dispatch
1313 [ -n "$cmd" ] || { do_help; exit 1; }
1315 case "$cmd" in
1317 help)
1318 do_help "$@"
1319 exit 0;;
1321 hooks-path)
1322 # Internal command
1323 echol "$TG_INST_HOOKSDIR";;
1326 [ -r "$TG_INST_CMDDIR"/tg-$cmd ] || {
1327 echo "Unknown subcommand: $cmd" >&2
1328 do_help
1329 exit 1
1332 initial_setup
1333 [ -z "$noremote" ] || unset base_remote
1335 nomergesetup=
1336 case "$cmd" in info|log|summary|rebase|revert|tag)
1337 # avoid merge setup where not necessary
1339 nomergesetup=1
1340 esac
1342 if [ -z "$nomergesetup" ]; then
1343 # make sure merging the .top* files will always behave sanely
1345 setup_ours
1346 setup_hook "pre-commit"
1349 _use_ref_cache=
1350 tg_read_only=1
1351 case "$cmd" in
1352 summary|info|export|tag)
1353 _use_ref_cache=1;;
1354 annihilate|create|delete|depend|import|update)
1355 tg_read_only=;;
1356 esac
1357 [ -z "$_use_ref_cache" ] || create_ref_cache
1359 . "$TG_INST_CMDDIR"/tg-$cmd;;
1360 esac
1364 # vim:noet