awk/ref_match.awk: minor optimizations and typo fixes
[topgit/pro.git] / tg.sh
blobb1085d2544853213ef9ab51e36c2d09357b0fe14
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.8
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 mkdir -p "$tg_tmp_dir/cached/refs"
527 awk '{x = $1; sub(/^refs\//, "", x); if (x != "") print x}' <"$tg_ref_cache" | tr '\n' '\0' | {
528 cd "$tg_tmp_dir/cached/refs" &&
529 xargs -0 mkdir -p
531 awk -v p="$tg_tmp_dir/cached/" '
532 NF == 2 && $1 ~ /^refs\/./ && $2 ~ /^[0-9a-fA-F]{4,}$/ {
533 fn = p $1 "/.ref"
534 print "0 " $2 >fn
535 close(fn)
537 ' <"$tg_ref_cache"
538 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
541 # If the first argument is non-empty, stores "1" there if this call created the cache
542 v_create_ref_cache()
544 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
545 _remotespec=
546 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
547 [ -z "$1" ] || eval "$1=1"
548 git for-each-ref --format='%(refname) %(objectname)' \
549 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
550 create_ref_dirs
553 remove_ref_cache()
555 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
556 >"$tg_ref_cache"
557 >"$tg_ref_cache_br"
558 >"$tg_ref_cache_rbr"
559 >"$tg_ref_cache_ann"
560 >"$tg_ref_cache_dep"
563 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
564 rev_parse()
566 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
567 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
568 else
569 [ -z "$tg_ref_cache_only" ] || return 1
570 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
574 # ref_exists_rev REF
575 # Whether REF is a valid ref name
576 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
577 # or, if $base_remote is set, refs/remotes/$base_remote/
578 # Caches result if $tg_read_only and outputs HASH on success
579 ref_exists_rev()
581 case "$1" in
582 refs/*)
584 $octet20)
585 printf '%s' "$1"
586 return;;
588 die "ref_exists_rev requires fully-qualified ref name (given: $1)"
589 esac
590 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
591 _result=
592 _result_rev=
593 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
594 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
595 _result_rev="$(rev_parse "$1")"
596 _result=$?
597 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
598 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
599 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
600 printf '%s' "$_result_rev"
601 return $_result
604 # Same as ref_exists_rev but output is abbreviated hash
605 # Optional second argument defaults to --short but may be any --short=.../--no-short option
606 ref_exists_rev_short()
608 case "$1" in
609 refs/*)
611 $octet20)
614 die "ref_exists_rev_short requires fully-qualified ref name"
615 esac
616 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
617 _result=
618 _result_rev=
619 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
620 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
621 _result_rev="$(rev_parse "$1")"
622 _result=$?
623 if [ $_result -eq 0 ]; then
624 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev^0" --)"
625 _result=$?
627 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
628 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
629 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
630 printf '%s' "$_result_rev"
631 return $_result
634 # ref_exists REF
635 # Whether REF is a valid ref name
636 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
637 # or, if $base_remote is set, refs/remotes/$base_remote/
638 # Caches result
639 ref_exists()
641 ref_exists_rev "$1" >/dev/null
644 # rev_parse_tree REF
645 # Runs git rev-parse REF^{tree}
646 # Caches result if $tg_read_only
647 rev_parse_tree()
649 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
650 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
651 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
652 printf '%s\n' "$_result"
653 return 0
655 return 1
657 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
658 if [ -d "$tg_tmp_dir/cached/$1" ]; then
659 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
660 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
661 printf '%s\n' "$_result"
662 return 0
664 return 1
666 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
669 # has_remote BRANCH
670 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
671 has_remote()
673 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
676 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
677 # If -z "$1" still set return code but do not return result
678 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
679 # refs/heads/... then ... will be verified instead.
680 # if "$3" = "-f" (for fail) then return an error rather than dying.
681 v_verify_topgit_branch()
683 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
684 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
685 [ -n "$_verifyname" -o "$3" = "-f" ] || die "HEAD is not a symbolic ref"
686 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
687 [ "$3" != "-f" ] || return 1
688 die "HEAD is not a symbolic ref to the refs/heads namespace"
689 esac
690 set -- "$1" "$_verifyname" "$3"
692 case "$2" in
693 refs/"$topbases"/*)
694 _verifyname="${2#refs/$topbases/}"
696 refs/heads/*)
697 _verifyname="${2#refs/heads/}"
700 _verifyname="$2"
702 esac
703 if ! ref_exists "refs/heads/$_verifyname"; then
704 [ "$3" != "-f" ] || return 1
705 die "no such branch: $_verifyname"
707 if ! ref_exists "refs/$topbases/$_verifyname"; then
708 [ "$3" != "-f" ] || return 1
709 die "not a TopGit-controlled branch: $_verifyname"
711 [ -z "$1" ] || eval "$1="'"$_verifyname"'
714 # Return the verified TopGit branch name or die with an error.
715 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
716 # refs/heads/... then ... will be verified instead.
717 # if "$2" = "-f" (for fail) then return an error rather than dying.
718 verify_topgit_branch()
720 v_verify_topgit_branch _verifyname "$@" || return
721 printf '%s' "$_verifyname"
724 # Caches result
725 # $1 = branch name (i.e. "t/foo/bar")
726 # $2 = optional result of rev-parse "refs/heads/$1"
727 # $3 = optional result of rev-parse "refs/$topbases/$1"
728 branch_annihilated()
730 _branch_name="$1"
731 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
732 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
734 _result=
735 _result_rev=
736 _result_rev_base=
737 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/refs/heads/$_branch_name/.ann"; } 2>/dev/null || :
738 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
740 # use the merge base in case the base is ahead.
741 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
743 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
744 _result=$?
745 [ -d "$tg_cache_dir/refs/heads/$_branch_name" ] || mkdir -p "$tg_cache_dir/refs/heads/$_branch_name" 2>/dev/null
746 [ ! -d "$tg_cache_dir/refs/heads/$_branch_name" ] ||
747 echo $_result $_rev $_rev_base >"$tg_cache_dir/refs/heads/$_branch_name/.ann" 2>/dev/null || :
748 return $_result
751 non_annihilated_branches()
753 refscacheopt="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
754 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
755 refscacheopt="$refscacheopt"'-r="$tg_ref_cache" "refs/$topbases"'
757 eval run_awk_topgit_branches -n "$refscacheopt" '"refs/$topbases" "$@"'
760 # Make sure our tree is clean
761 # if optional "$1" given also verify that a checkout to "$1" would succeed
762 ensure_clean_tree()
764 check_status
765 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
766 git update-index --ignore-submodules --refresh ||
767 die "the working directory has uncommitted changes (see above) - first commit or reset them"
768 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
769 die "the index has uncommited changes"
770 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
771 die "git checkout \"$1\" would fail"
774 # Make sure .topdeps and .topmsg are "clean"
775 # They are considered "clean" if each is identical in worktree, index and HEAD
776 # With "-u" as the argument skip the HEAD check (-u => unborn)
777 # untracked .topdeps and/or .topmsg files are always considered "dirty" as well
778 # with -u them just existing constitutes "dirty"
779 ensure_clean_topfiles()
781 _dirtw=0
782 _dirti=0
783 _dirtu=0
784 _check="$(git diff-files --ignore-submodules --name-only -- :/.topdeps :/.topmsg)" &&
785 [ -z "$_check" ] || _dirtw=1
786 if [ "$1" != "-u" ]; then
787 _check="$(git diff-index --cached --ignore-submodules --name-only HEAD -- :/.topdeps :/.topmsg)" &&
788 [ -z "$_check" ] || _dirti=1
790 if [ "$_dirti$_dirtw" = "00" ]; then
791 v_get_show_cdup
792 if [ -e "${git_cdup_result}.topdeps" ] || [ -e "${git_cdup_result}.topmsg" ]; then
793 [ "$1" != "-u" ] &&
794 _check="$(git status --porcelain --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg)" &&
795 [ -z "$_check" ] || _dirtu=1
798 if [ "$_dirtu$_dirti$_dirtw" != "000" ]; then
799 git status --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg || :
800 case "$_dirtu$_dirti$_dirtw" in
801 001) die "the working directory has uncommitted changes (see above) - first commit or reset them";;
802 010) die "the index has uncommited changes (see above)";;
803 011) die "the working directory and index have uncommitted changes (see above) - first commit or reset them";;
804 100) die "the working directory has untracked files that would be overwritten (see above)";;
805 esac
809 # is_sha1 REF
810 # Whether REF is a SHA1 (compared to a symbolic name).
811 is_sha1()
813 case "$1" in $octet20) return 0;; esac
814 return 1
817 # navigate_deps <run_awk_topgit_navigate options and arguments>
818 # all options and arguments are passed through to run_awk_topgit_navigate
819 # except for a leading -td= option, if any, which is picked off for deps
820 # after arranging to feed it a suitable deps list
821 navigate_deps()
823 dogfer=
824 dorad=1
825 userc=
826 tmpdep=
827 ratd_opts="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
828 ratn_opts=
829 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
830 userc=1
831 tmprfs="$tg_ref_cache"
832 tmptgbr="$tg_ref_cache_br"
833 tmpann="$tg_ref_cache_ann"
834 tmpdep="$tg_ref_cache_dep"
835 [ -s "$tg_ref_cache" ] || dogfer=1
836 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
837 else
838 ratd_opts="${ratd_opts}-rmr"
839 ratn_opts="-rma -rmb"
840 tmprfs="$tg_tmp_dir/refs.$$"
841 tmpann="$tg_tmp_dir/ann.$$"
842 tmptgbr="$tg_tmp_dir/tgbr.$$"
843 dogfer=1
845 refpats="\"refs/heads\" \"refs/\$topbases\""
846 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
847 [ -z "$dogfer" ] ||
848 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
849 depscmd="run_awk_topgit_deps $ratd_opts"
850 case "$1" in -td=*)
851 userc=
852 depscmd="$depscmd $1"
853 shift
854 esac
855 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -m="$mtblob" -s "refs/$topbases"'
856 if [ -n "$userc" ]; then
857 if [ -n "$dorad" ]; then
858 eval "$depscmd" >"$tmpdep"
860 depscmd='<"$tmpdep" '
861 else
862 depscmd="$depscmd |"
864 eval "$depscmd" run_awk_topgit_navigate '-a="$tmpann" -b="$tmptgbr"' "$ratn_opts" '"$@"'
867 # recurse_deps_internal NAME [BRANCHPATH...]
868 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
869 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
870 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
871 # but missing and remotes are always "0"
872 # then the branch name followed by its depedency chain (which might be empty)
873 # An output line might look like this:
874 # 0 1 1 t/foo/leaf t/foo/int t/stage
875 # If no_remotes is non-empty, exclude remotes
876 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
877 # If with_top_level is non-empty, include the top-level that's normally omitted
878 # any branch names in the space-separated recurse_deps_exclude variable
879 # are skipped (along with their dependencies)
880 recurse_deps_internal()
882 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
883 ratr_opts="${recurse_preorder:+-f} ${with_top_level:+-s}"
884 dogfer=
885 dorad=1
886 userc=
887 tmpdep=
888 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
889 userc=1
890 tmprfs="$tg_ref_cache"
891 tmptgbr="$tg_ref_cache_br"
892 tmpann="$tg_ref_cache_ann"
893 tmpdep="$tg_ref_cache_dep"
894 [ -s "$tg_ref_cache" ] || dogfer=1
895 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
896 else
897 ratr_opts="$ratr_opts -rmh -rma -rmb"
898 tmprfs="$tg_tmp_dir/refs.$$"
899 tmpann="$tg_tmp_dir/ann.$$"
900 tmptgbr="$tg_tmp_dir/tgbr.$$"
901 dogfer=1
903 refpats="\"refs/heads\" \"refs/\$topbases\""
904 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
905 tmptgrmtbr=
906 dorab=1
907 if [ -z "$no_remotes" ] && [ -n "$base_remote" ]; then
908 if [ -n "$userc" ]; then
909 tmptgrmtbr="$tg_ref_cache_rbr"
910 [ -n "$dogfer" ] || ! [ -s "$tmptgrmtbr" ] || dorab=
911 else
912 tmptgrmtbr="$tg_tmp_dir/tgrmtbr.$$"
913 ratr_opts="$ratr_opts -rmr"
915 ratr_opts="$ratr_opts -r=\"\$tmptgbr\" -u=\"refs/remotes/\$base_remote/\${topbases#heads/}\""
917 [ -z "$dogfer" ] ||
918 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
919 if [ -n "$tmptgrmtbr" ] && [ -n "$dorab" ]; then
920 run_awk_topgit_branches -n -h="refs/remotes/$base_remote" -r="$tmprfs" \
921 "refs/remotes/$base_remote/${topbases#heads/}" >"$tmptgrmtbr"
923 depscmd="run_awk_topgit_deps${TG_DEBUG:+ -p=\"\$tg_ref_cache.pre\"}"
924 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -m="$mtblob" "refs/$topbases"'
925 if [ -n "$userc" ]; then
926 if [ -n "$dorad" ]; then
927 eval "$depscmd" >"$tmpdep"
929 depscmd='<"$tmpdep" '
930 else
931 depscmd="$depscmd |"
933 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
934 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
937 # do_eval CMD
938 # helper for recurse_deps so that a return statement executed inside CMD
939 # does not return from recurse_deps. This shouldn't be necessary, but it
940 # seems that it actually is.
941 do_eval()
943 eval "$@"
946 # becomes read-only for caching purposes
947 # assigns new value to tg_read_only
948 # become_cacheable/undo_become_cacheable calls may be nested
949 become_cacheable()
951 _old_tg_read_only="$tg_read_only"
952 if [ -z "$tg_read_only" ]; then
953 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
954 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
955 tg_read_only=1
957 _my_ref_cache=
958 v_create_ref_cache _my_ref_cache
959 _my_ref_cache="${_my_ref_cache:+1}"
960 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
963 # restores tg_read_only and ref_cache to state before become_cacheable call
964 # become_cacheable/undo_bocome_cacheable calls may be nested
965 undo_become_cacheable()
967 case "$tg_read_only" in
968 "undo"[01]"-"*)
969 _suffix="${tg_read_only#undo?-}"
970 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
971 tg_read_only="$_suffix"
972 esac
975 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
976 become_non_cacheable()
978 remove_ref_cache
979 tg_read_only=
980 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
981 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
984 # call this to make sure Git will not complain about a missing user/email
985 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
986 ensure_ident_available()
988 [ -z "$TG_IDENT_CHECKED" ] || return 0
989 git var GIT_AUTHOR_IDENT >/dev/null &&
990 git var GIT_COMMITTER_IDENT >/dev/null || exit
991 TG_IDENT_CHECKED=1
992 export TG_IDENT_CHECKED
993 return 0
996 # recurse_deps [-o=<options string>] CMD NAME [BRANCHPATH...]
997 # Recursively eval CMD on all dependencies of NAME.
998 # Dependencies are visited in topological order.
999 # If <options string> is given, it's eval'd into the recurse_deps_internal
1000 # call just before the "--" that's passed just before NAME
1001 # CMD can refer to the following variables:
1003 # _ret starts as 0; CMD can change; will be final return result
1004 # _dep bare branch name or "refs/remotes/..." for a remote base
1005 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
1006 # _depchain 0+ space-separated branch names forming a path to top
1007 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
1008 # _dep_is_leaf boolean "1" if leaf; "" if not
1009 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
1010 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
1011 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
1013 # CMD may use a "return" statement without issue; its return value is ignored,
1014 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
1015 # will stop immediately and the value with the leading "-" stripped off will
1016 # be the final result code
1018 # CMD can refer to $_name for queried branch name,
1019 # $_dep for dependency name,
1020 # $_depchain for space-seperated branch backtrace,
1021 # $_dep_missing boolean to check whether $_dep is present
1022 # and the $_dep_is_tgish and $_dep_annihilated booleans.
1023 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
1024 # It can modify $_ret to affect the return value
1025 # of the whole function.
1026 # If recurse_deps() hits missing dependencies, it will append
1027 # them to space-separated $missing_deps list and skip them
1028 # after calling CMD with _dep_missing set.
1029 # remote dependencies are processed if no_remotes is unset.
1030 # any branch names in the space-separated recurse_deps_exclude variable
1031 # are skipped (along with their dependencies)
1033 # If no_remotes is non-empty, exclude remotes
1034 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1035 # If with_top_level is non-empty, include the top-level that's normally omitted
1036 # any branch names in the space-separated recurse_deps_exclude variable
1037 # are skipped (along with their dependencies)
1038 recurse_deps()
1040 _opts=
1041 case "$1" in -o=*) _opts="${1#-o=}"; shift; esac
1042 _cmd="$1"; shift
1044 _depsfile="$(get_temp tg-depsfile)"
1045 eval recurse_deps_internal "$_opts" -- '"$@"' >"$_depsfile" || :
1047 _ret=0
1048 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1049 _depchain="$_name${_deppath:+ $_deppath}"
1050 _dep_is_tgish=
1051 [ "$_istgish" = "0" ] || _dep_is_tgish=1
1052 _dep_has_remote=
1053 [ "$_istgish" != "2" ] || _dep_has_remote=1
1054 _dep_missing=
1055 if [ "$_ismissing" != "0" ]; then
1056 _dep_missing=1
1057 case " $missing_deps " in *" $_dep "*);;*)
1058 missing_deps="${missing_deps:+$missing_deps }$_dep"
1059 esac
1061 _dep_annihilated=
1062 _dep_is_leaf=
1063 if [ "$_isleaf" = "1" ]; then
1064 _dep_is_leaf=1
1065 elif [ "$_isleaf" = "2" ]; then
1066 _dep_annihilated=1
1068 do_eval "$_cmd" || :
1069 if [ "${_ret#-}" != "$_ret" ]; then
1070 _ret="${_ret#-}"
1071 break
1073 done <"$_depsfile"
1074 rm -f "$_depsfile"
1075 return ${_ret:-0}
1078 # find_leaves NAME
1079 # output (one per line) the unique leaves of NAME
1080 # a leaf is either
1081 # 1) a non-tgish dependency
1082 # 2) the base of a tgish dependency with no non-annihilated dependencies
1083 # duplicates are suppressed (by commit rev) and remotes are always ignored
1084 # if a leaf has an exact tag match that will be output
1085 # note that recurse_deps_exclude IS honored for this operation
1086 find_leaves()
1088 no_remotes=1
1089 with_top_level=1
1090 recurse_preorder=
1091 seen_leaf_refs=
1092 seen_leaf_revs=
1093 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1094 [ "$_isleaf" = "1" ] && [ "$_ismissing" = "0" ] || continue
1095 if [ "$_istgish" != "0" ]; then
1096 fulldep="refs/$topbases/$_dep"
1097 else
1098 fulldep="refs/heads/$_dep"
1100 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1101 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1102 if fullrev="$(ref_exists_rev "$fulldep")"; then
1103 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1104 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1105 # See if Git knows it by another name
1106 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1107 echo "refs/tags/$tagname"
1108 else
1109 echo "$fulldep"
1111 esac
1113 esac
1114 done <<-EOT
1115 $(recurse_deps_internal -l -o=1 -- "$1")
1117 with_top_level=
1120 # branch_needs_update
1121 # This is a helper function for determining whether given branch
1122 # is up-to-date wrt. its dependencies. It expects input as if it
1123 # is called as a recurse_deps() helper.
1124 # In case the branch does need update, it will echo it together
1125 # with the branch backtrace on the output (see needs_update()
1126 # description for details) and set $_ret to non-zero.
1127 branch_needs_update()
1129 if [ -n "$_dep_missing" ]; then
1130 echo "! $_dep $_depchain"
1131 return 0
1134 if [ -n "$_dep_is_tgish" ]; then
1135 [ -z "$_dep_annihilated" ] || return 0
1137 if [ -n "$_dep_has_remote" ]; then
1138 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
1139 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
1141 # We want to sync with our base first and should output this before
1142 # the remote branch, but the order does not actually matter to tg-update
1143 # as it just recurses regardless, but it does matter for tg-info (which
1144 # treats out-of-date bases as though they were already merged in) so
1145 # we output the remote before the base.
1146 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1147 echo ": $_dep $_depchain"
1148 _ret=1
1149 return
1153 if [ -n "$_name" ]; then
1154 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
1155 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1156 # Some new commits in _dep
1157 echo "$_dep $_depchain"
1158 _ret=1
1163 # needs_update NAME
1164 # This function is recursive; it outputs reverse path from NAME
1165 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1166 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
1167 # if the head is not in sync with the <remote> branch <name>, ':' if
1168 # the head is not in sync with the base (in this order of priority)
1169 # or '!' if dependency is missing. Note that the remote branch, base
1170 # order is reversed from the order they will actually be updated in
1171 # order to accomodate tg info which treats out-of-date items that are
1172 # only in the base as already being in the head for status purposes.
1173 # It will also return non-zero status if NAME needs update.
1174 # If needs_update() hits missing dependencies, it will append
1175 # them to space-separated $missing_deps list and skip them.
1176 needs_update()
1178 recurse_deps branch_needs_update "$1"
1181 # branch_empty NAME [-i | -w]
1182 branch_empty()
1184 if [ -z "$2" ]; then
1185 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1186 _result=
1187 _result_rev=
1188 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1189 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
1190 _result=0
1191 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1192 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1193 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1194 return $_result
1195 else
1196 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1200 v_get_tdmopt_internal()
1202 [ -n "$1" ] && [ -n "$3" ] || return 0
1203 [ "$2" = "-i" ] || [ "$2" = "-w" ] || return 0
1204 _optval=
1205 if v_verify_topgit_branch _tghead "HEAD" -f; then
1206 if [ "$2" = "-w" ] && [ -f "$root_dir/$3" ] && [ -r "$root_dir/$3" ]; then
1207 _opthash=
1208 if _opthash="$(git hash-object -w -t blob --stdin <"$root_dir/$3")" && [ -n "$_opthash" ]; then
1209 _optval="$4\"$_tghead:$_opthash\""
1211 elif [ "$2" = "-i" ]; then
1212 if _opthash="$(git rev-parse --quiet --verify ":0:$3" --)" && [ -n "$_opthash" ]; then
1213 _optval="$4\"$_tghead:$_opthash\""
1217 eval "$1="'"$_optval"'
1220 # set var $1 to the correct -td= option for use in an eval for $2 -i or -w mode
1221 v_get_tdopt() { v_get_tdmopt_internal "$1" "$2" ".topdeps" "-td="; }
1223 # set var $1 to the correct -tm= option for use in an eval for $2 -i or -w mode
1224 v_get_tmopt() { v_get_tdmopt_internal "$1" "$2" ".topmsg" "-tm="; }
1226 # checkout_symref_full [-f] FULLREF [SEED]
1227 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1228 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1229 # MUST be a committish which if present will be used instead of current FULLREF
1230 # (and FULLREF will be updated to it as well in that case)
1231 # Any merge state is always cleared by this function
1232 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1233 # instead of -m) but it will clear out any unmerged entries
1234 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1235 checkout_symref_full()
1237 _mode=-m
1238 _head="HEAD"
1239 if [ "$1" = "-f" ]; then
1240 _mode="--reset"
1241 _head=
1242 shift
1244 _ishash=
1245 case "$1" in
1246 refs/?*)
1248 $octet20)
1249 _ishash=1
1250 [ -z "$2" ] || [ "$1" = "$2" ] ||
1251 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1252 set -- HEAD "$1"
1255 die "programmer error: invalid checkout_symref_full \"$1\""
1257 esac
1258 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1259 die "invalid committish: \"${2:-$1}\""
1260 # Clear out any MERGE_HEAD kruft
1261 rm -f "$git_dir/MERGE_HEAD" || :
1262 # We have to do all the hard work ourselves :/
1263 # This is like git checkout -b "$1" "$2"
1264 # (or just git checkout "$1"),
1265 # but never creates a detached HEAD (unless $1 is a hash)
1266 git read-tree -u $_mode $_head "$_seedrev" &&
1268 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1269 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1270 } && {
1271 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1275 # switch_to_base NAME [SEED]
1276 switch_to_base()
1278 checkout_symref_full "refs/$topbases/$1" "$2"
1281 # run editor with arguments
1282 # the editor setting will be cached in $tg_editor (which is eval'd)
1283 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1284 # just in case, noalt_setup will be in effect while the editor is running
1285 run_editor()
1287 tg_editor="$GIT_EDITOR"
1288 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1290 noalt_setup
1291 eval "$tg_editor" '"$@"'
1295 # Show the help messages.
1296 do_help()
1298 _www=
1299 if [ "$1" = "-w" ]; then
1300 _www=1
1301 shift
1303 if [ -z "$1" ] ; then
1304 # This is currently invoked in all kinds of circumstances,
1305 # including when the user made a usage error. Should we end up
1306 # providing more than a short help message, then we should
1307 # differentiate.
1308 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1310 ## Build available commands list for help output
1312 cmds=
1313 sep=
1314 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1315 ! [ -r "$cmd" ] && continue
1316 # strip directory part and "tg-" prefix
1317 cmd="${cmd##*/}"
1318 cmd="${cmd#tg-}"
1319 [ "$cmd" != "migrate-bases" ] || continue
1320 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1321 cmds="$cmds$sep$cmd"
1322 sep="|"
1323 done
1325 echo "TopGit version $TG_VERSION - A different patch queue manager"
1326 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u]" \
1327 "[-c <name>=<val>] [--no-pager] ($cmds) ..."
1328 echo " Or: $tgname help [-w] [<command>]"
1329 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1330 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1331 if [ -n "$_www" ]; then
1332 nohtml=
1333 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1334 echo "${0##*/}: missing html help file:" \
1335 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1336 nohtml=1
1338 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1339 echo "${0##*/}: missing html help file:" \
1340 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1341 nohtml=1
1343 if [ -n "$nohtml" ]; then
1344 echo "${0##*/}: use" \
1345 "\"${0##*/} help $1\" instead" 1>&2
1346 exit 1
1348 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1349 exit
1351 output()
1353 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1354 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1355 echo
1356 elif [ "$1" = "help" ]; then
1357 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1358 echo
1359 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1360 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1361 echo
1363 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1364 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1367 page output "$1"
1368 else
1369 echo "${0##*/}: no help for $1" 1>&2
1370 do_help
1371 exit 1
1375 check_status()
1377 git_state=
1378 git_remove=
1379 if [ -e "$git_dir/MERGE_HEAD" ]; then
1380 git_state="merge"
1381 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1382 git_state="am"
1383 git_remove="$git_dir/rebase-apply"
1384 elif [ -e "$git_dir/rebase-apply" ]; then
1385 git_state="rebase"
1386 git_remove="$git_dir/rebase-apply"
1387 elif [ -e "$git_dir/rebase-merge" ]; then
1388 git_state="rebase"
1389 git_remove="$git_dir/rebase-merge"
1390 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1391 git_state="cherry-pick"
1392 elif [ -e "$git_dir/BISECT_LOG" ]; then
1393 git_state="bisect"
1394 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1395 git_state="revert"
1397 git_remove="${git_remove#./}"
1399 tg_state=
1400 tg_remove=
1401 tg_topmerge=
1402 if [ -e "$git_dir/tg-update" ]; then
1403 tg_state="update"
1404 tg_remove="$git_dir/tg-update"
1405 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1407 tg_remove="${tg_remove#./}"
1410 # Show status information
1411 do_status()
1413 do_status_result=0
1414 do_status_verbose=
1415 do_status_help=
1416 abbrev=refs
1417 pfx=
1418 while [ $# -gt 0 ] && case "$1" in
1419 --help|-h)
1420 do_status_help=1
1421 break;;
1422 -vv)
1423 # kludge in this common bundling option
1424 abbrev=
1425 do_status_verbose=1
1426 pfx="## "
1428 --verbose|-v)
1429 [ -z "$do_status_verbose" ] || abbrev=
1430 do_status_verbose=1
1431 pfx="## "
1433 --exit-code)
1434 do_status_result=2
1437 die "unknown status argument: $1"
1439 esac; do shift; done
1440 if [ -n "$do_status_help" ]; then
1441 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1442 return
1444 check_status
1445 symref="$(git symbolic-ref --quiet HEAD)" || :
1446 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1447 if [ -n "$symref" ]; then
1448 uprefpart=
1449 if [ -n "$headrv" ]; then
1450 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1451 if [ -n "$upref" ]; then
1452 uprefpart=" ... ${upref#$abbrev/remotes/}"
1453 mbase="$(git merge-base HEAD "$upref")" || :
1454 ahead="$(git rev-list --count HEAD ${mbase:+--not $mbase})" || ahead=0
1455 behind="$(git rev-list --count "$upref" ${mbase:+--not $mbase})" || behind=0
1456 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1457 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1458 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1459 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1460 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1463 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1464 else
1465 echol "${pfx}HEAD -> ${headrv:-?}"
1467 if [ -n "$tg_state" ]; then
1468 extra=
1469 if [ "$tg_state" = "update" ]; then
1470 IFS= read -r uname <"$git_dir/tg-update/name" || :
1471 [ -z "$uname" ] ||
1472 extra="; currently updating branch '$uname'"
1474 echol "${pfx}tg $tg_state in progress$extra"
1475 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1476 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1477 cat "$git_dir/tg-update/fullcmd"
1478 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1479 if [ $bcnt -gt 1 ]; then
1480 pcnt=0
1481 ! [ -s "$git_dir/tg-update/processed" ] ||
1482 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1483 echo "${pfx}$pcnt of $bcnt branches updated so far"
1486 if [ "$tg_state" = "update" ]; then
1487 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1488 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1489 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1490 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1493 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1494 if [ "$git_state" = "merge" ]; then
1495 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1496 if [ $ucnt -gt 0 ]; then
1497 echo "${pfx}"'fix conflicts and then "git commit" the result'
1498 else
1499 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1502 if [ -z "$git_state" ]; then
1503 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository
1504 gspcnt=0
1505 [ -z "$gsp" ] ||
1506 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1507 untr=
1508 if [ "$gspcnt" -eq 0 ]; then
1509 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1510 echo "${pfx}working directory is clean$untr"
1511 [ -n "$tg_state" ] || do_status_result=0
1512 else
1513 echo "${pfx}working directory is DIRTY"
1514 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1519 ## Pager stuff
1521 # isatty FD
1522 isatty()
1524 test -t $1
1527 # pass "diff" to get pager.diff
1528 # if pager.$1 is a boolean false returns cat
1529 # if set to true or unset fails
1530 # otherwise succeeds and returns the value
1531 get_pager()
1533 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1534 [ "$_x" != "true" ] || return 1
1535 echo "cat"
1536 return 0
1538 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1539 echol "$_x"
1540 return 0
1542 return 1
1545 # setup_pager
1546 # Set TG_PAGER to a valid executable
1547 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1548 # See also the following "page" function for ease of use
1549 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1550 # Preference is (same as Git):
1551 # 1. GIT_PAGER
1552 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1553 # 3. core.pager (only if set)
1554 # 4. PAGER
1555 # 5. git var GIT_PAGER
1556 # 6. less
1557 setup_pager()
1559 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1561 emptypager=
1562 if [ -z "$TG_PAGER_IN_USE" ]; then
1563 # TG_PAGER = GIT_PAGER | PAGER | less
1564 # NOTE: GIT_PAGER='' is significant
1565 if [ -n "${GIT_PAGER+set}" ]; then
1566 TG_PAGER="$GIT_PAGER"
1567 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1568 TG_PAGER="$_dp"
1569 elif _cp="$(git config core.pager 2>/dev/null)"; then
1570 TG_PAGER="$_cp"
1571 elif [ -n "${PAGER+set}" ]; then
1572 TG_PAGER="$PAGER"
1573 else
1574 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1575 [ "$_gp" != ":" ] || _gp=
1576 TG_PAGER="${_gp:-less}"
1578 if [ -z "$TG_PAGER" ]; then
1579 emptypager=1
1580 TG_PAGER=cat
1582 else
1583 emptypager=1
1584 TG_PAGER=cat
1587 # Set pager default environment variables
1588 # see pager.c:setup_pager
1589 if [ -z "${LESS+set}" ]; then
1590 LESS="-FRX"
1591 export LESS
1593 if [ -z "${LV+set}" ]; then
1594 LV="-c"
1595 export LV
1598 # this is needed so e.g. $(git diff) will still colorize it's output if
1599 # requested in ~/.gitconfig with color.diff=auto
1600 GIT_PAGER_IN_USE=1
1601 export GIT_PAGER_IN_USE
1603 # this is needed so we don't get nested pagers
1604 TG_PAGER_IN_USE=1
1605 export TG_PAGER_IN_USE
1608 # page eval_arg [arg ...]
1610 # Calls setup_pager then evals the first argument passing it all the rest
1611 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1612 # by setup_pager (in which case the output is left as-is).
1614 # To handle arbitrary paging duties, collect lines to be paged into a
1615 # function and then call page with the function name or perhaps func_name "$@".
1617 # If no arguments at all are passed in do nothing (return with success).
1618 page()
1620 [ $# -gt 0 ] || return 0
1621 setup_pager
1622 _evalarg="$1"; shift
1623 if [ -n "$emptypager" ]; then
1624 eval "$_evalarg" '"$@"'
1625 else
1626 { eval "$_evalarg" '"$@"';} | eval "$TG_PAGER"
1630 # get_temp NAME [-d]
1631 # creates a new temporary file (or directory with -d) in the global
1632 # temporary directory $tg_tmp_dir with pattern prefix NAME
1633 get_temp()
1635 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1638 # automatically called by strftime
1639 # does nothing if already setup
1640 # may be called explicitly if the first call would otherwise be in a subshell
1641 # so that the setup is only done once before subshells start being spawned
1642 setup_strftime()
1644 [ -z "$strftime_is_setup" ] || return 0
1646 # date option to format raw epoch seconds values
1647 daterawopt=
1648 _testes='951807788'
1649 _testdt='2000-02-29 07:03:08 UTC'
1650 _testfm='%Y-%m-%d %H:%M:%S %Z'
1651 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1652 daterawopt='-d@'
1653 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1654 daterawopt='-r'
1656 strftime_is_setup=1
1659 # $1 => strftime format string to use
1660 # $2 => raw timestamp as seconds since epoch
1661 # $3 => optional time zone string (empty/absent for local time zone)
1662 strftime()
1664 setup_strftime
1665 if [ -n "$daterawopt" ]; then
1666 if [ -n "$3" ]; then
1667 TZ="$3" date "$daterawopt$2" "+$1"
1668 else
1669 date "$daterawopt$2" "+$1"
1671 else
1672 if [ -n "$3" ]; then
1673 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1674 else
1675 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1680 got_cdup_result=
1681 git_cdup_result=
1682 v_get_show_cdup()
1684 if [ -z "$got_cdup_result" ]; then
1685 git_cdup_result="$(git rev-parse --show-cdup)"
1686 got_cdup_result=1
1688 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1691 setup_git_dirs()
1693 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1694 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1695 git_dir="$(cd "$git_dir" && pwd)"
1697 if [ -z "$git_common_dir" ]; then
1698 if vcmp "$git_version" '>=' "2.5"; then
1699 # rev-parse --git-common-dir is broken and may give
1700 # an incorrect result unless the current directory is
1701 # already set to the top level directory
1702 v_get_show_cdup
1703 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1704 else
1705 git_common_dir="$git_dir"
1708 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1709 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1710 git_hooks_dir="$git_common_dir/hooks"
1711 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1712 case "$gchp" in
1713 /[!/]*)
1714 git_hooks_dir="$gchp"
1717 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1719 esac
1720 unset gchp
1724 basic_setup()
1726 setup_git_dirs $1
1727 if [ -z "$base_remote" ]; then
1728 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
1729 base_remote="$TG_EXPLICIT_REMOTE"
1730 else
1731 base_remote="$(git config topgit.remote 2>/dev/null)" || :
1734 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1735 tgnosequester=
1736 [ "$tgsequester" != "false" ] || tgnosequester=1
1737 unset tgsequester
1739 # catch errors if topbases is used without being set
1740 unset tg_topbases_set
1741 topbases="programmer*:error"
1742 topbasesrx="programmer*:error}"
1743 oldbases="$topbases"
1746 ## Initial setup
1747 initial_setup()
1749 # suppress the merge log editor feature since git 1.7.10
1751 GIT_MERGE_AUTOEDIT=no
1752 export GIT_MERGE_AUTOEDIT
1754 basic_setup $1
1755 iowopt=
1756 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
1757 gcfbopt=
1758 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
1759 auhopt=
1760 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1761 v_get_show_cdup root_dir
1762 root_dir="${root_dir:-.}"
1763 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1764 [ "$logrefupdates" = "true" ] || logrefupdates=
1766 # make sure root_dir doesn't end with a trailing slash.
1768 root_dir="${root_dir%/}"
1770 # create global temporary directories, inside GIT_DIR
1772 if [ -n "$TG_TMPDIR" ] && [ -d "$TG_TMPDIR" ] && [ -w "$TG_TMPDIR" ] &&
1773 { >"$TG_TMPDIR/.check"; } >/dev/null 2>&1; then
1774 tg_tmp_dir="$TG_TMPDIR"
1775 else
1776 tg_tmp_dir=
1777 trap '${TG_DEBUG:+echo} rm -rf "$tg_tmp_dir" >&2' EXIT
1778 trap 'exit 129' HUP
1779 trap 'exit 130' INT
1780 trap 'exit 131' QUIT
1781 trap 'exit 134' ABRT
1782 trap 'exit 143' TERM
1783 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1784 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1785 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1787 unset TG_TMPDIR
1788 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1789 tg_ref_cache_br="$tg_ref_cache.br"
1790 tg_ref_cache_rbr="$tg_ref_cache.rbr"
1791 tg_ref_cache_ann="$tg_ref_cache.ann"
1792 tg_ref_cache_dep="$tg_ref_cache.dep"
1793 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_ref_cache"; } >/dev/null 2>&1 ||
1794 die "could not create a writable temporary directory"
1796 # make sure global cache directory exists inside GIT_DIR or $tg_tmp_dir
1798 user_id_no="$(id -u)" || :
1799 : "${user_id_no:=_99_}"
1800 tg_cache_dir="$git_common_dir/tg-cache"
1801 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1802 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
1803 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1804 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1805 if [ -z "$tg_cache_dir" ]; then
1806 tg_cache_dir="$tg_tmp_dir/tg-cache"
1807 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1808 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1810 [ -n "$tg_cache_dir" ] ||
1811 die "could not create a writable tg-cache directory (even a temporary one)"
1813 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
1814 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
1815 # so we avoid it if possible and require v2.11.1 to do it at all
1816 # otherwise just don't make an alternates temporary store in that case;
1817 # it's okay to not have one; everything will still work; the nicety of
1818 # making the temporary tree objects vanish when tg exits just won't
1819 # happen in that case but nothing will break also be sure to reuse
1820 # the parent's if we've been recursively invoked and it's for the
1821 # same repository we were invoked on
1823 tg_use_alt_odb=1
1824 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
1825 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] || tg_use_alt_odb=
1826 _fulltmpdir=
1827 [ -z "$tg_use_alt_odb" ] || _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
1828 case "$_fulltmpdir" in *[";:"]*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
1829 _fullodbdir=
1830 [ -z "$tg_use_alt_odb" ] || _fullodbdir="$(cd "$_odbdir" && pwd -P)"
1831 if [ -n "$tg_use_alt_odb" ] && [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
1832 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
1833 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
1834 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
1835 tg_use_alt_odb=2
1838 if [ "$tg_use_alt_odb" = "1" ]; then
1839 # create an alternate objects database to keep the ephemeral objects in
1840 mkdir -p "$tg_tmp_dir/objects/info"
1841 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
1842 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
1843 case "$TG_OBJECT_DIRECTORY" in
1844 *[";:"]*)
1845 # surround in "..." and backslash-escape internal '"' and '\\'
1846 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
1847 sed 's/\([""\\]\)/\\\1/g')\""
1850 _altodbdq="$TG_OBJECT_DIRECTORY"
1852 esac
1853 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1854 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
1855 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1856 else
1857 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
1859 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
1863 noalt_setup()
1865 if [ "${TG_PRESERVED_ALTERNATES+set}" = "set" ]; then
1866 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
1867 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
1868 export GIT_ALTERNATE_OBJECT_DIRECTORIES
1869 else
1870 unset GIT_ALTERNATE_OBJECT_DIRECTORIES
1873 unset TG_TMPDIR TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES tg_use_alt_odb
1876 set_topbases()
1878 # refer to "top-bases" in a refname with $topbases
1880 [ -z "$tg_topbases_set" ] || return 0
1882 topbases_implicit_default=1
1883 # See if topgit.top-bases is set to heads or refs
1884 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
1885 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
1886 if [ -n "$1" ]; then
1887 # never die on the hook script
1888 unset tgtb
1889 else
1890 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
1893 if [ -n "$tgtb" ]; then
1894 case "$tgtb" in
1895 heads)
1896 topbases="heads/{top-bases}"
1897 topbasesrx="heads/[{]top-bases[}]"
1898 oldbases="top-bases";;
1899 refs)
1900 topbases="top-bases"
1901 topbasesrx="top-bases"
1902 oldbases="heads/{top-bases}";;
1903 esac
1904 # MUST NOT be exported
1905 unset tgtb tg_topbases_set topbases_implicit_default
1906 tg_topbases_set=1
1907 return 0
1909 unset tgtb
1911 # check heads and top-bases and see what state the current
1912 # repository is in. remotes are ignored.
1914 rc=0 activebases=
1915 activebases="$(
1916 git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null |
1917 run_awk_ref_prefixes ${1:+-e} -n -- "refs/heads/{top-bases}" "refs/top-bases" "refs/heads")" ||
1918 rc=$?
1919 if [ "$rc" = "65" ]; then
1920 # Complain and die
1921 err "repository contains existing TopGit branches"
1922 err "but some use refs/top-bases/... for the base"
1923 err "and some use refs/heads/{top-bases}/... for the base"
1924 err "with the latter being the new, preferred location"
1925 err "set \"topgit.top-bases\" to either \"heads\" to use"
1926 err "the new heads/{top-bases} location or \"refs\" to use"
1927 err "the old top-bases location."
1928 err "(the tg migrate-bases command can also resolve this issue)"
1929 die "schizophrenic repository requires topgit.top-bases setting"
1931 [ -z "$activebases" ] || unset topbases_implicit_default
1932 if [ "$activebases" = "refs/heads/{top-bases}" ]; then
1933 topbases="heads/{top-bases}"
1934 topbasesrx="heads/[{]top-bases[}]"
1935 oldbases="top-bases"
1936 else
1937 # default is still top-bases for now
1938 topbases="top-bases"
1939 topbasesrx="top-bases"
1940 oldbases="heads/{top-bases}"
1942 # MUST NOT be exported
1943 unset rc activebases tg_topases_set
1944 tg_topbases_set=1
1945 return 0
1948 # init_reflog "ref"
1949 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
1950 # an empty log file to exist so that ref changes will be logged
1951 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
1952 # However, if "$1" is "refs/tgstash" then always make the reflog
1953 # The only ref not under refs/ that Git will write a reflog for is HEAD;
1954 # no matter what, it will NOT update a reflog for any other bare refs so
1955 # just quietly succeed when passed TG_STASH without doing anything.
1956 init_reflog()
1958 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
1959 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
1960 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
1961 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
1962 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
1965 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
1966 # a symbolic link. The directory part must exist, but the basename need not.
1967 v_get_abs_path()
1969 [ -n "$1" ] && [ -n "$2" ] || return 1
1970 set -- "$1" "$2" "${2%/}"
1971 case "$3" in
1972 */*) set -- "$1" "$2" "${3%/*}";;
1973 * ) set -- "$1" "$2" ".";;
1974 esac
1975 case "$2" in */)
1976 set -- "$1" "${2%/}" "$3" "/"
1977 esac
1978 [ -d "$3" ] || return 1
1979 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
1982 ## Startup
1984 : "${TG_INST_CMDDIR:=@cmddir@}"
1985 : "${TG_INST_SHAREDIR:=@sharedir@}"
1986 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1988 [ -d "$TG_INST_CMDDIR" ] ||
1989 die "No command directory: '$TG_INST_CMDDIR'"
1991 ## Include awk scripts and their utility functions (separated for easier debugging)
1993 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
1994 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
1995 . "$TG_INST_CMDDIR/tg--awksome"
1997 if [ -n "$tg__include" ]; then
1999 # We were sourced from another script for our utility functions;
2000 # this is set by hooks. Skip the rest of the file. A simple return doesn't
2001 # work as expected in every shell. See http://bugs.debian.org/516188
2003 # ensure setup happens
2005 initial_setup 1
2006 set_topbases 1
2007 noalt_setup
2009 else
2011 set -e
2013 tgbin="$0"
2014 tgdir="${tgbin%/}"
2015 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
2016 tgdir="${tgdir%/*}/"
2017 tgname="${tgbin##*/}"
2018 [ "$0" != "$tgname" ] || tgdir=""
2020 # If tg contains a '/' but does not start with one then replace it with an absolute path
2022 case "$0" in /*) ;; */*)
2023 tgdir="$(cd "${0%/*}" && pwd -P)/"
2024 tgbin="$tgdir$tgname"
2025 esac
2027 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
2028 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2030 tgdisplaydir="$tgdir"
2031 tgdisplay="$tgbin"
2032 tgdisplayac="$tgdisplay"
2034 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2035 _tgabs="$_tgnameabs" &&
2036 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2037 [ "$_tgabs" = "$_tgnameabs" ]
2038 then
2039 tgdisplaydir=""
2040 tgdisplay="$tgname"
2041 tgdisplayac="$tgdisplay"
2043 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2044 unset _tgabs _tgnameabs
2046 tg() (
2047 TG_TMPDIR="$tg_tmp_dir" && export TG_TMPDIR &&
2048 exec "$tgbin" "$@"
2051 explicit_remote=
2052 explicit_dir=
2053 gitcdopt=
2054 noremote=
2056 cmd=
2057 while :; do case "$1" in
2059 help|--help|-h)
2060 cmd=help
2061 shift
2062 break;;
2064 status|--status)
2065 cmd=status
2066 shift
2067 break;;
2069 --hooks-path)
2070 cmd=hooks-path
2071 shift
2072 break;;
2074 --exec-path)
2075 cmd=exec-path
2076 shift
2077 break;;
2079 --top-bases)
2080 cmd=top-bases
2081 shift
2082 break;;
2084 --no-pager)
2085 GIT_PAGER_IN_USE=1 TG_PAGER_IN_USE=1 &&
2086 export GIT_PAGER_IN_USE TG_PAGER_IN_USE
2087 shift;;
2090 shift
2091 if [ -z "$1" ]; then
2092 echo "Option -r requires an argument." >&2
2093 do_help
2094 exit 1
2096 unset noremote
2097 base_remote="$1"
2098 explicit_remote="$base_remote"
2099 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2100 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2101 shift;;
2104 unset base_remote explicit_remote
2105 noremote=1
2106 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2107 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2108 shift;;
2111 shift
2112 if [ -z "$1" ]; then
2113 echo "Option -C requires an argument." >&2
2114 do_help
2115 exit 1
2117 cd "$1"
2118 unset GIT_DIR GIT_COMMON_DIR
2119 if [ -z "$explicit_dir" ]; then
2120 explicit_dir="$1"
2121 else
2122 explicit_dir="$PWD"
2124 gitcdopt=" -C \"$explicit_dir\""
2125 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2126 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2127 tgdisplayac="$tgdisplay"
2128 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2129 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2130 shift;;
2133 shift
2134 if [ -z "$1" ]; then
2135 echo "Option -c requires an argument." >&2
2136 do_help
2137 exit 1
2139 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2140 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2141 export GIT_CONFIG_PARAMETERS
2142 shift;;
2145 shift
2146 break;;
2149 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2150 do_help
2151 exit 1;;
2154 break;;
2156 esac; done
2158 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
2160 ## Dispatch
2162 [ -n "$cmd" ] || { do_help; exit 1; }
2164 case "$cmd" in
2166 help)
2167 do_help "$@"
2168 exit 0;;
2170 status|st)
2171 unset base_remote
2172 basic_setup
2173 set_topbases
2174 do_status "$@"
2175 exit ${do_status_result:-0};;
2177 hooks-path)
2178 # Internal command
2179 echol "$TG_INST_HOOKSDIR";;
2181 exec-path)
2182 # Internal command
2183 echol "$TG_INST_CMDDIR";;
2185 top-bases)
2186 # Maintenance command
2187 ! git rev-parse --git-dir >/dev/null 2>&1 || setup_git_dirs
2188 set_topbases
2189 echol "refs/$topbases";;
2192 isutil=
2193 case "$cmd" in index-merge-one-file)
2194 isutil="-"
2195 esac
2196 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2197 looplevel="$TG_ALIAS_DEPTH"
2198 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2199 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2200 looplevel=0
2201 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2202 [ -n "$tgalias" ] || {
2203 echo "Unknown subcommand: $cmd" >&2
2204 do_help
2205 exit 1
2207 looplevel=$(( $looplevel + 1 ))
2208 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2209 TG_ALIAS_DEPTH="$looplevel"
2210 export TG_ALIAS_DEPTH
2211 if [ "!${tgalias#?}" = "$tgalias" ]; then
2212 unset GIT_PREFIX
2213 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2214 GIT_PREFIX="$pfx"
2215 export GIT_PREFIX
2217 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2218 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2219 else
2220 eval 'exec "$tgbin"' "$tgalias" '"$@"'
2222 die "alias execution failed for: $tgalias"
2224 unset TG_ALIAS_DEPTH
2226 showing_help=
2227 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2228 showing_help=1
2231 [ -n "$showing_help" ] || initial_setup
2232 [ -z "$noremote" ] || unset base_remote
2234 nomergesetup="$showing_help"
2235 case "$cmd" in base|contains|info|log|rebase|revert|summary|tag)
2236 # avoid merge setup where not necessary
2238 nomergesetup=1
2239 esac
2241 if [ -z "$nomergesetup" ]; then
2242 # make sure merging the .top* files will always behave sanely
2244 setup_ours
2245 setup_hook "pre-commit"
2248 # everything but rebase needs topbases set
2249 carefully="$showing_help"
2250 [ "$cmd" != "migrate-bases" ] || carefully=1
2251 [ "$cmd" = "rebase" ] || set_topbases $carefully
2253 _use_ref_cache=
2254 tg_read_only=1
2255 _suppress_alt=
2256 case "$cmd$showing_help" in
2257 contains|info|summary|tag)
2258 _use_ref_cache=1;;
2259 "export")
2260 _use_ref_cache=1
2261 suppress_alt=1;;
2262 annihilate|create|delete|depend|import|update)
2263 tg_read_only=
2264 suppress_alt=1;;
2265 esac
2266 [ -z "$_suppress_alt" ] || noalt_setup
2267 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2269 fullcmd="${tgname:-tg} $cmd $*"
2270 . "$TG_INST_CMDDIR"/tg-$isutil$cmd;;
2271 esac