tg.sh: accelerate find_leaves a bit
[topgit/pro.git] / tg.sh
blobeee4536ce876256c49ecacabd0885a24d43c2352
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.7
10 # Update in Makefile if you add any code that requires a newer version of git
11 GIT_MINIMUM_VERSION="@mingitver@"
13 ## SHA-1 pattern
15 octet='[0-9a-f][0-9a-f]'
16 octet4="$octet$octet$octet$octet"
17 octet19="$octet4$octet4$octet4$octet4$octet$octet$octet"
18 octet20="$octet4$octet4$octet4$octet4$octet4"
19 nullsha="0000000000000000000000000000000000000000"
20 mtblob="e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
21 tab=' '
22 lf='
25 ## Auxiliary functions
27 # Preserves current $? value while triggering a non-zero set -e exit if active
28 # This works even for shells that sometimes fail to correctly trigger a -e exit
29 check_exit_code()
31 return $?
34 # This is the POSIX equivalent of which
35 cmd_path()
37 { "unset" -f command unset unalias "$1"; } >/dev/null 2>&1 || :
38 { "unalias" -a; } >/dev/null 2>&1 || :
39 command -v "$1"
42 # helper for wrappers
43 # note deliberate use of '(' ... ')' rather than '{' ... '}'
44 exec_lc_all_c()
46 LC_ALL="C" &&
47 export LC_ALL &&
48 exec "$@"
51 # These tools work better for us with LC_ALL=C and by using these little
52 # convenience functions LC_ALL=C does not have to appear in the code but
53 # any Git translations will still appear for Git commands
54 awk() { exec_lc_all_c @AWK_PATH@ "$@"; }
55 cat() { exec_lc_all_c cat "$@"; }
56 cut() { exec_lc_all_c cut "$@"; }
57 find() { exec_lc_all_c find "$@"; }
58 grep() { exec_lc_all_c grep "$@"; }
59 join() { exec_lc_all_c join "$@"; }
60 paste() { exec_lc_all_c paste "$@"; }
61 sed() { exec_lc_all_c sed "$@"; }
62 sort() { exec_lc_all_c sort "$@"; }
63 tr() { exec_lc_all_c tr "$@"; }
64 wc() { exec_lc_all_c wc "$@"; }
65 xargs() { exec_lc_all_c xargs "$@"; }
67 # Output arguments without any possible interpretation
68 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
69 echol()
71 printf '%s\n' "$*"
74 info()
76 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
79 warn()
81 info "warning: $*" >&2
84 err()
86 info "error: $*" >&2
89 die()
91 info "fatal: $*" >&2
92 exit 1
95 # shift off first arg then return "$*" properly quoted in single-quotes
96 # if $1 was '' output goes to stdout otherwise it's assigned to $1
97 # the final \n, if any, is omitted from the result but any others are included
98 v_quotearg()
100 _quotearg_v="$1"
101 shift
102 set -- "$_quotearg_v" \
103 "sed \"s/'/'\\\\\\''/g;1s/^/'/;\\\$s/\\\$/'/;s/'''/'/g;1s/^''\\(.\\)/\\1/\"" "$*"
104 unset _quotearg_v
105 if [ -z "$3" ]; then
106 if [ -z "$1" ]; then
107 echo "''"
108 else
109 eval "$1=\"''\""
111 else
112 if [ -z "$1" ]; then
113 printf "%s$4" "$3" | eval "$2"
114 else
115 eval "$1="'"$(printf "%s$4" "$3" | eval "$2")"'
120 # same as v_quotearg except there's no extra $1 so output always goes to stdout
121 quotearg()
123 v_quotearg '' "$@"
126 vcmp()
128 # Compare $1 to $3 each of which must match ^[^0-9]*\d*(\.\d*)*.*$
129 # where only the "\d*" parts in the regex participate in the comparison
130 # Since EVERY string matches that regex this function is easy to use
131 # An empty string ('') for $1 or $3 or any "\d*" part is treated as 0
132 # $2 is a compare op '<', '<=', '=', '==', '!=', '>=', '>'
133 # Return code is 0 for true, 1 for false (or unknown compare op)
134 # There is NO difference in behavior between '=' and '=='
135 # Note that "vcmp 1.8 == 1.8.0.0.0.0" correctly returns 0
136 set -- "$1" "$2" "$3" "${1%%[0-9]*}" "${3%%[0-9]*}"
137 set -- "${1#"$4"}" "$2" "${3#"$5"}"
138 set -- "${1%%[!0-9.]*}" "$2" "${3%%[!0-9.]*}"
139 while
140 vcmp_a_="${1%%.*}"
141 vcmp_b_="${3%%.*}"
142 [ "z$vcmp_a_" != "z" -o "z$vcmp_b_" != "z" ]
144 if [ "${vcmp_a_:-0}" -lt "${vcmp_b_:-0}" ]; then
145 unset vcmp_a_ vcmp_b_
146 case "$2" in "<"|"<="|"!=") return 0; esac
147 return 1
148 elif [ "${vcmp_a_:-0}" -gt "${vcmp_b_:-0}" ]; then
149 unset vcmp_a_ vcmp_b_
150 case "$2" in ">"|">="|"!=") return 0; esac
151 return 1;
153 vcmp_a_="${1#$vcmp_a_}"
154 vcmp_b_="${3#$vcmp_b_}"
155 set -- "${vcmp_a_#.}" "$2" "${vcmp_b_#.}"
156 done
157 unset vcmp_a_ vcmp_b_
158 case "$2" in "="|"=="|"<="|">=") return 0; esac
159 return 1
162 precheck() {
163 if ! git_version="$(git version)"; then
164 die "'git version' failed"
166 case "$git_version" in [Gg]"it version "*);;*)
167 die "'git version' output does not start with 'git version '"
168 esac
170 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
171 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
174 case "$1" in version|--version|-V)
175 echo "TopGit version $TG_VERSION"
176 exit 0
177 esac
179 precheck
180 [ "$1" = "precheck" ] && exit 0
183 cat_depsmsg_internal()
185 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
186 if [ -s "$tg_cache_dir/refs/heads/$1/.$2" ]; then
187 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
188 _line=
189 while IFS= read -r _line || [ -n "$_line" ]; do
190 printf '%s\n' "$_line"
191 done
192 return 0
193 fi <"$tg_cache_dir/refs/heads/$1/.$2"
195 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null || :
196 if [ -d "$tg_cache_dir/refs/heads/$1" ]; then
197 printf '%s\n' "$_rev" >"$tg_cache_dir/refs/heads/$1/.$2"
198 _line=
199 git cat-file blob "$_rev:.$2" 2>/dev/null |
200 while IFS= read -r _line || [ -n "$_line" ]; do
201 printf '%s\n' "$_line" >&3
202 printf '%s\n' "$_line"
203 done 3>>"$tg_cache_dir/refs/heads/$1/.$2"
204 else
205 git cat-file blob "$_rev:.$2" 2>/dev/null
209 # cat_deps BRANCHNAME
210 # Caches result
211 cat_deps()
213 cat_depsmsg_internal "$1" topdeps
216 # cat_msg BRANCHNAME
217 # Caches result
218 cat_msg()
220 cat_depsmsg_internal "$1" topmsg
223 # cat_file TOPIC:PATH [FROM]
224 # cat the file PATH from branch TOPIC when FROM is empty.
225 # FROM can be -i or -w, than the file will be from the index or worktree,
226 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
227 cat_file()
229 path="$1"
230 case "$2" in
232 cat "$root_dir/${path#*:}"
235 # ':file' means cat from index
236 git cat-file blob ":${path#*:}" 2>/dev/null
239 case "$path" in
240 refs/heads/*:.topdeps)
241 _temp="${path%:.topdeps}"
242 cat_deps "${_temp#refs/heads/}"
244 refs/heads/*:.topmsg)
245 _temp="${path%:.topmsg}"
246 cat_msg "${_temp#refs/heads/}"
249 git cat-file blob "$path" 2>/dev/null
251 esac
254 die "Wrong argument to cat_file: '$2'"
256 esac
259 # if use_alt_temp_odb and tg_use_alt_odb are true try to write the object(s)
260 # into the temporary alt odb area instead of the usual location
261 git_temp_alt_odb_cmd()
263 if [ -n "$use_alt_temp_odb" ] && [ -n "$tg_use_alt_odb" ] &&
264 [ -n "$TG_OBJECT_DIRECTORY" ] &&
265 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
267 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
268 GIT_OBJECT_DIRECTORY="$TG_OBJECT_DIRECTORY"
269 unset TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES
270 export GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
271 git "$@"
273 else
274 git "$@"
278 git_write_tree() { git_temp_alt_odb_cmd write-tree "$@"; }
279 git_mktree() { git_temp_alt_odb_cmd mktree "$@"; }
281 # get tree for the committed topic
282 get_tree_()
284 echo "refs/heads/$1"
287 # get tree for the base
288 get_tree_b()
290 echo "refs/$topbases/$1"
293 # get tree for the index
294 get_tree_i()
296 git_write_tree
299 # get tree for the worktree
300 get_tree_w()
302 i_tree=$(git_write_tree)
304 # the file for --index-output needs to sit next to the
305 # current index file
306 cd "$root_dir"
307 : ${GIT_INDEX_FILE:="$git_dir/index"}
308 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
309 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
310 GIT_INDEX_FILE="$TMP_INDEX" &&
311 export GIT_INDEX_FILE &&
312 git diff --name-only -z HEAD |
313 git update-index -z --add --remove --stdin &&
314 git_write_tree &&
315 rm -f "$TMP_INDEX"
319 # get tree for arbitrary ref
320 get_tree_r()
322 echo "$1"
325 # strip_ref "$(git symbolic-ref HEAD)"
326 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
327 strip_ref()
329 case "$1" in
330 refs/"$topbases"/*)
331 echol "${1#refs/$topbases/}"
333 refs/heads/*)
334 echol "${1#refs/heads/}"
337 echol "$1"
338 esac
341 # pretty_tree [-t] NAME [-b | -i | -w | -r]
342 # Output tree ID of a cleaned-up tree without tg's artifacts.
343 # NAME will be ignored for -i and -w, but needs to be present
344 # With -r NAME must be a full ref name to a treeish (it's used as-is)
345 # If -t is used the tree is written into the alternate temporary objects area
346 pretty_tree()
348 use_alt_temp_odb=
349 [ "$1" != "-t" ] || { shift; use_alt_temp_odb=1; }
350 name="$1"
351 source="${2#?}"
352 git ls-tree --full-tree "$(get_tree_$source "$name")" |
353 sed -ne '/ \.top.*$/!p' |
354 git_mktree
357 # return an empty-tree root commit -- date is either passed in or current
358 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
359 # An invalid secs causes the current date to be used, an invalid zone offset
360 # causes +0000 to be used
361 make_empty_commit()
363 # the empty tree is guaranteed to always be there even in a repo with
364 # zero objects, but for completeness we force it to exist as a real object
365 SECS=
366 read -r SECS ZONE JUNK <<-EOT || :
369 case "$SECS" in *[!0-9]*) SECS=; esac
370 if [ -z "$SECS" ]; then
371 MTDATE="$(date '+%s %z')"
372 else
373 case "$ZONE" in
374 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
376 [01][0-9][0-5][0-9])
377 ZONE="+$ZONE"
380 ZONE="+0000"
381 esac
382 MTDATE="$SECS $ZONE"
384 EMPTYID="- <-> $MTDATE"
385 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
386 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
387 git hash-object -t commit -w --stdin
390 # standard input is a diff
391 # standard output is the "+" lines with leading "+ " removed
392 diff_added_lines()
394 awk '
395 BEGIN { in_hunk = 0; }
396 /^@@ / { in_hunk = 1; }
397 /^\+/ { if (in_hunk == 1) printf("%s\n", substr($0, 2)); }
398 /^[^@ +-]/ { in_hunk = 0; }
402 # $1 is name of new branch to create locally if all of these are true:
403 # a) exists as a remote TopGit branch for "$base_remote"
404 # b) the branch "name" does not have any invalid characters in it
405 # c) neither of the two branch refs (branch or base) exist locally
406 # returns success only if a new local branch was created (and dumps message)
407 auto_create_local_remote()
409 case "$1" in ""|*[" $tab$lf~^:\\*?["]*|.*|*/.*|*.|*./|/*|*/|*//*) return 1; esac
410 [ -n "$base_remote" ] &&
411 git update-ref --stdin <<-EOT >/dev/null 2>&1 &&
412 verify refs/remotes/$base_remote/${topbases#heads/}/$1 refs/remotes/$base_remote/${topbases#heads/}/$1
413 verify refs/remotes/$base_remote/$1 refs/remotes/$base_remote/$1
414 create refs/$topbases/$1 refs/remotes/$base_remote/${topbases#heads/}/$1^0
415 create refs/heads/$1 refs/remotes/$base_remote/$1^0
417 { init_reflog "refs/$topbases/$1" || :; } &&
418 info "topic branch '$1' automatically set up from remote '$base_remote'"
421 # setup_hook NAME
422 setup_hook()
424 tgname="${0##*/}"
425 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
426 if [ -f "$git_hooks_dir/$1" ] && grep -Fq "$hook_call" "$git_hooks_dir/$1"; then
427 # Another job well done!
428 return
430 # Prepare incantation
431 hook_chain=
432 if [ -s "$git_hooks_dir/$1" -a -x "$git_hooks_dir/$1" ]; then
433 hook_call="$hook_call"' || exit $?'
434 if [ -L "$git_hooks_dir/$1" ] || ! sed -n 1p <"$git_hooks_dir/$1" | grep -Fqx "#!@SHELL_PATH@"; then
435 chain_num=
436 while [ -e "$git_hooks_dir/$1-chain$chain_num" ]; do
437 chain_num=$(( $chain_num + 1 ))
438 done
439 mv -f "$git_hooks_dir/$1" "$git_hooks_dir/$1-chain$chain_num"
440 hook_chain=1
442 else
443 hook_call="exec $hook_call"
444 [ -d "$git_hooks_dir" ] || mkdir -p "$git_hooks_dir" || :
446 # Don't call hook if tg is not installed
447 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
448 # Insert call into the hook
450 echol "#!@SHELL_PATH@"
451 echol "$hook_call"
452 if [ -n "$hook_chain" ]; then
453 echol "exec \"\$0-chain$chain_num\" \"\$@\""
454 else
455 [ ! -s "$git_hooks_dir/$1" ] || cat "$git_hooks_dir/$1"
457 } >"$git_hooks_dir/$1+"
458 chmod a+x "$git_hooks_dir/$1+"
459 mv "$git_hooks_dir/$1+" "$git_hooks_dir/$1"
462 # setup_ours (no arguments)
463 setup_ours()
465 if [ ! -s "$git_common_dir/info/attributes" ] || ! grep -q topmsg "$git_common_dir/info/attributes"; then
466 [ -d "$git_common_dir/info" ] || mkdir "$git_common_dir/info"
468 echo ".topmsg merge=ours"
469 echo ".topdeps merge=ours"
470 } >>"$git_common_dir/info/attributes"
472 if ! git config merge.ours.driver >/dev/null; then
473 git config merge.ours.name '"always keep ours" merge driver'
474 git config merge.ours.driver 'touch %A'
478 # measure_branch NAME [BASE] [EXTRAHEAD...]
479 measure_branch()
481 _bname="$1"; _base="$2"
482 shift; shift
483 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
484 # The caller should've verified $name is valid
485 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
486 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
487 if [ $_commits -ne 1 ]; then
488 _suffix="commits"
489 else
490 _suffix="commit"
492 echo "$_commits/$_nmcommits $_suffix"
495 # true if $1 is contained by (or the same as) $2
496 # this is never slower than merge-base --is-ancestor and is often slightly faster
497 contained_by()
499 [ "$(git rev-list --count --max-count=1 "$1" --not "$2" --)" = "0" ]
502 # branch_contains B1 B2
503 # Whether B1 is a superset of B2.
504 branch_contains()
506 _revb1="$(ref_exists_rev "$1")" || return 0
507 _revb2="$(ref_exists_rev "$2")" || return 0
508 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
509 if read _result _rev_matchb1 _rev_matchb2 &&
510 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
511 return $_result
512 fi <"$tg_cache_dir/$1/.bc/$2/.d"
514 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
515 _result=0
516 contained_by "$_revb2" "$_revb1" || _result=1
517 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
518 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
520 return $_result
523 create_ref_dirs()
525 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
526 awk -v p="$tg_tmp_dir/cached/" '{print p $1}' <"$tg_ref_cache" | tr '\n' '\0' | xargs -0 mkdir -p
527 awk -v p="$tg_tmp_dir/cached/" '
528 NF == 2 && $1 ~ /^refs\/./ && $2 ~ /^[0-9a-fA-F]{4,}$/ {
529 fn = p $1 "/.ref"
530 print "0 " $2 >fn
531 close fn
533 ' <"$tg_ref_cache"
534 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
537 # If the first argument is non-empty, stores "1" there if this call created the cache
538 v_create_ref_cache()
540 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
541 _remotespec=
542 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
543 [ -z "$1" ] || eval "$1=1"
544 git for-each-ref --format='%(refname) %(objectname)' \
545 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
546 create_ref_dirs
549 remove_ref_cache()
551 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
552 >"$tg_ref_cache"
553 >"$tg_ref_cache_br"
554 >"$tg_ref_cache_rbr"
555 >"$tg_ref_cache_ann"
556 >"$tg_ref_cache_dep"
559 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
560 rev_parse()
562 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
563 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
564 else
565 [ -z "$tg_ref_cache_only" ] || return 1
566 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
570 # ref_exists_rev REF
571 # Whether REF is a valid ref name
572 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
573 # or, if $base_remote is set, refs/remotes/$base_remote/
574 # Caches result if $tg_read_only and outputs HASH on success
575 ref_exists_rev()
577 case "$1" in
578 refs/*)
580 $octet20)
581 printf '%s' "$1"
582 return;;
584 die "ref_exists_rev requires fully-qualified ref name (given: $1)"
585 esac
586 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
587 _result=
588 _result_rev=
589 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
590 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
591 _result_rev="$(rev_parse "$1")"
592 _result=$?
593 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
594 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
595 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
596 printf '%s' "$_result_rev"
597 return $_result
600 # Same as ref_exists_rev but output is abbreviated hash
601 # Optional second argument defaults to --short but may be any --short=.../--no-short option
602 ref_exists_rev_short()
604 case "$1" in
605 refs/*)
607 $octet20)
610 die "ref_exists_rev_short requires fully-qualified ref name"
611 esac
612 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
613 _result=
614 _result_rev=
615 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
616 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
617 _result_rev="$(rev_parse "$1")"
618 _result=$?
619 if [ $_result -eq 0 ]; then
620 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev" --)"
621 _result=$?
623 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
624 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
625 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
626 printf '%s' "$_result_rev"
627 return $_result
630 # ref_exists REF
631 # Whether REF is a valid ref name
632 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
633 # or, if $base_remote is set, refs/remotes/$base_remote/
634 # Caches result
635 ref_exists()
637 ref_exists_rev "$1" >/dev/null
640 # rev_parse_tree REF
641 # Runs git rev-parse REF^{tree}
642 # Caches result if $tg_read_only
643 rev_parse_tree()
645 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
646 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
647 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
648 printf '%s\n' "$_result"
649 return 0
651 return 1
653 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
654 if [ -d "$tg_tmp_dir/cached/$1" ]; then
655 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
656 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
657 printf '%s\n' "$_result"
658 return 0
660 return 1
662 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
665 # has_remote BRANCH
666 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
667 has_remote()
669 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
672 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
673 # If -z "$1" still set return code but do not return result
674 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
675 # refs/heads/... then ... will be verified instead.
676 # if "$3" = "-f" (for fail) then return an error rather than dying.
677 v_verify_topgit_branch()
679 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
680 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
681 [ -n "$_verifyname" -o "$3" = "-f" ] || die "HEAD is not a symbolic ref"
682 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
683 [ "$3" != "-f" ] || return 1
684 die "HEAD is not a symbolic ref to the refs/heads namespace"
685 esac
686 set -- "$1" "$_verifyname" "$3"
688 case "$2" in
689 refs/"$topbases"/*)
690 _verifyname="${2#refs/$topbases/}"
692 refs/heads/*)
693 _verifyname="${2#refs/heads/}"
696 _verifyname="$2"
698 esac
699 if ! ref_exists "refs/heads/$_verifyname"; then
700 [ "$3" != "-f" ] || return 1
701 die "no such branch: $_verifyname"
703 if ! ref_exists "refs/$topbases/$_verifyname"; then
704 [ "$3" != "-f" ] || return 1
705 die "not a TopGit-controlled branch: $_verifyname"
707 [ -z "$1" ] || eval "$1="'"$_verifyname"'
710 # Return the verified TopGit branch name or die with an error.
711 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
712 # refs/heads/... then ... will be verified instead.
713 # if "$2" = "-f" (for fail) then return an error rather than dying.
714 verify_topgit_branch()
716 v_verify_topgit_branch _verifyname "$@" || return
717 printf '%s' "$_verifyname"
720 # Caches result
721 # $1 = branch name (i.e. "t/foo/bar")
722 # $2 = optional result of rev-parse "refs/heads/$1"
723 # $3 = optional result of rev-parse "refs/$topbases/$1"
724 branch_annihilated()
726 _branch_name="$1"
727 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
728 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
730 _result=
731 _result_rev=
732 _result_rev_base=
733 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/refs/heads/$_branch_name/.ann"; } 2>/dev/null || :
734 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
736 # use the merge base in case the base is ahead.
737 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
739 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
740 _result=$?
741 [ -d "$tg_cache_dir/refs/heads/$_branch_name" ] || mkdir -p "$tg_cache_dir/refs/heads/$_branch_name" 2>/dev/null
742 [ ! -d "$tg_cache_dir/refs/heads/$_branch_name" ] ||
743 echo $_result $_rev $_rev_base >"$tg_cache_dir/refs/heads/$_branch_name/.ann" 2>/dev/null || :
744 return $_result
747 non_annihilated_branches()
749 refscacheopt=
750 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
751 refscacheopt='-r="$tg_ref_cache" "refs/$topbases"'
753 eval run_awk_topgit_branches -n "$refscacheopt" '"refs/$topbases" "$@"'
756 # Make sure our tree is clean
757 # if optional "$1" given also verify that a checkout to "$1" would succeed
758 ensure_clean_tree()
760 check_status
761 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
762 git update-index --ignore-submodules --refresh ||
763 die "the working directory has uncommitted changes (see above) - first commit or reset them"
764 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
765 die "the index has uncommited changes"
766 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
767 die "git checkout \"$1\" would fail"
770 # Make sure .topdeps and .topmsg are "clean"
771 # They are considered "clean" if each is identical in worktree, index and HEAD
772 # With "-u" as the argument skip the HEAD check (-u => unborn)
773 # untracked .topdeps and/or .topmsg files are always considered "dirty" as well
774 # with -u them just existing constitutes "dirty"
775 ensure_clean_topfiles()
777 _dirtw=0
778 _dirti=0
779 _dirtu=0
780 _check="$(git diff-files --ignore-submodules --name-only -- :/.topdeps :/.topmsg)" &&
781 [ -z "$_check" ] || _dirtw=1
782 if [ "$1" != "-u" ]; then
783 _check="$(git diff-index --cached --ignore-submodules --name-only HEAD -- :/.topdeps :/.topmsg)" &&
784 [ -z "$_check" ] || _dirti=1
786 if [ "$_dirti$_dirtw" = "00" ]; then
787 v_get_show_cdup
788 if [ -e "${git_cdup_result}.topdeps" ] || [ -e "${git_cdup_result}.topmsg" ]; then
789 [ "$1" != "-u" ] &&
790 _check="$(git status --porcelain --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg)" &&
791 [ -z "$_check" ] || _dirtu=1
794 if [ "$_dirtu$_dirti$_dirtw" != "000" ]; then
795 git status --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg || :
796 case "$_dirtu$_dirti$_dirtw" in
797 001) die "the working directory has uncommitted changes (see above) - first commit or reset them";;
798 010) die "the index has uncommited changes (see above)";;
799 011) die "the working directory and index have uncommitted changes (see above) - first commit or reset them";;
800 100) die "the working directory has untracked files that would be overwritten (see above)";;
801 esac
805 # is_sha1 REF
806 # Whether REF is a SHA1 (compared to a symbolic name).
807 is_sha1()
809 case "$1" in $octet20) return 0;; esac
810 return 1
813 # navigate_deps <run_awk_topgit_navigate options and arguments>
814 # all options and arguments are passed through to run_awk_topgit_navigate
815 # except for a leading -td= option, if any, which is picked off for deps
816 # after arranging to feed it a suitable deps list
817 navigate_deps()
819 dogfer=
820 dorad=1
821 userc=
822 tmpdep=
823 ratd_opts=
824 ratn_opts=
825 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
826 userc=1
827 tmprfs="$tg_ref_cache"
828 tmptgbr="$tg_ref_cache_br"
829 tmpann="$tg_ref_cache_ann"
830 tmpdep="$tg_ref_cache_dep"
831 [ -s "$tg_ref_cache" ] || dogfer=1
832 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
833 else
834 ratd_opts="-rmr"
835 ratn_opts="-rma -rmb"
836 tmprfs="$tg_tmp_dir/refs.$$"
837 tmpann="$tg_tmp_dir/ann.$$"
838 tmptgbr="$tg_tmp_dir/tgbr.$$"
839 dogfer=1
841 refpats="\"refs/heads\" \"refs/\$topbases\""
842 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
843 [ -z "$dogfer" ] ||
844 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
845 depscmd="run_awk_topgit_deps $ratd_opts"
846 case "$1" in -td=*)
847 userc=
848 depscmd="$depscmd $1"
849 shift
850 esac
851 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -m="$mtblob" -s "refs/$topbases"'
852 if [ -n "$userc" ]; then
853 if [ -n "$dorad" ]; then
854 eval "$depscmd" >"$tmpdep"
856 depscmd='<"$tmpdep" '
857 else
858 depscmd="$depscmd |"
860 eval "$depscmd" run_awk_topgit_navigate '-a="$tmpann" -b="$tmptgbr"' "$ratn_opts" '"$@"'
863 # recurse_deps_internal NAME [BRANCHPATH...]
864 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
865 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
866 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
867 # but missing and remotes are always "0"
868 # then the branch name followed by its depedency chain (which might be empty)
869 # An output line might look like this:
870 # 0 1 1 t/foo/leaf t/foo/int t/stage
871 # If no_remotes is non-empty, exclude remotes
872 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
873 # If with_top_level is non-empty, include the top-level that's normally omitted
874 # any branch names in the space-separated recurse_deps_exclude variable
875 # are skipped (along with their dependencies)
876 recurse_deps_internal()
878 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
879 ratr_opts="${recurse_preorder:+-f} ${with_top_level:+-s}"
880 dogfer=
881 dorad=1
882 userc=
883 tmpdep=
884 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
885 userc=1
886 tmprfs="$tg_ref_cache"
887 tmptgbr="$tg_ref_cache_br"
888 tmpann="$tg_ref_cache_ann"
889 tmpdep="$tg_ref_cache_dep"
890 [ -s "$tg_ref_cache" ] || dogfer=1
891 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
892 else
893 ratr_opts="$ratr_opts -rmh -rma -rmb"
894 tmprfs="$tg_tmp_dir/refs.$$"
895 tmpann="$tg_tmp_dir/ann.$$"
896 tmptgbr="$tg_tmp_dir/tgbr.$$"
897 dogfer=1
899 refpats="\"refs/heads\" \"refs/\$topbases\""
900 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
901 tmptgrmtbr=
902 dorab=1
903 if [ -z "$no_remotes" ] && [ -n "$base_remote" ]; then
904 if [ -n "$userc" ]; then
905 tmptgrmtbr="$tg_ref_cache_rbr"
906 [ -n "$dogfer" ] || ! [ -s "$tmptgrmtbr" ] || dorab=
907 else
908 tmptgrmtbr="$tg_tmp_dir/tgrmtbr.$$"
909 ratr_opts="$ratr_opts -rmr"
911 ratr_opts="$ratr_opts -r=\"\$tmptgbr\" -u=\"refs/remotes/\$base_remote/\${topbases#heads/}\""
913 [ -z "$dogfer" ] ||
914 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
915 if [ -n "$tmptgrmtbr" ] && [ -n "$dorab" ]; then
916 run_awk_topgit_branches -n -h="refs/remotes/$base_remote" -r="$tmprfs" \
917 "refs/remotes/$base_remote/${topbases#heads/}" >"$tmptgrmtbr"
919 depscmd='run_awk_topgit_deps -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -m="$mtblob" "refs/$topbases"'
920 if [ -n "$userc" ]; then
921 if [ -n "$dorad" ]; then
922 eval "$depscmd" >"$tmpdep"
924 depscmd='<"$tmpdep" '
925 else
926 depscmd="$depscmd |"
928 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
929 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
932 # do_eval CMD
933 # helper for recurse_deps so that a return statement executed inside CMD
934 # does not return from recurse_deps. This shouldn't be necessary, but it
935 # seems that it actually is.
936 do_eval()
938 eval "$@"
941 # becomes read-only for caching purposes
942 # assigns new value to tg_read_only
943 # become_cacheable/undo_become_cacheable calls may be nested
944 become_cacheable()
946 _old_tg_read_only="$tg_read_only"
947 if [ -z "$tg_read_only" ]; then
948 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
949 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
950 tg_read_only=1
952 _my_ref_cache=
953 v_create_ref_cache _my_ref_cache
954 _my_ref_cache="${_my_ref_cache:+1}"
955 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
958 # restores tg_read_only and ref_cache to state before become_cacheable call
959 # become_cacheable/undo_bocome_cacheable calls may be nested
960 undo_become_cacheable()
962 case "$tg_read_only" in
963 "undo"[01]"-"*)
964 _suffix="${tg_read_only#undo?-}"
965 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
966 tg_read_only="$_suffix"
967 esac
970 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
971 become_non_cacheable()
973 remove_ref_cache
974 tg_read_only=
975 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
976 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
979 # call this to make sure Git will not complain about a missing user/email
980 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
981 ensure_ident_available()
983 [ -z "$TG_IDENT_CHECKED" ] || return 0
984 git var GIT_AUTHOR_IDENT >/dev/null &&
985 git var GIT_COMMITTER_IDENT >/dev/null || exit
986 TG_IDENT_CHECKED=1
987 export TG_IDENT_CHECKED
988 return 0
991 # recurse_deps CMD NAME [BRANCHPATH...]
992 # Recursively eval CMD on all dependencies of NAME.
993 # Dependencies are visited in topological order.
994 # CMD can refer to the following variables:
996 # _ret starts as 0; CMD can change; will be final return result
997 # _dep bare branch name or "refs/remotes/..." for a remote base
998 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
999 # _depchain 0+ space-separated branch names forming a path to top
1000 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
1001 # _dep_is_leaf boolean "1" if leaf; "" if not
1002 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
1003 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
1004 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
1006 # CMD may use a "return" statement without issue; its return value is ignored,
1007 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
1008 # will stop immediately and the value with the leading "-" stripped off will
1009 # be the final result code
1011 # CMD can refer to $_name for queried branch name,
1012 # $_dep for dependency name,
1013 # $_depchain for space-seperated branch backtrace,
1014 # $_dep_missing boolean to check whether $_dep is present
1015 # and the $_dep_is_tgish and $_dep_annihilated booleans.
1016 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
1017 # It can modify $_ret to affect the return value
1018 # of the whole function.
1019 # If recurse_deps() hits missing dependencies, it will append
1020 # them to space-separated $missing_deps list and skip them
1021 # after calling CMD with _dep_missing set.
1022 # remote dependencies are processed if no_remotes is unset.
1023 # any branch names in the space-separated recurse_deps_exclude variable
1024 # are skipped (along with their dependencies)
1026 # If no_remotes is non-empty, exclude remotes
1027 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1028 # If with_top_level is non-empty, include the top-level that's normally omitted
1029 # any branch names in the space-separated recurse_deps_exclude variable
1030 # are skipped (along with their dependencies)
1031 recurse_deps()
1033 _cmd="$1"; shift
1035 _depsfile="$(get_temp tg-depsfile)"
1036 recurse_deps_internal -- "$@" >"$_depsfile" || :
1038 _ret=0
1039 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1040 _depchain="$_name${_deppath:+ $_deppath}"
1041 _dep_is_tgish=
1042 [ "$_istgish" = "0" ] || _dep_is_tgish=1
1043 _dep_has_remote=
1044 [ "$_istgish" != "2" ] || _dep_has_remote=1
1045 _dep_missing=
1046 if [ "$_ismissing" != "0" ]; then
1047 _dep_missing=1
1048 case " $missing_deps " in *" $_dep "*);;*)
1049 missing_deps="${missing_deps:+$missing_deps }$_dep"
1050 esac
1052 _dep_annihilated=
1053 _dep_is_leaf=
1054 if [ "$_isleaf" = "1" ]; then
1055 _dep_is_leaf=1
1056 elif [ "$_isleaf" = "2" ]; then
1057 _dep_annihilated=1
1059 do_eval "$_cmd" || :
1060 if [ "${_ret#-}" != "$_ret" ]; then
1061 _ret="${_ret#-}"
1062 break
1064 done <"$_depsfile"
1065 rm -f "$_depsfile"
1066 return ${_ret:-0}
1069 # find_leaves NAME
1070 # output (one per line) the unique leaves of NAME
1071 # a leaf is either
1072 # 1) a non-tgish dependency
1073 # 2) the base of a tgish dependency with no non-annihilated dependencies
1074 # duplicates are suppressed (by commit rev) and remotes are always ignored
1075 # if a leaf has an exact tag match that will be output
1076 # note that recurse_deps_exclude IS honored for this operation
1077 find_leaves()
1079 no_remotes=1
1080 with_top_level=1
1081 recurse_preorder=
1082 seen_leaf_refs=
1083 seen_leaf_revs=
1084 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1085 [ "$_isleaf" = "1" ] && [ "$_ismissing" = "0" ] || continue
1086 if [ "$_istgish" != "0" ]; then
1087 fulldep="refs/$topbases/$_dep"
1088 else
1089 fulldep="refs/heads/$_dep"
1091 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1092 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1093 if fullrev="$(ref_exists_rev "$fulldep")"; then
1094 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1095 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1096 # See if Git knows it by another name
1097 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1098 echo "refs/tags/$tagname"
1099 else
1100 echo "$fulldep"
1102 esac
1104 esac
1105 done <<-EOT
1106 $(recurse_deps_internal -l -o=1 -- "$1")
1108 with_top_level=
1111 # branch_needs_update
1112 # This is a helper function for determining whether given branch
1113 # is up-to-date wrt. its dependencies. It expects input as if it
1114 # is called as a recurse_deps() helper.
1115 # In case the branch does need update, it will echo it together
1116 # with the branch backtrace on the output (see needs_update()
1117 # description for details) and set $_ret to non-zero.
1118 branch_needs_update()
1120 if [ -n "$_dep_missing" ]; then
1121 echo "! $_dep $_depchain"
1122 return 0
1125 if [ -n "$_dep_is_tgish" ]; then
1126 [ -z "$_dep_annihilated" ] || return 0
1128 if [ -n "$_dep_has_remote" ]; then
1129 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
1130 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
1132 # We want to sync with our base first and should output this before
1133 # the remote branch, but the order does not actually matter to tg-update
1134 # as it just recurses regardless, but it does matter for tg-info (which
1135 # treats out-of-date bases as though they were already merged in) so
1136 # we output the remote before the base.
1137 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1138 echo ": $_dep $_depchain"
1139 _ret=1
1140 return
1144 if [ -n "$_name" ]; then
1145 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
1146 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1147 # Some new commits in _dep
1148 echo "$_dep $_depchain"
1149 _ret=1
1154 # needs_update NAME
1155 # This function is recursive; it outputs reverse path from NAME
1156 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1157 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
1158 # if the head is not in sync with the <remote> branch <name>, ':' if
1159 # the head is not in sync with the base (in this order of priority)
1160 # or '!' if dependency is missing. Note that the remote branch, base
1161 # order is reversed from the order they will actually be updated in
1162 # order to accomodate tg info which treats out-of-date items that are
1163 # only in the base as already being in the head for status purposes.
1164 # It will also return non-zero status if NAME needs update.
1165 # If needs_update() hits missing dependencies, it will append
1166 # them to space-separated $missing_deps list and skip them.
1167 needs_update()
1169 recurse_deps branch_needs_update "$1"
1172 # branch_empty NAME [-i | -w]
1173 branch_empty()
1175 if [ -z "$2" ]; then
1176 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1177 _result=
1178 _result_rev=
1179 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1180 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
1181 _result=0
1182 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1183 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1184 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1185 return $_result
1186 else
1187 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1191 # list_deps [-i | -w] [BRANCH]
1192 # -i/-w apply only to HEAD
1193 list_deps()
1195 head_from=
1196 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
1197 head="$(git symbolic-ref -q HEAD)" ||
1198 head="..detached.."
1200 git for-each-ref --format='%(objectname) %(refname)' "refs/$topbases${1:+/$1}" |
1201 while read rev ref; do
1202 name="${ref#refs/$topbases/}"
1203 if branch_annihilated "$name" "" "$rev"; then
1204 continue
1207 from=$head_from
1208 [ "refs/heads/$name" = "$head" ] ||
1209 from=
1210 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
1211 dep_is_tgish=true
1212 ref_exists "refs/$topbases/$dep" ||
1213 dep_is_tgish=false
1214 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
1215 echo "$name $dep"
1217 done
1218 done
1221 # checkout_symref_full [-f] FULLREF [SEED]
1222 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1223 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1224 # MUST be a committish which if present will be used instead of current FULLREF
1225 # (and FULLREF will be updated to it as well in that case)
1226 # Any merge state is always cleared by this function
1227 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1228 # instead of -m) but it will clear out any unmerged entries
1229 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1230 checkout_symref_full()
1232 _mode=-m
1233 _head="HEAD"
1234 if [ "$1" = "-f" ]; then
1235 _mode="--reset"
1236 _head=
1237 shift
1239 _ishash=
1240 case "$1" in
1241 refs/?*)
1243 $octet20)
1244 _ishash=1
1245 [ -z "$2" ] || [ "$1" = "$2" ] ||
1246 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1247 set -- HEAD "$1"
1250 die "programmer error: invalid checkout_symref_full \"$1\""
1252 esac
1253 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1254 die "invalid committish: \"${2:-$1}\""
1255 # Clear out any MERGE_HEAD kruft
1256 rm -f "$git_dir/MERGE_HEAD" || :
1257 # We have to do all the hard work ourselves :/
1258 # This is like git checkout -b "$1" "$2"
1259 # (or just git checkout "$1"),
1260 # but never creates a detached HEAD (unless $1 is a hash)
1261 git read-tree -u $_mode $_head "$_seedrev" &&
1263 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1264 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1265 } && {
1266 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1270 # switch_to_base NAME [SEED]
1271 switch_to_base()
1273 checkout_symref_full "refs/$topbases/$1" "$2"
1276 # run editor with arguments
1277 # the editor setting will be cached in $tg_editor (which is eval'd)
1278 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1279 run_editor()
1281 tg_editor="$GIT_EDITOR"
1282 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1283 eval "$tg_editor" '"$@"'
1286 # Show the help messages.
1287 do_help()
1289 _www=
1290 if [ "$1" = "-w" ]; then
1291 _www=1
1292 shift
1294 if [ -z "$1" ] ; then
1295 # This is currently invoked in all kinds of circumstances,
1296 # including when the user made a usage error. Should we end up
1297 # providing more than a short help message, then we should
1298 # differentiate.
1299 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1301 ## Build available commands list for help output
1303 cmds=
1304 sep=
1305 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1306 ! [ -r "$cmd" ] && continue
1307 # strip directory part and "tg-" prefix
1308 cmd="${cmd##*/}"
1309 cmd="${cmd#tg-}"
1310 [ "$cmd" != "migrate-bases" ] || continue
1311 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1312 cmds="$cmds$sep$cmd"
1313 sep="|"
1314 done
1316 echo "TopGit version $TG_VERSION - A different patch queue manager"
1317 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
1318 echo " Or: $tgname help [-w] [<command>]"
1319 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1320 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1321 if [ -n "$_www" ]; then
1322 nohtml=
1323 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1324 echo "${0##*/}: missing html help file:" \
1325 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1326 nohtml=1
1328 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1329 echo "${0##*/}: missing html help file:" \
1330 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1331 nohtml=1
1333 if [ -n "$nohtml" ]; then
1334 echo "${0##*/}: use" \
1335 "\"${0##*/} help $1\" instead" 1>&2
1336 exit 1
1338 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1339 exit
1341 output()
1343 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1344 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1345 echo
1346 elif [ "$1" = "help" ]; then
1347 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1348 echo
1349 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1350 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1351 echo
1353 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1354 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1357 page output "$1"
1358 else
1359 echo "${0##*/}: no help for $1" 1>&2
1360 do_help
1361 exit 1
1365 check_status()
1367 git_state=
1368 git_remove=
1369 if [ -e "$git_dir/MERGE_HEAD" ]; then
1370 git_state="merge"
1371 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1372 git_state="am"
1373 git_remove="$git_dir/rebase-apply"
1374 elif [ -e "$git_dir/rebase-apply" ]; then
1375 git_state="rebase"
1376 git_remove="$git_dir/rebase-apply"
1377 elif [ -e "$git_dir/rebase-merge" ]; then
1378 git_state="rebase"
1379 git_remove="$git_dir/rebase-merge"
1380 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1381 git_state="cherry-pick"
1382 elif [ -e "$git_dir/BISECT_LOG" ]; then
1383 git_state="bisect"
1384 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1385 git_state="revert"
1387 git_remove="${git_remove#./}"
1389 tg_state=
1390 tg_remove=
1391 tg_topmerge=
1392 if [ -e "$git_dir/tg-update" ]; then
1393 tg_state="update"
1394 tg_remove="$git_dir/tg-update"
1395 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1397 tg_remove="${tg_remove#./}"
1400 # Show status information
1401 do_status()
1403 do_status_result=0
1404 do_status_verbose=
1405 do_status_help=
1406 abbrev=refs
1407 pfx=
1408 while [ $# -gt 0 ] && case "$1" in
1409 --help|-h)
1410 do_status_help=1
1411 break;;
1412 -vv)
1413 # kludge in this common bundling option
1414 abbrev=
1415 do_status_verbose=1
1416 pfx="## "
1418 --verbose|-v)
1419 [ -z "$do_status_verbose" ] || abbrev=
1420 do_status_verbose=1
1421 pfx="## "
1423 --exit-code)
1424 do_status_result=2
1427 die "unknown status argument: $1"
1429 esac; do shift; done
1430 if [ -n "$do_status_help" ]; then
1431 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1432 return
1434 check_status
1435 symref="$(git symbolic-ref --quiet HEAD)" || :
1436 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1437 if [ -n "$symref" ]; then
1438 uprefpart=
1439 if [ -n "$headrv" ]; then
1440 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1441 if [ -n "$upref" ]; then
1442 uprefpart=" ... ${upref#$abbrev/remotes/}"
1443 mbase="$(git merge-base HEAD "$upref")" || :
1444 ahead="$(git rev-list --count HEAD ${mbase:+--not $mbase})" || ahead=0
1445 behind="$(git rev-list --count "$upref" ${mbase:+--not $mbase})" || behind=0
1446 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1447 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1448 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1449 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1450 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1453 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1454 else
1455 echol "${pfx}HEAD -> ${headrv:-?}"
1457 if [ -n "$tg_state" ]; then
1458 extra=
1459 if [ "$tg_state" = "update" ]; then
1460 IFS= read -r uname <"$git_dir/tg-update/name" || :
1461 [ -z "$uname" ] ||
1462 extra="; currently updating branch '$uname'"
1464 echol "${pfx}tg $tg_state in progress$extra"
1465 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1466 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1467 cat "$git_dir/tg-update/fullcmd"
1468 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1469 if [ $bcnt -gt 1 ]; then
1470 pcnt=0
1471 ! [ -s "$git_dir/tg-update/processed" ] ||
1472 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1473 echo "${pfx}$pcnt of $bcnt branches updated so far"
1476 if [ "$tg_state" = "update" ]; then
1477 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1478 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1479 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1480 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1483 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1484 if [ "$git_state" = "merge" ]; then
1485 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1486 if [ $ucnt -gt 0 ]; then
1487 echo "${pfx}"'fix conflicts and then "git commit" the result'
1488 else
1489 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1492 if [ -z "$git_state" ]; then
1493 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository
1494 gspcnt=0
1495 [ -z "$gsp" ] ||
1496 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1497 untr=
1498 if [ "$gspcnt" -eq 0 ]; then
1499 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1500 echo "${pfx}working directory is clean$untr"
1501 [ -n "$tg_state" ] || do_status_result=0
1502 else
1503 echo "${pfx}working directory is DIRTY"
1504 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1509 ## Pager stuff
1511 # isatty FD
1512 isatty()
1514 test -t $1
1517 # pass "diff" to get pager.diff
1518 # if pager.$1 is a boolean false returns cat
1519 # if set to true or unset fails
1520 # otherwise succeeds and returns the value
1521 get_pager()
1523 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1524 [ "$_x" != "true" ] || return 1
1525 echo "cat"
1526 return 0
1528 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1529 echol "$_x"
1530 return 0
1532 return 1
1535 # setup_pager
1536 # Set TG_PAGER to a valid executable
1537 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1538 # See also the following "page" function for ease of use
1539 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1540 # Preference is (same as Git):
1541 # 1. GIT_PAGER
1542 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1543 # 3. core.pager (only if set)
1544 # 4. PAGER
1545 # 5. git var GIT_PAGER
1546 # 6. less
1547 setup_pager()
1549 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1551 emptypager=
1552 if [ -z "$TG_PAGER_IN_USE" ]; then
1553 # TG_PAGER = GIT_PAGER | PAGER | less
1554 # NOTE: GIT_PAGER='' is significant
1555 if [ -n "${GIT_PAGER+set}" ]; then
1556 TG_PAGER="$GIT_PAGER"
1557 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1558 TG_PAGER="$_dp"
1559 elif _cp="$(git config core.pager 2>/dev/null)"; then
1560 TG_PAGER="$_cp"
1561 elif [ -n "${PAGER+set}" ]; then
1562 TG_PAGER="$PAGER"
1563 else
1564 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1565 [ "$_gp" != ":" ] || _gp=
1566 TG_PAGER="${_gp:-less}"
1568 if [ -z "$TG_PAGER" ]; then
1569 emptypager=1
1570 TG_PAGER=cat
1572 else
1573 emptypager=1
1574 TG_PAGER=cat
1577 # Set pager default environment variables
1578 # see pager.c:setup_pager
1579 if [ -z "${LESS+set}" ]; then
1580 LESS="-FRX"
1581 export LESS
1583 if [ -z "${LV+set}" ]; then
1584 LV="-c"
1585 export LV
1588 # this is needed so e.g. $(git diff) will still colorize it's output if
1589 # requested in ~/.gitconfig with color.diff=auto
1590 GIT_PAGER_IN_USE=1
1591 export GIT_PAGER_IN_USE
1593 # this is needed so we don't get nested pagers
1594 TG_PAGER_IN_USE=1
1595 export TG_PAGER_IN_USE
1598 # page eval_arg [arg ...]
1600 # Calls setup_pager then evals the first argument passing it all the rest
1601 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1602 # by setup_pager (in which case the output is left as-is).
1604 # To handle arbitrary paging duties, collect lines to be paged into a
1605 # function and then call page with the function name or perhaps func_name "$@".
1607 # If no arguments at all are passed in do nothing (return with success).
1608 page()
1610 [ $# -gt 0 ] || return 0
1611 setup_pager
1612 _evalarg="$1"; shift
1613 if [ -n "$emptypager" ]; then
1614 eval "$_evalarg" '"$@"'
1615 else
1616 eval "$_evalarg" '"$@"' | eval "$TG_PAGER"
1620 # get_temp NAME [-d]
1621 # creates a new temporary file (or directory with -d) in the global
1622 # temporary directory $tg_tmp_dir with pattern prefix NAME
1623 get_temp()
1625 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1628 # automatically called by strftime
1629 # does nothing if already setup
1630 # may be called explicitly if the first call would otherwise be in a subshell
1631 # so that the setup is only done once before subshells start being spawned
1632 setup_strftime()
1634 [ -z "$strftime_is_setup" ] || return 0
1636 # date option to format raw epoch seconds values
1637 daterawopt=
1638 _testes='951807788'
1639 _testdt='2000-02-29 07:03:08 UTC'
1640 _testfm='%Y-%m-%d %H:%M:%S %Z'
1641 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1642 daterawopt='-d@'
1643 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1644 daterawopt='-r'
1646 strftime_is_setup=1
1649 # $1 => strftime format string to use
1650 # $2 => raw timestamp as seconds since epoch
1651 # $3 => optional time zone string (empty/absent for local time zone)
1652 strftime()
1654 setup_strftime
1655 if [ -n "$daterawopt" ]; then
1656 if [ -n "$3" ]; then
1657 TZ="$3" date "$daterawopt$2" "+$1"
1658 else
1659 date "$daterawopt$2" "+$1"
1661 else
1662 if [ -n "$3" ]; then
1663 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1664 else
1665 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1670 got_cdup_result=
1671 git_cdup_result=
1672 v_get_show_cdup()
1674 if [ -z "$got_cdup_result" ]; then
1675 git_cdup_result="$(git rev-parse --show-cdup)"
1676 got_cdup_result=1
1678 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1681 setup_git_dirs()
1683 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1684 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1685 git_dir="$(cd "$git_dir" && pwd)"
1687 if [ -z "$git_common_dir" ]; then
1688 if vcmp "$git_version" '>=' "2.5"; then
1689 # rev-parse --git-common-dir is broken and may give
1690 # an incorrect result unless the current directory is
1691 # already set to the top level directory
1692 v_get_show_cdup
1693 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1694 else
1695 git_common_dir="$git_dir"
1698 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1699 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1700 git_hooks_dir="$git_common_dir/hooks"
1701 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1702 case "$gchp" in
1703 /[!/]*)
1704 git_hooks_dir="$gchp"
1707 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1709 esac
1710 unset gchp
1714 basic_setup()
1716 setup_git_dirs $1
1717 if [ -z "$base_remote" ]; then
1718 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
1719 base_remote="$TG_EXPLICIT_REMOTE"
1720 else
1721 base_remote="$(git config topgit.remote 2>/dev/null)" || :
1724 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1725 tgnosequester=
1726 [ "$tgsequester" != "false" ] || tgnosequester=1
1727 unset tgsequester
1729 # catch errors if topbases is used without being set
1730 unset tg_topbases_set
1731 topbases="programmer*:error"
1732 topbasesrx="programmer*:error}"
1733 oldbases="$topbases"
1736 ## Initial setup
1737 initial_setup()
1739 # suppress the merge log editor feature since git 1.7.10
1741 GIT_MERGE_AUTOEDIT=no
1742 export GIT_MERGE_AUTOEDIT
1744 basic_setup $1
1745 iowopt=
1746 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
1747 gcfbopt=
1748 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
1749 auhopt=
1750 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1751 v_get_show_cdup root_dir
1752 root_dir="${root_dir:-.}"
1753 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1754 [ "$logrefupdates" = "true" ] || logrefupdates=
1756 # make sure root_dir doesn't end with a trailing slash.
1758 root_dir="${root_dir%/}"
1760 # create global temporary directories, inside GIT_DIR
1762 tg_tmp_dir=
1763 trap 'rm -rf "$tg_tmp_dir"' EXIT
1764 trap 'exit 129' HUP
1765 trap 'exit 130' INT
1766 trap 'exit 131' QUIT
1767 trap 'exit 134' ABRT
1768 trap 'exit 143' TERM
1769 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1770 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1771 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1772 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1773 tg_ref_cache_br="$tg_ref_cache.br"
1774 tg_ref_cache_rbr="$tg_ref_cache.rbr"
1775 tg_ref_cache_ann="$tg_ref_cache.ann"
1776 tg_ref_cache_dep="$tg_ref_cache.dep"
1777 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_ref_cache"; } >/dev/null 2>&1 ||
1778 die "could not create a writable temporary directory"
1780 # make sure global cache directory exists inside GIT_DIR or $tg_tmp_dir
1782 user_id_no="$(id -u)" || :
1783 : "${user_id_no:=_99_}"
1784 tg_cache_dir="$git_common_dir/tg-cache"
1785 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1786 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
1787 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1788 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1789 if [ -z "$tg_cache_dir" ]; then
1790 tg_cache_dir="$tg_tmp_dir/tg-cache"
1791 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1792 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1794 [ -n "$tg_cache_dir" ] ||
1795 die "could not create a writable tg-cache directory (even a temporary one)"
1797 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
1798 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
1799 # so we avoid it if possible and require v2.11.1 to do it at all
1800 # otherwise just don't make an alternates temporary store in that case;
1801 # it's okay to not have one; everything will still work; the nicety of
1802 # making the temporary tree objects vanish when tg exits just won't
1803 # happen in that case but nothing will break also be sure to reuse
1804 # the parent's if we've been recursively invoked and it's for the
1805 # same repository we were invoked on
1807 tg_use_alt_odb=1
1808 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
1809 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] || tg_use_alt_odb=
1810 _fulltmpdir=
1811 [ -z "$tg_use_alt_odb" ] || _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
1812 case "$_fulltmpdir" in *[";:"]*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
1813 _fullodbdir=
1814 [ -z "$tg_use_alt_odb" ] || _fullodbdir="$(cd "$_odbdir" && pwd -P)"
1815 if [ -n "$tg_use_alt_odb" ] && [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
1816 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
1817 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
1818 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
1819 tg_use_alt_odb=2
1822 if [ "$tg_use_alt_odb" = "1" ]; then
1823 # create an alternate objects database to keep the ephemeral objects in
1824 mkdir -p "$tg_tmp_dir/objects/info"
1825 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
1826 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
1827 case "$TG_OBJECT_DIRECTORY" in
1828 *[";:"]*)
1829 # surround in "..." and backslash-escape internal '"' and '\\'
1830 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
1831 sed 's/\([""\\]\)/\\\1/g')\""
1834 _altodbdq="$TG_OBJECT_DIRECTORY"
1836 esac
1837 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1838 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
1839 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1840 else
1841 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
1843 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
1847 set_topbases()
1849 # refer to "top-bases" in a refname with $topbases
1851 [ -z "$tg_topbases_set" ] || return 0
1853 topbases_implicit_default=1
1854 # See if topgit.top-bases is set to heads or refs
1855 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
1856 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
1857 if [ -n "$1" ]; then
1858 # never die on the hook script
1859 unset tgtb
1860 else
1861 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
1864 if [ -n "$tgtb" ]; then
1865 case "$tgtb" in
1866 heads)
1867 topbases="heads/{top-bases}"
1868 topbasesrx="heads/[{]top-bases[}]"
1869 oldbases="top-bases";;
1870 refs)
1871 topbases="top-bases"
1872 topbasesrx="top-bases"
1873 oldbases="heads/{top-bases}";;
1874 esac
1875 # MUST NOT be exported
1876 unset tgtb tg_topbases_set topbases_implicit_default
1877 tg_topbases_set=1
1878 return 0
1880 unset tgtb
1882 # check heads and top-bases and see what state the current
1883 # repository is in. remotes are ignored.
1885 hblist=" "
1886 topbases=
1887 both=
1888 newtb="heads/{top-bases}"
1889 while read -r rn && [ -n "$rn" ]; do case "$rn" in
1890 "refs/heads/{top-bases}"/*)
1891 case "$hblist" in *" ${rn#refs/$newtb/} "*)
1892 if [ "$topbases" != "heads/{top-bases}" ] && [ -n "$topbases" ]; then
1893 both=1
1894 break;
1895 else
1896 topbases="heads/{top-bases}"
1897 topbasesrx="heads/[{]top-bases[}]"
1898 oldbases="top-bases"
1900 esac;;
1901 "refs/top-bases"/*)
1902 case "$hblist" in *" ${rn#refs/top-bases/} "*)
1903 if [ "$topbases" != "top-bases" ] && [ -n "$topbases" ]; then
1904 both=1
1905 break;
1906 else
1907 topbases="top-bases"
1908 topbasesrx="top-bases"
1909 oldbases="heads/{top-bases}"
1911 esac;;
1912 "refs/heads"/*)
1913 hblist="$hblist${rn#refs/heads/} ";;
1914 esac; done <<-EOT
1915 $(git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null)
1917 if [ -n "$both" ]; then
1918 if [ -n "$1" ]; then
1919 # hook script always prefers newer without complaint
1920 topbases="heads/{top-bases}"
1921 topbasesrx="heads/[{]top-bases[}]"
1922 oldbases="top-bases"
1923 else
1924 # Complain and die
1925 err "repository contains existing TopGit branches"
1926 err "but some use refs/top-bases/... for the base"
1927 err "and some use refs/heads/{top-bases}/... for the base"
1928 err "with the latter being the new, preferred location"
1929 err "set \"topgit.top-bases\" to either \"heads\" to use"
1930 err "the new heads/{top-bases} location or \"refs\" to use"
1931 err "the old top-bases location."
1932 err "(the tg migrate-bases command can also resolve this issue)"
1933 die "schizophrenic repository requires topgit.top-bases setting"
1935 elif [ -n "$topbases" ]; then
1936 unset topbases_implicit_default
1939 [ -n "$topbases" ] || {
1940 # default is still top-bases for now
1941 topbases="top-bases"
1942 topbasesrx="top-bases"
1943 oldbases="heads/{top-bases}"
1945 # MUST NOT be exported
1946 unset hblist both newtb rn tg_topases_set
1947 tg_topbases_set=1
1948 return 0
1951 # init_reflog "ref"
1952 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
1953 # an empty log file to exist so that ref changes will be logged
1954 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
1955 # However, if "$1" is "refs/tgstash" then always make the reflog
1956 # The only ref not under refs/ that Git will write a reflog for is HEAD;
1957 # no matter what, it will NOT update a reflog for any other bare refs so
1958 # just quietly succeed when passed TG_STASH without doing anything.
1959 init_reflog()
1961 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
1962 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
1963 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
1964 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
1965 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
1968 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
1969 # a symbolic link. The directory part must exist, but the basename need not.
1970 v_get_abs_path()
1972 [ -n "$1" ] && [ -n "$2" ] || return 1
1973 set -- "$1" "$2" "${2%/}"
1974 case "$3" in
1975 */*) set -- "$1" "$2" "${3%/*}";;
1976 * ) set -- "$1" "$2" ".";;
1977 esac
1978 case "$2" in */)
1979 set -- "$1" "${2%/}" "$3" "/"
1980 esac
1981 [ -d "$3" ] || return 1
1982 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
1985 ## Startup
1987 : "${TG_INST_CMDDIR:=@cmddir@}"
1988 : "${TG_INST_SHAREDIR:=@sharedir@}"
1989 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1991 [ -d "$TG_INST_CMDDIR" ] ||
1992 die "No command directory: '$TG_INST_CMDDIR'"
1994 ## Include awk scripts and their utility functions (separated for easier debugging)
1996 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
1997 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
1998 . "$TG_INST_CMDDIR/tg--awksome"
2000 if [ -n "$tg__include" ]; then
2002 # We were sourced from another script for our utility functions;
2003 # this is set by hooks. Skip the rest of the file. A simple return doesn't
2004 # work as expected in every shell. See http://bugs.debian.org/516188
2006 # ensure setup happens
2008 initial_setup 1
2009 set_topbases 1
2011 else
2013 set -e
2015 tgbin="$0"
2016 tgdir="${tgbin%/}"
2017 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
2018 tgdir="${tgdir%/*}/"
2019 tgname="${tgbin##*/}"
2020 [ "$0" != "$tgname" ] || tgdir=""
2022 # If tg contains a '/' but does not start with one then replace it with an absolute path
2024 case "$0" in /*) ;; */*)
2025 tgdir="$(cd "${0%/*}" && pwd -P)/"
2026 tgbin="$tgdir$tgname"
2027 esac
2029 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
2030 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2032 tgdisplaydir="$tgdir"
2033 tgdisplay="$tgbin"
2034 tgdisplayac="$tgdisplay"
2036 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2037 _tgabs="$_tgnameabs" &&
2038 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2039 [ "$_tgabs" = "$_tgnameabs" ]
2040 then
2041 tgdisplaydir=""
2042 tgdisplay="$tgname"
2043 tgdisplayac="$tgdisplay"
2045 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2046 unset _tgabs _tgnameabs
2048 tg() { command "$tgbin" "$@"; }
2050 explicit_remote=
2051 explicit_dir=
2052 gitcdopt=
2053 noremote=
2055 cmd=
2056 while :; do case "$1" in
2058 help|--help|-h)
2059 cmd=help
2060 shift
2061 break;;
2063 status|--status)
2064 cmd=status
2065 shift
2066 break;;
2068 --hooks-path)
2069 cmd=hooks-path
2070 shift
2071 break;;
2073 --exec-path)
2074 cmd=exec-path
2075 shift
2076 break;;
2078 --top-bases)
2079 cmd=top-bases
2080 shift
2081 break;;
2084 shift
2085 if [ -z "$1" ]; then
2086 echo "Option -r requires an argument." >&2
2087 do_help
2088 exit 1
2090 unset noremote
2091 base_remote="$1"
2092 explicit_remote="$base_remote"
2093 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2094 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2095 shift;;
2098 unset base_remote explicit_remote
2099 noremote=1
2100 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2101 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2102 shift;;
2105 shift
2106 if [ -z "$1" ]; then
2107 echo "Option -C requires an argument." >&2
2108 do_help
2109 exit 1
2111 cd "$1"
2112 unset GIT_DIR GIT_COMMON_DIR
2113 if [ -z "$explicit_dir" ]; then
2114 explicit_dir="$1"
2115 else
2116 explicit_dir="$PWD"
2118 gitcdopt=" -C \"$explicit_dir\""
2119 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2120 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2121 tgdisplayac="$tgdisplay"
2122 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2123 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2124 shift;;
2127 shift
2128 if [ -z "$1" ]; then
2129 echo "Option -c requires an argument." >&2
2130 do_help
2131 exit 1
2133 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2134 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2135 export GIT_CONFIG_PARAMETERS
2136 shift;;
2139 shift
2140 break;;
2143 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2144 do_help
2145 exit 1;;
2148 break;;
2150 esac; done
2152 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
2154 ## Dispatch
2156 [ -n "$cmd" ] || { do_help; exit 1; }
2158 case "$cmd" in
2160 help)
2161 do_help "$@"
2162 exit 0;;
2164 status|st)
2165 unset base_remote
2166 basic_setup
2167 set_topbases
2168 do_status "$@"
2169 exit ${do_status_result:-0};;
2171 hooks-path)
2172 # Internal command
2173 echol "$TG_INST_HOOKSDIR";;
2175 exec-path)
2176 # Internal command
2177 echol "$TG_INST_CMDDIR";;
2179 top-bases)
2180 # Maintenance command
2181 ! git rev-parse --git-dir >/dev/null 2>&1 || setup_git_dirs
2182 set_topbases
2183 echol "refs/$topbases";;
2186 isutil=
2187 case "$cmd" in index-merge-one-file)
2188 isutil="-"
2189 esac
2190 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2191 looplevel="$TG_ALIAS_DEPTH"
2192 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2193 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2194 looplevel=0
2195 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2196 [ -n "$tgalias" ] || {
2197 echo "Unknown subcommand: $cmd" >&2
2198 do_help
2199 exit 1
2201 looplevel=$(( $looplevel + 1 ))
2202 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2203 TG_ALIAS_DEPTH="$looplevel"
2204 export TG_ALIAS_DEPTH
2205 if [ "!${tgalias#?}" = "$tgalias" ]; then
2206 unset GIT_PREFIX
2207 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2208 GIT_PREFIX="$pfx"
2209 export GIT_PREFIX
2211 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2212 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2213 else
2214 eval 'exec "$tgbin"' "$tgalias" '"$@"'
2216 die "alias execution failed for: $tgalias"
2218 unset TG_ALIAS_DEPTH
2220 showing_help=
2221 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2222 showing_help=1
2225 [ -n "$showing_help" ] || initial_setup
2226 [ -z "$noremote" ] || unset base_remote
2228 nomergesetup="$showing_help"
2229 case "$cmd" in base|contains|info|log|rebase|revert|summary|tag)
2230 # avoid merge setup where not necessary
2232 nomergesetup=1
2233 esac
2235 if [ -z "$nomergesetup" ]; then
2236 # make sure merging the .top* files will always behave sanely
2238 setup_ours
2239 setup_hook "pre-commit"
2242 # everything but rebase needs topbases set
2243 carefully="$showing_help"
2244 [ "$cmd" != "migrate-bases" ] || carefully=1
2245 [ "$cmd" = "rebase" ] || set_topbases $carefully
2247 _use_ref_cache=
2248 tg_read_only=1
2249 case "$cmd$showing_help" in
2250 contains|export|info|summary|tag)
2251 _use_ref_cache=1;;
2252 annihilate|create|delete|depend|import|update)
2253 tg_use_alt_odb=
2254 tg_read_only=;;
2255 esac
2256 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2258 fullcmd="${tgname:-tg} $cmd $*"
2259 . "$TG_INST_CMDDIR"/tg-$isutil$cmd;;
2260 esac