topgit: version 0.19.13
[topgit/pro.git] / tg.sh
blob94af2a91132c33ef000cd392bd696cee5960acd1
1 #!/bin/sh
2 # TopGit - A different patch queue manager
3 # Copyright (C) 2008 Petr Baudis <pasky@suse.cz>
4 # Copyright (C) 2014-2021 Kyle J. McKay <mackyle@gmail.com>
5 # All rights reserved.
6 # GPLv2
8 TG_VERSION="0.19.13"
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 hexch='[0-9a-f]'
16 octet="$hexch$hexch"
17 octet4="$octet$octet$octet$octet"
18 octet19="$octet4$octet4$octet4$octet4$octet$octet$octet"
19 octet20="$octet4$octet4$octet4$octet4$octet4"
20 octet32="$octet20$octet4$octet4$octet4"
21 tab=' '
22 lf='
25 ## Auxiliary functions
27 # some ridiculous sh implementations require 'trap ... EXIT' to be executed
28 # OUTSIDE ALL FUNCTIONS to work in a sane fashion. Always trap it and eval
29 # "${TRAPEXIT_:-exit}" as a substitute.
30 TRAPEXIT_=
31 trapexit_()
33 EXITCODE_=${1:-$?}
34 trap - EXIT
35 eval "${TRAPEXIT_:-exit $EXITCODE_}"
36 exit $EXITCODE_
38 trap 'trapexit_ $?' EXIT
40 # unset that ignores error code that shouldn't be produced according to POSIX
41 unset_()
43 { unset "$@"; } >/dev/null 2>&1 || :
46 # Preserves current $? value while triggering a non-zero set -e exit if active
47 # This works even for shells that sometimes fail to correctly trigger a -e exit
48 check_exit_code()
50 return $?
53 # This is the POSIX equivalent of which
54 cmd_path()
56 { "unset" -f command unset unalias "$1"; } >/dev/null 2>&1 || :
57 { "unalias" -a || unalias -m "*"; } >/dev/null 2>&1 || :
58 command -v "$1"
61 # helper for wrappers
62 # note deliberate use of '(' ... ')' rather than '{' ... '}'
63 exec_lc_all_c()
65 { "unset" -f "$1" || :; } >/dev/null 2>&1 &&
66 shift &&
67 LC_ALL="C" &&
68 export LC_ALL &&
69 exec "$@"
72 # These tools work better for us with LC_ALL=C and by using these little
73 # convenience functions LC_ALL=C does not have to appear in the code but
74 # any Git translations will still appear for Git commands
75 awk() { exec_lc_all_c awk @AWK_PATH@ "$@"; }
76 cat() { exec_lc_all_c cat cat "$@"; }
77 cmp() { exec_lc_all_c cmp cmp "$@"; }
78 cut() { exec_lc_all_c cut cut "$@"; }
79 find() { exec_lc_all_c find find "$@"; }
80 grep() { exec_lc_all_c grep grep "$@"; }
81 join() { exec_lc_all_c join join "$@"; }
82 paste() { exec_lc_all_c paste paste "$@"; }
83 sed() { exec_lc_all_c sed sed "$@"; }
84 sort() { exec_lc_all_c sort sort "$@"; }
85 tr() { exec_lc_all_c tr tr "$@"; }
86 wc() { exec_lc_all_c wc wc "$@"; }
87 xargs() { exec_lc_all_c xargs xargs "$@"; }
89 # Output arguments without any possible interpretation
90 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
91 echol()
93 printf '%s\n' "$*"
96 info()
98 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
101 warn()
103 info "warning: $*" >&2
106 err()
108 info "error: $*" >&2
111 fatal()
113 info "fatal: $*" >&2
116 die()
118 fatal "$@"
119 exit 1
122 # shift off first arg then return "$*" properly quoted in single-quotes
123 # if $1 was '' output goes to stdout otherwise it's assigned to $1
124 # the final \n, if any, is omitted from the result but any others are included
125 v_quotearg()
127 _quotearg_v="$1"
128 shift
129 set -- "$_quotearg_v" \
130 "sed \"s/'/'\\\\\\''/g;1s/^/'/;\\\$s/\\\$/'/;s/'''/'/g;1s/^''\\(.\\)/\\1/\"" "$*"
131 unset_ _quotearg_v
132 if [ -z "$3" ]; then
133 if [ -z "$1" ]; then
134 echo "''"
135 else
136 eval "$1=\"''\""
138 else
139 if [ -z "$1" ]; then
140 printf "%s$4" "$3" | eval "$2"
141 else
142 eval "$1="'"$(printf "%s$4" "$3" | eval "$2")"'
147 # same as v_quotearg except there's no extra $1 so output always goes to stdout
148 quotearg()
150 v_quotearg '' "$@"
153 vcmp()
155 # Compare $1 to $3 each of which must match ^[^0-9]*\d*(\.\d*)*.*$
156 # where only the "\d*" parts in the regex participate in the comparison
157 # Since EVERY string matches that regex this function is easy to use
158 # An empty string ('') for $1 or $3 or any "\d*" part is treated as 0
159 # $2 is a compare op '<', '<=', '=', '==', '!=', '>=', '>'
160 # Return code is 0 for true, 1 for false (or unknown compare op)
161 # There is NO difference in behavior between '=' and '=='
162 # Note that "vcmp 1.8 == 1.8.0.0.0.0" correctly returns 0
163 set -- "$1" "$2" "$3" "${1%%[0-9]*}" "${3%%[0-9]*}"
164 set -- "${1#"$4"}" "$2" "${3#"$5"}"
165 set -- "${1%%[!0-9.]*}" "$2" "${3%%[!0-9.]*}"
166 while
167 vcmp_a_="${1%%.*}"
168 vcmp_b_="${3%%.*}"
169 [ "z$vcmp_a_" != "z" ] || [ "z$vcmp_b_" != "z" ]
171 if [ "${vcmp_a_:-0}" -lt "${vcmp_b_:-0}" ]; then
172 unset_ vcmp_a_ vcmp_b_
173 case "$2" in "<"|"<="|"!=") return 0; esac
174 return 1
175 elif [ "${vcmp_a_:-0}" -gt "${vcmp_b_:-0}" ]; then
176 unset_ vcmp_a_ vcmp_b_
177 case "$2" in ">"|">="|"!=") return 0; esac
178 return 1;
180 vcmp_a_="${1#$vcmp_a_}"
181 vcmp_b_="${3#$vcmp_b_}"
182 set -- "${vcmp_a_#.}" "$2" "${vcmp_b_#.}"
183 done
184 unset_ vcmp_a_ vcmp_b_
185 case "$2" in "="|"=="|"<="|">=") return 0; esac
186 return 1
189 # true if "$1" is an existing dir and is empty except for
190 # any additional files given as extra arguments. If "$2"
191 # is the single character "." then all ".*" files will be
192 # ignored for the test (plus any further args, if any)
193 is_empty_dir() {
194 test -n "$1" && test -d "$1" || return 1
195 iedd_="$1"
196 shift
197 ieddnok_='\.?$'
198 if [ z"$1" = z"." ]; then
199 ieddnok_=
200 shift
201 while ! case "$1" in "."*) ! :; esac; do shift; done
203 if [ $# -eq 0 ]; then
204 ! \ls -a1 "$iedd_" | grep -q -E -v '^\.'"$ieddnok_"
205 else
206 # we only handle ".git" right now for efficiency
207 [ z"$*" = z".git" ] || {
208 fatal "[BUG] is_empty_dir not implemented for arguments: $*"
209 exit 70
211 ! \ls -a1 "$iedd_" | grep -q -E -v -i -e '^\.\.?$' -e '^\.git$'
215 precheck() {
216 if ! git_version="$(git version)"; then
217 die "'git version' failed"
219 case "$git_version" in [Gg]"it version "*);;*)
220 die "'git version' output does not start with 'git version '"
221 esac
223 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
224 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
227 case "$1" in version|--version|-V)
228 echo "TopGit version $TG_VERSION"
229 exit 0
230 esac
232 [ $# -eq 1 ] && [ "$1" = "--make-empty-blob" ] || precheck
233 [ $# -ne 1 ] || [ "$1" != "precheck" ] || exit 0
235 cat_depsmsg_internal()
237 v_ref_exists_rev _rev "refs/heads/$1" || return 0
238 if [ -s "$tg_cache_dir/refs/heads/$1/.$2" ]; then
239 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
240 _line=
241 while IFS= read -r _line || [ -n "$_line" ]; do
242 printf '%s\n' "$_line"
243 done
244 return 0
245 fi <"$tg_cache_dir/refs/heads/$1/.$2"
247 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null || :
248 if [ -d "$tg_cache_dir/refs/heads/$1" ]; then
249 rm -f "$tg_cache_dir/refs/heads/$1/.$2" "$tg_cache_dir/refs/heads/$1/.$2-$$"
250 printf '%s\n' "$_rev" >"$tg_cache_dir/refs/heads/$1/.$2-$$"
251 _line=
252 git cat-file blob "$_rev:.$2" 2>/dev/null |
253 while IFS= read -r _line || [ -n "$_line" ]; do
254 printf '%s\n' "$_line" >&3
255 printf '%s\n' "$_line"
256 done 3>>"$tg_cache_dir/refs/heads/$1/.$2-$$"
257 mv -f "$tg_cache_dir/refs/heads/$1/.$2-$$" "$tg_cache_dir/refs/heads/$1/.$2"
258 rm -f "$tg_cache_dir/refs/heads/$1/.$2-$$"
259 else
260 git cat-file blob "$_rev:.$2" 2>/dev/null
264 # cat_deps BRANCHNAME
265 # Caches result
266 cat_deps()
268 cat_depsmsg_internal "$1" topdeps
271 # cat_msg BRANCHNAME
272 # Caches result
273 cat_msg()
275 cat_depsmsg_internal "$1" topmsg
278 # cat_file TOPIC:PATH [FROM]
279 # cat the file PATH from branch TOPIC when FROM is empty.
280 # FROM can be -i or -w, than the file will be from the index or worktree,
281 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
282 cat_file()
284 path="$1"
285 case "$2" in
287 cat "$root_dir/${path#*:}"
290 # ':file' means cat from index
291 git cat-file blob ":${path#*:}" 2>/dev/null
294 case "$path" in
295 refs/heads/*:.topdeps)
296 _temp="${path%:.topdeps}"
297 cat_deps "${_temp#refs/heads/}"
299 refs/heads/*:.topmsg)
300 _temp="${path%:.topmsg}"
301 cat_msg "${_temp#refs/heads/}"
304 git cat-file blob "$path" 2>/dev/null
306 esac
309 die "Wrong argument to cat_file: '$2'"
311 esac
314 # if use_alt_temp_odb and tg_use_alt_odb are true try to write the object(s)
315 # into the temporary alt odb area instead of the usual location
316 git_temp_alt_odb_cmd()
318 if [ -n "$use_alt_temp_odb" ] && [ -n "$tg_use_alt_odb" ] &&
319 [ -n "$TG_OBJECT_DIRECTORY" ] &&
320 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
322 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
323 GIT_OBJECT_DIRECTORY="$TG_OBJECT_DIRECTORY"
324 unset_ TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES
325 export GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
326 git "$@"
328 else
329 git "$@"
333 git_write_tree() { git_temp_alt_odb_cmd write-tree "$@"; }
334 git_mktree() { git_temp_alt_odb_cmd mktree "$@"; }
336 make_mtblob() {
337 use_alt_temp_odb=1
338 tg_use_alt_odb=1
339 git_temp_alt_odb_cmd hash-object -t blob -w --stdin </dev/null >/dev/null 2>&1
341 # short-circuit this for speed
342 [ $# -ne 1 ] || [ "$1" != "--make-empty-blob" ] || { make_mtblob || :; exit 0; }
344 # get tree for the committed topic (second arg)
345 # store result in variable named by first arg
346 v_get_tree_()
348 eval "$1="'"refs/heads/$2"'
351 # get tree for the base (second arg)
352 # store result in variable named by first arg
353 v_get_tree_b()
355 eval "$1="'"refs/$topbases/$2"'
358 # get tree for the index
359 # store result in variable named by first arg
360 v_get_tree_i()
362 eval "$1="'"$(git_write_tree)"'
365 # get tree for the worktree
366 # store result in variable named by first arg
367 v_get_tree_w()
369 eval "$1="'"$(
370 i_tree="$(git_write_tree)"
371 # the file for --index-output needs to sit next to the
372 # current index file
373 cd "$root_dir"
374 : ${GIT_INDEX_FILE:="$git_dir/index"}
375 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
376 git read-tree -m "$i_tree" --index-output="$TMP_INDEX" &&
377 GIT_INDEX_FILE="$TMP_INDEX" &&
378 export GIT_INDEX_FILE &&
379 git diff --name-only -z HEAD |
380 git update-index -z --add --remove --stdin &&
381 git_write_tree &&
382 rm -f "$TMP_INDEX"
386 # get tree for arbitrary ref (second arg)
387 # store result in variable named by first arg
388 v_get_tree_r()
390 eval "$1="'"$2"'
393 # v_strip_ref answer "$(git symbolic-ref HEAD)"
394 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
395 # store result in variable named by first arg
396 v_strip_ref()
398 case "$2" in
399 refs/"$topbases"/*)
400 eval "$1="'"${2#refs/$topbases/}"'
402 refs/heads/*)
403 eval "$1="'"${2#refs/heads/}"'
406 eval "$1="'"$2"'
407 esac
410 # v_pretty_tree answer [-t] NAME [-b | -i | -w | -r]
411 # Output tree ID of a cleaned-up tree without tg's artifacts.
412 # NAME will be ignored for -i and -w, but needs to be present
413 # With -r NAME must be a full ref name to a treeish (it's used as-is)
414 # If -t is used the tree is written into the alternate temporary objects area
415 # store result in variable named by first arg
416 v_pretty_tree()
418 _vname="$1"
419 shift
420 use_alt_temp_odb=
421 [ "$1" != "-t" ] || { shift; use_alt_temp_odb=1; }
422 eval "v_get_tree_${2#?}" _tree '"$1"'
423 eval "$_vname=\"\$(
424 git ls-tree --full-tree \"\$_tree\" |
425 sed -ne '/ \.top.*\$/!p' |
426 git_mktree
427 )\""
430 # return an empty-tree root commit -- date is either passed in or current
431 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
432 # An invalid secs causes the current date to be used, an invalid zone offset
433 # causes +0000 to be used
434 make_empty_commit()
436 # the empty tree is guaranteed to always be there even in a repo with
437 # zero objects, but for completeness we force it to exist as a real object
438 SECS=
439 read -r SECS ZONE JUNK <<-EOT || :
442 case "$SECS" in *[!0-9]*) SECS=; esac
443 if [ -z "$SECS" ]; then
444 MTDATE="$(date '+%s %z')"
445 else
446 case "$ZONE" in
447 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
449 [01][0-9][0-5][0-9])
450 ZONE="+$ZONE"
453 ZONE="+0000"
454 esac
455 MTDATE="$SECS $ZONE"
457 EMPTYID="- <-> $MTDATE"
458 EMPTYTREE="$(git mktree < /dev/null)"
459 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
460 git hash-object -t commit -w --stdin
463 # standard input is a diff
464 # standard output is the "+" lines with leading "+ " removed
465 # beware that old lines followed by the dreaded '\ No newline at end of file'
466 # will appear to be new lines if lines are added after them
467 # the git diff --ignore-space-at-eol option can be used to prevent this
468 diff_added_lines()
470 awk '
471 BEGIN { in_hunk = 0; }
472 /^@@ / { in_hunk = 1; }
473 /^\+/ { if (in_hunk == 1) printf("%s\n", substr($0, 2)); }
474 !/^\\ No newline at end of file/ &&
475 /^[^@ +-]/ { in_hunk = 0; }
479 # $1 is name of new branch to create locally if all of these are true:
480 # a) exists as a remote TopGit branch for "$base_remote"
481 # b) the branch "name" does not have any invalid characters in it
482 # c) neither of the two branch refs (branch or base) exist locally
483 # returns success only if a new local branch was created (and dumps message)
484 auto_create_local_remote()
486 case "$1" in ""|*[" $tab$lf~^:\\*?["]*|.*|*/.*|*.|*./|/*|*/|*//*) return 1; esac
487 [ -n "$base_remote" ] &&
488 git update-ref --stdin <<-EOT >/dev/null 2>&1 &&
489 verify refs/remotes/$base_remote/${topbases#heads/}/$1 refs/remotes/$base_remote/${topbases#heads/}/$1
490 verify refs/remotes/$base_remote/$1 refs/remotes/$base_remote/$1
491 create refs/$topbases/$1 refs/remotes/$base_remote/${topbases#heads/}/$1^0
492 create refs/heads/$1 refs/remotes/$base_remote/$1^0
494 { init_reflog "refs/$topbases/$1" || :; } &&
495 info "topic branch '$1' automatically set up from remote '$base_remote'"
498 is_writable_hook()
500 if [ -n "$1" ] && [ -e "$1" ] && [ ! -L "$1" ] && [ -f "$1" ] && [ -r "$1" ] && [ -w "$1" ] && [ -x "$1" ]; then
501 hook_links="$(ls -ld "$1" 2>/dev/null | awk '{print $2}')" || :
502 [ "$hook_links" != "1" ] || return 0
504 return 1
507 # setup_hook NAME
508 setup_hook()
510 setup_git_dir_is_bare
511 [ -z "$git_dir_is_bare" ] || return 0
512 setup_git_hooks_dir
513 tgname="${0##*/}"
514 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
515 if [ -f "$git_hooks_dir/$1" ] && grep -Fq "$hook_call" "$git_hooks_dir/$1"; then
516 # Another job well done!
517 return
519 # Prepare incantation
520 hook_chain=
521 if [ -e "$git_hooks_dir/$1" ] || [ -L "$git_hooks_dir/$1" ]; then
522 hook_call="$hook_call"' || exit $?'
524 ! is_writable_hook "$git_hooks_dir/$1" ||
525 ! sed -n 1p <"$git_hooks_dir/$1" | grep -Fqx "#!@SHELL_PATH@"
526 then
527 chain_num=
528 while [ -e "$git_hooks_dir/$1-chain$chain_num" ] || [ -L "$git_hooks_dir/$1-chain$chain_num" ]; do
529 chain_num=$(( $chain_num + 1 ))
530 done
531 mv -f "$git_hooks_dir/$1" "$git_hooks_dir/$1-chain$chain_num"
532 hook_chain=1
534 else
535 hook_call="exec $hook_call"
536 [ -d "$git_hooks_dir" ] || mkdir -p "$git_hooks_dir" || :
538 # Don't call hook if tg is not installed
539 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
540 # Insert call into the hook
542 echol "#!@SHELL_PATH@"
543 echol "$hook_call"
544 if [ -n "$hook_chain" ]; then
545 echol "test -f \"\$0-chain$chain_num\" &&"
546 echol "test -x \"\$0-chain$chain_num\" &&"
547 echol "exec \"\$0-chain$chain_num\" \"\$@\" || :"
548 else
549 [ ! -s "$git_hooks_dir/$1" ] || cat "$git_hooks_dir/$1"
551 } >"$git_hooks_dir/$1+"
552 chmod a+x "$git_hooks_dir/$1+"
553 mv "$git_hooks_dir/$1+" "$git_hooks_dir/$1"
556 # setup_ours (no arguments)
557 setup_ours()
559 setup_git_dir_is_bare
560 [ -z "$git_dir_is_bare" ] || return 0
561 if [ ! -s "$git_common_dir/info/attributes" ] || ! grep -q topmsg "$git_common_dir/info/attributes"; then
562 [ -d "$git_common_dir/info" ] || mkdir "$git_common_dir/info"
564 echo ".topmsg merge=ours"
565 echo ".topdeps merge=ours"
566 } >>"$git_common_dir/info/attributes"
568 if ! git config merge.ours.driver >/dev/null; then
569 git config merge.ours.name '"always keep ours" merge driver'
570 git config merge.ours.driver 'touch %A'
574 # measure_branch NAME [BASE] [EXTRAHEAD...]
575 measure_branch()
577 _bname="$1"; _base="$2"
578 shift; shift
579 if [ -z "$_base" ]; then
580 v_strip_ref _base "$_bname"
581 _base="refs/$topbases/$_base"
583 # The caller should've verified $name is valid
584 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
585 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
586 if [ $_commits -ne 1 ]; then
587 _suffix="commits"
588 else
589 _suffix="commit"
591 echo "$_commits/$_nmcommits $_suffix"
594 # true if $1 is contained by (or the same as) $2
595 # this is never slower than merge-base --is-ancestor and is often slightly faster
596 contained_by()
598 [ "$(git rev-list --count --max-count=1 "$1" --not "$2" --)" = "0" ]
601 # branch_contains B1 B2
602 # Whether B1 is a superset of B2.
603 branch_contains()
605 v_ref_exists_rev _revb1 "$1" || return 0
606 v_ref_exists_rev _revb2 "$2" || return 0
607 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
608 if read _result _rev_matchb1 _rev_matchb2 &&
609 [ "$_revb1" = "$_rev_matchb1" ] && [ "$_revb2" = "$_rev_matchb2" ]; then
610 return $_result
611 fi <"$tg_cache_dir/$1/.bc/$2/.d"
613 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
614 _result=0
615 contained_by "$_revb2" "$_revb1" || _result=1
616 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
617 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
619 return $_result
622 create_ref_dirs()
624 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" ] && [ -s "$tg_ref_cache" ] || return 0
625 mkdir -p "$tg_tmp_dir/cached/refs"
626 awk '{x=$1; sub(/^refs\//,"",x); if (x != "") {gsub(/[^A-Za-z0-9\/_.+-]/,"\\\\&",x); print x;}}' <"$tg_ref_cache" |
628 cd "$tg_tmp_dir/cached/refs" &&
629 xargs mkdir -p
631 awk -v p="$tg_tmp_dir/cached/" '
632 NF == 2 &&
633 $1 ~ /^refs\/./ &&
634 $2 ~ /^[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]+$/ {
635 fn = p $1 "/.ref"
636 print "0 " $2 >fn
637 close(fn)
639 ' <"$tg_ref_cache"
640 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
643 # If the first argument is non-empty, stores "1" there if this call created the cache
644 v_create_ref_cache()
646 [ -n "$tg_ref_cache" ] && ! [ -s "$tg_ref_cache" ] || return 0
647 _remotespec=
648 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
649 [ -z "$1" ] || eval "$1=1"
650 git for-each-ref --format='%(refname) %(objectname)' \
651 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
652 create_ref_dirs
655 remove_ref_cache()
657 [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ] || return 0
658 >"$tg_ref_cache"
659 >"$tg_ref_cache_br"
660 >"$tg_ref_cache_rbr"
661 >"$tg_ref_cache_ann"
662 >"$tg_ref_cache_dep"
665 core_abbrev_val=
666 core_abbrev_is_setup=
667 v_get_core_abbrev()
669 if [ -z "$core_abbrev_is_setup" ]; then
670 core_abbrev_val="$(git config --int --get core.abbrev 2>/dev/null)" || :
671 : "${core_abbrev_val:=7}"
672 [ "$core_abbrev_val" -ge 4 ] || core_abbrev_val=4
673 core_abbrev_is_setup=1
675 eval "$1="'"$core_abbrev_val"'
678 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
679 rev_parse()
681 rev_parse_code_=1
682 if [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
683 rev_parse_code_=0
684 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache" ||
685 rev_parse_code_=$?
687 [ $rev_parse_code_ -ne 0 ] && [ -z "$tg_ref_cache_only" ] || return $rev_parse_code_
688 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
691 # v_ref_exists_rev answer REF
692 # Whether REF (second arg) is a valid ref name
693 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
694 # or, if $base_remote is set, refs/remotes/$base_remote/
695 # Caches result if $tg_read_only and outputs HASH on success
696 # store result in variable named by first arg
697 v_ref_exists_rev()
699 case "$2" in
700 refs/*)
702 $octethl)
703 eval "$1="'"$2"'
704 return;;
706 die "v_ref_exists_rev requires fully-qualified ref name (given: $2)"
707 esac
708 [ -n "$tg_read_only" ] || { eval "$1="'"$(git rev-parse --quiet --verify "$2^0" -- 2>/dev/null)"'; return; }
709 _result=
710 _result_rev=
711 { read -r _result _result_rev <"$tg_tmp_dir/cached/$2/.ref"; } 2>/dev/null || :
712 [ -z "$_result" ] || { eval "$1="'"$_result_rev"'; return $_result; }
713 _result=0
714 _result_rev="$(rev_parse "$2")" || _result=$?
715 [ -d "$tg_tmp_dir/cached/$2" ] || mkdir -p "$tg_tmp_dir/cached/$2" 2>/dev/null
716 [ ! -d "$tg_tmp_dir/cached/$2" ] ||
717 echo $_result $_result_rev >"$tg_tmp_dir/cached/$2/.ref" 2>/dev/null || :
718 eval "$1="'"$_result_rev"'
719 return $_result
722 # Same as v_ref_exists_rev but output is abbreviated hash
723 # Optional third argument defaults to --short but may be any --short=.../--no-short option
724 v_ref_exists_rev_short()
726 case "$2" in
727 refs/*)
729 $octethl)
732 die "v_ref_exists_rev_short requires fully-qualified ref name (given: $2)"
733 esac
734 if [ "${3:---short}" = "--short" ]; then
735 v_get_core_abbrev _shortval
736 set -- "$1" "$2" "--short=$_shortval"
738 [ -n "$tg_read_only" ] || { eval "$1="'"$(git rev-parse --quiet --verify ${3:---short} "$2^0" -- 2>/dev/null)"'; return; }
739 _result=
740 _result_rev=
741 _result_arg=
742 { read -r _result _result_rev _result_arg <"$tg_tmp_dir/cached/$2/.rfs"; } 2>/dev/null || :
743 [ -z "$_result" ] || [ "${_result_arg:-missing}" != "${3:---short}" ] || { eval "$1="'"$_result_rev"'; return $_result; }
744 _result=0
745 _result_rev="$(rev_parse "$2")" || _result=$?
746 if [ $_result -eq 0 ]; then
747 _result_rev="$(git rev-parse --verify ${3:---short} --quiet "$_result_rev^0" --)"
748 _result=$?
750 [ -d "$tg_tmp_dir/cached/$2" ] || mkdir -p "$tg_tmp_dir/cached/$2" 2>/dev/null
751 [ ! -d "$tg_tmp_dir/cached/$2" ] ||
752 echo $_result $_result_rev "${3:---short}" >"$tg_tmp_dir/cached/$2/.rfs" 2>/dev/null || :
753 eval "$1="'"$_result_rev"'
754 return $_result
757 # ref_exists REF
758 # Whether REF is a valid ref name
759 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
760 # or, if $base_remote is set, refs/remotes/$base_remote/
761 # Caches result
762 ref_exists()
764 v_ref_exists_rev _dummy "$1"
767 # v_rev_parse_tree answer REF
768 # Runs git rev-parse REF^{tree}
769 # Caches result if $tg_read_only
770 # store result in variable named by first arg
771 v_rev_parse_tree()
773 [ -n "$tg_read_only" ] || { eval "$1="'"$(git rev-parse --verify "$2^{tree}" -- 2>/dev/null)"'; return; }
774 if [ -f "$tg_tmp_dir/cached/$2/.rpt" ]; then
775 if IFS= read -r _result <"$tg_tmp_dir/cached/$2/.rpt" && [ -n "$_result" ]; then
776 eval "$1="'"$_result"'
777 return 0
779 return 1
781 [ -d "$tg_tmp_dir/cached/$2" ] || mkdir -p "$tg_tmp_dir/cached/$2" 2>/dev/null || :
782 if [ -d "$tg_tmp_dir/cached/$2" ]; then
783 git rev-parse --verify "$2^{tree}" -- >"$tg_tmp_dir/cached/$2/.rpt" 2>/dev/null || :
784 if IFS= read -r _result <"$tg_tmp_dir/cached/$2/.rpt" && [ -n "$_result" ]; then
785 eval "$1="'"$_result"'
786 return 0
788 return 1
790 eval "$1="'"$(git rev-parse --verify "$2^{tree}" -- 2>/dev/null)"'
793 # has_remote BRANCH
794 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
795 has_remote()
797 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
800 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
801 # If -z "$1" still set return code but do not return result
802 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
803 # refs/heads/... then ... will be verified instead.
804 # if "$3" = "-f" (for fail) then return an error rather than dying.
805 v_verify_topgit_branch()
807 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
808 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
809 [ -n "$_verifyname" ] || [ "$3" = "-f" ] || die "HEAD is not a symbolic ref"
810 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
811 [ "$3" != "-f" ] || return 1
812 die "HEAD is not a symbolic ref to the refs/heads namespace"
813 esac
814 set -- "$1" "$_verifyname" "$3"
816 case "$2" in
817 refs/"$topbases"/*)
818 _verifyname="${2#refs/$topbases/}"
820 refs/heads/*)
821 _verifyname="${2#refs/heads/}"
824 _verifyname="$2"
826 esac
827 if ! ref_exists "refs/heads/$_verifyname"; then
828 [ "$3" != "-f" ] || return 1
829 die "no such branch: $_verifyname"
831 if ! ref_exists "refs/$topbases/$_verifyname"; then
832 [ "$3" != "-f" ] || return 1
833 die "not a TopGit-controlled branch: $_verifyname"
835 [ -z "$1" ] || eval "$1="'"$_verifyname"'
838 # Caches result
839 # $1 = branch name (i.e. "t/foo/bar")
840 # $2 = optional result of rev-parse "refs/heads/$1"
841 # $3 = optional result of rev-parse "refs/$topbases/$1"
842 branch_annihilated()
844 _branch_name="$1"
845 _rev="$2"
846 [ -n "$_rev" ] || v_ref_exists_rev _rev "refs/heads/$_branch_name"
847 _rev_base="$3"
848 [ -n "$_rev_base" ] || v_ref_exists_rev _rev_base "refs/$topbases/$_branch_name"
850 _result=
851 _result_rev=
852 _result_rev_base=
853 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/refs/heads/$_branch_name/.ann"; } 2>/dev/null || :
854 [ -z "$_result" ] || [ "$_result_rev" != "$_rev" ] || [ "$_result_rev_base" != "$_rev_base" ] || return $_result
856 # use the merge base in case the base is ahead.
857 _mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)" || :
859 _result=0
860 if [ -n "$_mb" ]; then
861 v_rev_parse_tree _mbtree "$_mb"
862 v_rev_parse_tree _revtree "$_rev"
863 test "$_mbtree" = "$_revtree" || _result=1
865 [ -d "$tg_cache_dir/refs/heads/$_branch_name" ] || mkdir -p "$tg_cache_dir/refs/heads/$_branch_name" 2>/dev/null
866 [ ! -d "$tg_cache_dir/refs/heads/$_branch_name" ] ||
867 echo $_result $_rev $_rev_base >"$tg_cache_dir/refs/heads/$_branch_name/.ann" 2>/dev/null || :
868 return $_result
871 non_annihilated_branches()
873 refscacheopt="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
874 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
875 refscacheopt="$refscacheopt"'-r="$tg_ref_cache" "refs/$topbases"'
877 eval run_awk_topgit_branches -n "$refscacheopt" '"refs/$topbases" "$@"'
880 # Make sure our tree is clean
881 # if optional "$1" given also verify that a checkout to "$1" would succeed
882 # Note that the empty tree can always be used as a diff target even if it's not
883 # actually a real, concrete object in the repository (since Git v1.5.5)
884 ensure_clean_tree()
886 check_status
887 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
888 git update-index --ignore-submodules --refresh ||
889 die "the working directory has uncommitted changes (see above) - first commit or reset them"
890 _ectHEAD="$(git rev-parse --verify --quiet "HEAD^{tree}" -- 2>/dev/null)" && [ -n "$_ectHEAD" ] ||
891 _ectHEAD="$mttree"
892 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules "$_ectHEAD" -- 2>/dev/null)" ] ||
893 die "the index has uncommited changes"
894 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
895 die "git checkout \"$1\" would fail"
898 # Make sure .topdeps and .topmsg are "clean"
899 # They are considered "clean" if each is identical in worktree, index and HEAD
900 # With "-u" as the argument skip the HEAD check (-u => unborn)
901 # untracked .topdeps and/or .topmsg files are always considered "dirty" as well
902 # with -u them just existing constitutes "dirty"
903 ensure_clean_topfiles()
905 _dirtw=0
906 _dirti=0
907 _dirtu=0
908 _check="$(git diff-files --ignore-submodules --name-only -- :/.topdeps :/.topmsg)" &&
909 [ -z "$_check" ] || _dirtw=1
910 if [ "$1" != "-u" ]; then
911 _check="$(git diff-index --cached --ignore-submodules --name-only HEAD -- :/.topdeps :/.topmsg)" &&
912 [ -z "$_check" ] || _dirti=1
914 if [ "$_dirti$_dirtw" = "00" ]; then
915 v_get_show_cdup
916 if [ -e "${git_cdup_result}.topdeps" ] || [ -e "${git_cdup_result}.topmsg" ]; then
917 [ "$1" != "-u" ] &&
918 _check="$(git status --porcelain --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg)" &&
919 [ -z "$_check" ] || _dirtu=1
922 if [ "$_dirtu$_dirti$_dirtw" != "000" ]; then
923 git status --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg || :
924 case "$_dirtu$_dirti$_dirtw" in
925 001) die "the working directory has uncommitted changes (see above) - first commit or reset them";;
926 010) die "the index has uncommited changes (see above)";;
927 011) die "the working directory and index have uncommitted changes (see above) - first commit or reset them";;
928 100) die "the working directory has untracked files that would be overwritten (see above)";;
929 esac
933 # is_sha1 REF
934 # Whether REF is a SHA1 (compared to a symbolic name).
935 is_sha1()
937 case "$1" in $octethl) return 0;; esac
938 return 1
941 # navigate_deps <run_awk_topgit_navigate options and arguments>
942 # all options and arguments are passed through to run_awk_topgit_navigate
943 # except for a leading -td= option, if any, which is picked off for deps
944 # after arranging to feed it a suitable deps list
945 navigate_deps()
947 dogfer=
948 dorad=1
949 userc=
950 tmpdep=
951 ratd_opts="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
952 ratn_opts=
953 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
954 userc=1
955 tmprfs="$tg_ref_cache"
956 tmptgbr="$tg_ref_cache_br"
957 tmpann="$tg_ref_cache_ann"
958 tmpdep="$tg_ref_cache_dep"
959 [ -s "$tg_ref_cache" ] || dogfer=1
960 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
961 else
962 ratd_opts="${ratd_opts}-rmr"
963 ratn_opts="-rma -rmb"
964 tmprfs="$tg_tmp_dir/refs.$$"
965 tmpann="$tg_tmp_dir/ann.$$"
966 tmptgbr="$tg_tmp_dir/tgbr.$$"
967 dogfer=1
969 refpats="\"refs/heads\" \"refs/\$topbases\""
970 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
971 [ -z "$dogfer" ] ||
972 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
973 depscmd="run_awk_topgit_deps $ratd_opts"
974 case "$1" in -td=*)
975 userc=
976 depscmd="$depscmd $1"
977 shift
978 esac
979 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -s "refs/$topbases"'
980 if [ -n "$userc" ]; then
981 if [ -n "$dorad" ]; then
982 eval "$depscmd" >"$tmpdep"
984 depscmd='<"$tmpdep" '
985 else
986 depscmd="$depscmd |"
988 eval "$depscmd" run_awk_topgit_navigate '-a="$tmpann" -b="$tmptgbr"' "$ratn_opts" '"$@"'
991 # recurse_deps_internal NAME [BRANCHPATH...]
992 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
993 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
994 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
995 # (but missing and remotes are always "0")
996 # followed by a 0 for no excess visits or a positive number of excess visits
997 # then the branch name followed by its depedency chain (which might be empty)
998 # An output line might look like this:
999 # 0 1 1 0 t/foo/leaf t/foo/int t/stage
1000 # If no_remotes is non-empty, exclude remotes
1001 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1002 # If with_top_level is non-empty, include the top-level that's normally omitted
1003 # If with_deps_opts is non-empty, always run_awk_topgit_deps with those extra opts
1004 # any branch names in the space-separated recurse_deps_exclude variable
1005 # are skipped (along with their dependencies)
1006 unset_ no_remotes recurse_preorder with_top_level with_deps_opts
1007 recurse_deps_internal()
1009 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
1010 ratr_opts="${recurse_preorder:+-f} ${with_top_level:+-s}"
1011 dogfer=
1012 dorad=1
1013 userc=
1014 tmpdep=
1015 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
1016 userc=1
1017 tmprfs="$tg_ref_cache"
1018 tmptgbr="$tg_ref_cache_br"
1019 tmpann="$tg_ref_cache_ann"
1020 tmpdep="$tg_ref_cache_dep"
1021 [ -s "$tg_ref_cache" ] || dogfer=1
1022 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
1023 else
1024 ratr_opts="$ratr_opts -rmh -rma -rmb"
1025 tmprfs="$tg_tmp_dir/refs.$$"
1026 tmpann="$tg_tmp_dir/ann.$$"
1027 tmptgbr="$tg_tmp_dir/tgbr.$$"
1028 dogfer=1
1030 refpats="\"refs/heads\" \"refs/\$topbases\""
1031 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
1032 tmptgrmtbr=
1033 dorab=1
1034 if [ -z "$no_remotes" ] && [ -n "$base_remote" ]; then
1035 if [ -n "$userc" ]; then
1036 tmptgrmtbr="$tg_ref_cache_rbr"
1037 [ -n "$dogfer" ] || ! [ -s "$tmptgrmtbr" ] || dorab=
1038 else
1039 tmptgrmtbr="$tg_tmp_dir/tgrmtbr.$$"
1040 ratr_opts="$ratr_opts -rmr"
1042 ratr_opts="$ratr_opts -r=\"\$tmptgrmtbr\" -u=\":refs/remotes/\$base_remote/\${topbases#heads/}\""
1044 [ -z "$dogfer" ] ||
1045 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
1046 if [ -n "$tmptgrmtbr" ] && [ -n "$dorab" ]; then
1047 run_awk_topgit_branches -n -h="refs/remotes/$base_remote" -r="$tmprfs" \
1048 "refs/remotes/$base_remote/${topbases#heads/}" >"$tmptgrmtbr"
1050 depscmd="run_awk_topgit_deps -s${with_deps_opts:+ $with_deps_opts}${TG_DEBUG:+ -p=\"\$tg_ref_cache.pre\"}"
1051 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" "refs/$topbases"'
1052 if [ -z "$with_deps_opts" ] && [ -n "$userc" ]; then
1053 if [ -n "$dorad" ]; then
1054 eval "$depscmd" >"$tmpdep"
1056 depscmd='<"$tmpdep" '
1057 else
1058 depscmd="$depscmd |"
1060 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
1061 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
1064 # do_eval CMD
1065 # helper for recurse_deps so that a return statement executed inside CMD
1066 # does not return from recurse_deps. This shouldn't be necessary, but it
1067 # seems that it actually is.
1068 do_eval()
1070 eval "$@"
1073 # becomes read-only for caching purposes
1074 # assigns new value to tg_read_only
1075 # become_cacheable/undo_become_cacheable calls may be nested
1076 become_cacheable()
1078 _old_tg_read_only="$tg_read_only"
1079 if [ -z "$tg_read_only" ]; then
1080 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1081 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1082 tg_read_only=1
1084 _my_ref_cache=
1085 v_create_ref_cache _my_ref_cache
1086 _my_ref_cache="${_my_ref_cache:+1}"
1087 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
1090 # restores tg_read_only and ref_cache to state before become_cacheable call
1091 # become_cacheable/undo_bocome_cacheable calls may be nested
1092 undo_become_cacheable()
1094 case "$tg_read_only" in
1095 "undo"[01]"-"*)
1096 _suffix="${tg_read_only#undo?-}"
1097 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
1098 tg_read_only="$_suffix"
1099 esac
1102 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
1103 become_non_cacheable()
1105 remove_ref_cache
1106 tg_read_only=
1107 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1108 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1111 # call this to make sure the current Git repository has an associated work tree
1112 # also make sure we are not in wayback mode
1113 ensure_work_tree()
1115 [ -z "$wayback" ] ||
1116 die "the wayback machine cannot be used with the specified options"
1117 setup_git_dir_is_bare
1118 [ -n "$git_dir_is_bare" ] || v_get_show_toplevel
1119 [ -n "$git_dir_is_bare" ] || [ -z "$git_toplevel_result" ] || return 0
1120 die "This operation must be run in a work tree"
1123 # call this to make sure Git will not complain about a missing user/email
1124 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
1125 ensure_ident_available()
1127 [ -z "$TG_IDENT_CHECKED" ] || return 0
1128 git var GIT_AUTHOR_IDENT >/dev/null &&
1129 git var GIT_COMMITTER_IDENT >/dev/null || exit
1130 TG_IDENT_CHECKED=1
1131 export TG_IDENT_CHECKED
1132 return 0
1135 # recurse_deps [-o=<options string>] CMD NAME [BRANCHPATH...]
1136 # Recursively eval CMD on all dependencies of NAME.
1137 # Dependencies are visited in topological order.
1138 # If <options string> is given, it's eval'd into the recurse_deps_internal
1139 # call just before the "--" that's passed just before NAME
1140 # CMD can refer to the following variables:
1142 # _ret starts as 0; CMD can change; will be final return result
1143 # _dep bare branch name or ":refs/remotes/..." for a remote
1144 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
1145 # _depchain 0+ space-sep branch names (_name first) form a path to top
1146 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
1147 # _dep_is_leaf boolean "1" if leaf; "" if not
1148 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
1149 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
1150 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
1151 # _dep_xvisits non-negative integer number of excess visits (often 0)
1153 # CMD may use a "return" statement without issue; its return value is ignored,
1154 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
1155 # will stop immediately and the value with the leading "-" stripped off will
1156 # be the final result code
1158 # CMD can refer to $_name for queried branch name,
1159 # $_dep for dependency name,
1160 # $_depchain for space-seperated branch backtrace,
1161 # $_dep_missing boolean to check whether $_dep is present
1162 # and the $_dep_is_tgish and $_dep_annihilated booleans.
1163 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
1164 # It can modify $_ret to affect the return value
1165 # of the whole function.
1166 # If recurse_deps() hits missing dependencies, it will append
1167 # them to space-separated $missing_deps list and skip them
1168 # after calling CMD with _dep_missing set.
1169 # remote dependencies are processed if no_remotes is unset.
1170 # any branch names in the space-separated recurse_deps_exclude variable
1171 # are skipped (along with their dependencies)
1173 # If no_remotes is non-empty, exclude remotes
1174 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1175 # If with_top_level is non-empty, include the top-level that's normally omitted
1176 # If with_deps_opts is non-empty, always run_awk_topgit_deps with those extra opts
1177 # any branch names in the space-separated recurse_deps_exclude variable
1178 # are skipped (along with their dependencies)
1179 recurse_deps()
1181 _opts=
1182 case "$1" in -o=*) _opts="${1#-o=}"; shift; esac
1183 _cmd="$1"; shift
1185 _depsfile="$(get_temp tg-depsfile)"
1186 eval recurse_deps_internal "$_opts" -- '"$@"' >"$_depsfile" || :
1188 _ret=0
1189 while read _ismissing _istgish _isleaf _dep_xvisits _dep _name _deppath; do
1190 _depchain="$_name${_deppath:+ $_deppath}"
1191 _dep_is_tgish=
1192 [ "$_istgish" = "0" ] || _dep_is_tgish=1
1193 _dep_has_remote=
1194 [ "$_istgish" != "2" ] || _dep_has_remote=1
1195 _dep_missing=
1196 if [ "$_ismissing" != "0" ]; then
1197 _dep_missing=1
1198 case " $missing_deps " in *" $_dep "*);;*)
1199 missing_deps="${missing_deps:+$missing_deps }$_dep"
1200 esac
1202 _dep_annihilated=
1203 _dep_is_leaf=
1204 if [ "$_isleaf" = "1" ]; then
1205 _dep_is_leaf=1
1206 elif [ "$_isleaf" = "2" ]; then
1207 _dep_annihilated=1
1209 do_eval "$_cmd" || :
1210 if [ "${_ret#-}" != "$_ret" ]; then
1211 _ret="${_ret#-}"
1212 break
1214 done <"$_depsfile"
1215 rm -f "$_depsfile"
1216 return ${_ret:-0}
1219 # find_leaves NAME
1220 # output (one per line) the unique leaves of NAME
1221 # a leaf is either
1222 # 1) a non-tgish dependency
1223 # 2) the base of a tgish dependency with no non-annihilated dependencies
1224 # duplicates are suppressed (by commit rev) and remotes are always ignored
1225 # if a leaf has an exact tag match that will be output
1226 # note that recurse_deps_exclude IS honored for this operation
1227 # if with_deps_opts is set it will take effect here
1228 find_leaves()
1230 no_remotes=1
1231 with_top_level=1
1232 recurse_preorder=
1233 seen_leaf_refs=
1234 seen_leaf_revs=
1235 while read _ismissing _istgish _isleaf _xvsts _dep _name _deppath; do
1236 [ "$_isleaf" = "1" ] && [ "$_ismissing" = "0" ] || continue
1237 if [ "$_istgish" != "0" ]; then
1238 fulldep="refs/$topbases/$_dep"
1239 else
1240 fulldep="refs/heads/$_dep"
1242 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1243 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1244 if v_ref_exists_rev fullrev "$fulldep"; then
1245 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1246 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1247 # See if Git knows it by another name
1248 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null || git describe --exact-match --tags "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1249 echo "refs/tags/$tagname"
1250 else
1251 echo "$fulldep"
1253 esac
1255 esac
1256 done <<-EOT
1257 $(recurse_deps_internal -l -o=1 -- "$1")
1259 with_top_level=
1262 # branch_needs_update
1263 # This is a helper function for determining whether given branch
1264 # is up-to-date wrt. its dependencies. It expects input as if it
1265 # is called as a recurse_deps() helper.
1266 # In case the branch does need update, it will echo it together
1267 # with the branch backtrace on the output (see needs_update()
1268 # description for details) and set $_ret to non-zero.
1269 branch_needs_update()
1271 if [ -n "$_dep_missing" ]; then
1272 echo "! $_dep $_depchain"
1273 return 0
1276 if [ -n "$_dep_is_tgish" ]; then
1277 [ -z "$_dep_annihilated" ] || return 0
1279 if [ -n "$_dep_has_remote" ]; then
1280 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" || {
1281 echo ":refs/remotes/$base_remote/$_dep $_dep $_depchain"
1282 _ret=1
1285 # We want to sync with our base first and should output this before
1286 # the remote branch, but the order does not actually matter to tg-update
1287 # as it just recurses regardless, but it does matter for tg-info (which
1288 # treats out-of-date bases as though they were already merged in) so
1289 # we output the remote before the base.
1290 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1291 echo ": $_dep $_depchain"
1292 _ret=1
1293 return
1297 if [ -n "$_name" ]; then
1298 case "$_dep" in :*) _fulldep="${_dep#:}";; *) _fulldep="refs/heads/$_dep";; esac
1299 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1300 # Some new commits in _dep
1301 echo "$_dep $_depchain"
1302 _ret=1
1307 # needs_update NAME
1308 # This function is recursive; it outputs reverse path from NAME
1309 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1310 # inner paths first. Innermost name can be :refs/remotes/<remote>/<name>
1311 # if the head is not in sync with the <remote> branch <name>, ':' if
1312 # the head is not in sync with the base (in this order of priority)
1313 # or '!' if dependency is missing. Note that the remote branch, base
1314 # order is reversed from the order they will actually be updated in
1315 # order to accomodate tg info which treats out-of-date items that are
1316 # only in the base as already being in the head for status purposes.
1317 # It will also return non-zero status if NAME needs update (seems backwards
1318 # but think of it as non-zero status if any non-missing output lines produced)
1319 # If needs_update() hits missing dependencies, it will append
1320 # them to space-separated $missing_deps list and skip them.
1321 # if with_deps_opts is set it will take effect here
1322 needs_update()
1324 recurse_deps branch_needs_update "$1"
1327 # append second arg to first arg variable gluing with space if first already set
1328 vplus()
1330 eval "$1=\"\${$1:+\$$1 }\$2\""
1333 # true if whitespace separated first var name list contains second arg
1334 # use `vcontains 3 "value" "some list"` for a literal list
1335 vcontains()
1337 eval case "\" \${$1} \"" in '*" $2 "*) return 0; esac; return 1'
1340 # if the $1 var does not already contain $2 it's appended
1341 vsetadd()
1343 vcontains "$1" "$2" || vplus "$1" "$2"
1346 # reset needs_update_check results to empty
1347 needs_update_check_clear()
1349 unset_ needs_update_processed needs_update_behind needs_update_ahead needs_update_partial
1352 # needs_update_check NAME...
1354 # A faster version of needs_update that always succeeds
1355 # No output and unsuitable for actually performing updates themselves
1356 # If any of NAME... are NOT up-to-date AND they were not already processed
1357 # return status always will be zero however a simple check of
1358 # needs_update_behind after the call will answer the:
1359 # "are any out of date?": test -n "$needs_update_behind"
1360 # "is <x> out of date?": vcontains needs_update_behind "<x>"
1362 # Note that results are cumulative and "no_remotes" is honored as well as other
1363 # variables that modify recurse_deps_internal behavior. See the preceding
1364 # function to reset the results to empty when accumulation should start over.
1366 # Unlike needs_update, the branch names are themselves also checked to see if
1367 # they are out-of-date with respect to their bases or remote branches (not just
1368 # their remote bases). However, this can muddy some status results so this
1369 # can be disabled by setting needs_update_check_no_self to a non-empty value.
1371 # Unlike needs_update, here the remote base check is handled together with the
1372 # remote head check so if one is modified the other is too in the same way.
1374 # Dependencies are normally considered "behind" if they need an update from
1375 # their base or remote but this can be suppressed by setting the
1376 # needs_update_check_no_same to a non-empty value. This will NOT prevent
1377 # parents of those dependencies from still being considered behind in such a
1378 # case even though the dependency itself will not be. Note that setting
1379 # needs_update_check_no_same also implies needs_update_check_no_self.
1381 # The following whitespace-separated lists are updated with the results:
1383 # if with_deps_opts is set it will take effect here
1385 # The "no_remotes" setting is obeyed but remote names themselves will never
1386 # appear in any of the lists
1388 # needs_update_processed
1389 # The branch names in here have been processed and will be skipped
1391 # needs_update_behind
1392 # Any branch named in here needs an update from one or more of its
1393 # direct or indirect dependencies (i.e. it's "out-of-date")
1395 # needs_update_ahead
1396 # Any branch named in here is NOT fully contained by at least one of
1397 # its dependents (i.e. it's a source of "out-of-date (aka dirty)"ness
1399 # needs_update_partial
1400 # Any branch names in here are either missing themselves or have one
1401 # or more detected missing dependencies (a completely missing remote
1402 # branch is never "detected")
1403 needs_update_check()
1405 # each head must be processed independently or else there will be
1406 # confusion about who's missing what and which branches actually are
1407 # out of date
1408 tmptgrdi="$tg_tmp_dir/tgrdi.$$"
1409 for nucname in "$@"; do
1410 ! vcontains needs_update_processed "$nucname" || continue
1411 # no need to fuss with recurse_deps, just use
1412 # recurse_deps_internal directly
1413 recurse_deps_internal -s -o=-1 "$nucname" >"$tmptgrdi"
1414 while read -r _rdi_m _rdi_t _rdi_l _rdi_v _rdi_node _rdi_parent _rdi_chain; do
1415 case "$_rdi_node" in ""|:*) continue; esac # empty or checked with remote
1416 vsetadd needs_update_processed "$_rdi_node"
1417 if [ "$_rdi_m" != "0" ]; then # missing
1418 vsetadd needs_update_partial "$_rdi_node"
1419 [ -z "$_rdi_parent" ] || vsetadd needs_update_partial "$_rdi_parent"
1420 continue
1422 [ "$_rdi_t$_rdi_l" != "12" ] || continue # always skip annihilated
1423 _rdi_dertee= # :)
1424 if [ -n "$_rdi_parent" ]; then # not a "self" line
1425 ! vcontains needs_update_partial "$_rdi_node" || vsetadd needs_update_partial "$_rdi_parent"
1426 ! vcontains needs_update_behind "$_rdi_node" || _rdi_dertee=2
1427 else
1428 [ -z "$needs_update_check_no_self$needs_update_check_no_same" ] || continue # skip self
1430 if [ -z "$_rdi_dertee" ]; then
1431 if [ "$_rdi_t" != "0" ]; then # tgish
1432 if branch_contains "refs/heads/$_rdi_node" "refs/$topbases/$_rdi_node"; then
1433 if [ "$_rdi_t" = "2" ]; then # will never be "2" when no_remotes is set
1434 branch_contains "refs/heads/$_rdi_node" "refs/remotes/$base_remote/$_rdi_node" &&
1435 branch_contains "refs/$topbases/$_rdi_node" "refs/remotes/$base_remote/${topbases#heads/}/$_rdi_node" ||
1436 _rdi_dertee=3
1438 else
1439 _rdi_dertee=3
1441 [ -z "$_rdi_dertee" ] || [ -n "$needs_update_check_no_same" ] || _rdi_dertee=1
1444 [ z"$_rdi_dertee" != z"1" ] || vsetadd needs_update_behind "$_rdi_node"
1445 [ -n "$_rdi_parent" ] || continue # self line
1446 if ! branch_contains "refs/$topbases/$_rdi_parent" "refs/heads/$_rdi_node"; then
1447 _rdi_dertee=1
1448 vsetadd needs_update_ahead "$_rdi_node"
1450 [ -z "$_rdi_dertee" ] || vsetadd needs_update_behind "$_rdi_parent"
1451 done <"$tmptgrdi"
1452 done
1455 # branch_empty NAME [-i | -w]
1456 branch_empty()
1458 if [ -z "$2" ]; then
1459 v_ref_exists_rev _rev "refs/heads/$1" || return 0
1460 _result=
1461 _result_rev=
1462 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1463 [ -z "$_result" ] || [ "$_result_rev" != "$_rev" ] || return $_result
1464 _result=0
1465 v_pretty_tree _pretty1 -t "$1" -b
1466 v_pretty_tree _pretty2 -t "$1" $2
1467 [ "$_pretty1" = "$_pretty2" ] || _result=$?
1468 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1469 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1470 return $_result
1471 else
1472 v_pretty_tree _pretty1 -t "$1" -b
1473 v_pretty_tree _pretty2 -t "$1" $2
1474 [ "$_pretty1" = "$_pretty2" ]
1478 v_get_tdmopt_internal()
1480 [ -n "$1" ] && [ -n "$3" ] || return 0
1481 [ "$2" = "-i" ] || [ "$2" = "-w" ] || return 0
1482 ensure_work_tree
1483 _optval=
1484 if v_verify_topgit_branch _tghead "HEAD" -f; then
1485 if [ "$2" = "-w" ] && [ -f "$root_dir/$3" ] && [ -r "$root_dir/$3" ]; then
1486 _opthash=
1487 if _opthash="$(git hash-object -w -t blob --stdin <"$root_dir/$3")" && [ -n "$_opthash" ]; then
1488 _optval="$4\"$_tghead:$_opthash\""
1490 elif [ "$2" = "-i" ]; then
1491 if _opthash="$(git rev-parse --quiet --verify ":0:$3" --)" && [ -n "$_opthash" ]; then
1492 _optval="$4\"$_tghead:$_opthash\""
1496 eval "$1="'"$_optval"'
1499 # set var $1 to the correct -td= option for use in an eval for $2 -i or -w mode
1500 v_get_tdopt() { v_get_tdmopt_internal "$1" "$2" ".topdeps" "-td="; }
1502 # set var $1 to the correct -tm= option for use in an eval for $2 -i or -w mode
1503 v_get_tmopt() { v_get_tdmopt_internal "$1" "$2" ".topmsg" "-tm="; }
1505 # checkout_symref_full [-f] FULLREF [SEED]
1506 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1507 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1508 # MUST be a committish which if present will be used instead of current FULLREF
1509 # (and FULLREF will be updated to it as well in that case)
1510 # Any merge state is always cleared by this function
1511 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1512 # instead of -m) but it will clear out any unmerged entries
1513 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1514 checkout_symref_full()
1516 _mode=-m
1517 _head="HEAD"
1518 if [ "$1" = "-f" ]; then
1519 _mode="--reset"
1520 _head=
1521 shift
1523 _ishash=
1524 case "$1" in
1525 refs/?*)
1527 $octethl)
1528 _ishash=1
1529 [ -z "$2" ] || [ "$1" = "$2" ] ||
1530 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1531 set -- HEAD "$1"
1534 die "programmer error: invalid checkout_symref_full \"$1\""
1536 esac
1537 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1538 die "invalid committish: \"${2:-$1}\""
1539 # Clear out any MERGE_HEAD kruft
1540 rm -f "$git_dir/MERGE_HEAD" || :
1541 # We have to do all the hard work ourselves :/
1542 # This is like git checkout -b "$1" "$2"
1543 # (or just git checkout "$1"),
1544 # but never creates a detached HEAD (unless $1 is a hash)
1545 git read-tree -u $_mode $_head "$_seedrev" &&
1547 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1548 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1549 } && {
1550 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1554 # switch_to_base NAME [SEED]
1555 switch_to_base()
1557 checkout_symref_full "refs/$topbases/$1" "$2"
1560 # fer_branch_contains [-a|-r] <committish>
1561 # Like `git branch --no-color --contains [-a|-r] <committish>` except
1562 # that full ref names are always output without any 2-character prefix
1563 fer_branch_contains()
1565 _feropt=
1566 if [ $# -gt 1 ]; then
1567 case "$1" in
1568 "-a") _feropt="-a"; shift;;
1569 "-r") _feropt="-r"; shift;;
1570 esac
1572 [ $# -eq 1 ] ||
1573 die "programmer error: fer_branch_contains: wrong number of arguments"
1574 if [ -n "$gferc" ]; then
1575 # easy way, Git is 2.7.0+ and for-each-ref has --contains
1576 case "$_feropt" in
1577 "-a") _ferref="refs/heads refs/remotes";;
1578 "-r") _ferref="refs/remotes";;
1579 *) _ferref="refs/heads";;
1580 esac
1581 git for-each-ref --format='%(refname)' --contains "$1" $_ferref
1582 else
1583 # hard way, munge `git branch --contains` output;
1584 # must run twice for -a to truly avoid ambiguity
1585 # with a ref such as "refs/heads/remotes/foo/bar" present
1586 [ "$_feropt" = "-r" ] ||
1587 git branch --no-color --contains "$@" |
1588 awk '{x=substr($0,3);if(x!~/[ \t]/)print"refs/heads/"x}'
1589 [ "$_feropt" = "" ] ||
1590 git branch --no-color -r --contains "$@" |
1591 awk '{x=substr($0,3);if(x!~/[ \t]/)print"refs/remotes/"x}'
1595 # run editor with arguments
1596 # the editor setting will be cached in $tg_editor (which is eval'd)
1597 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1598 # just in case, noalt_setup will be in effect while the editor is running
1599 run_editor()
1601 tg_editor="$GIT_EDITOR"
1602 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1604 noalt_setup
1605 eval "$tg_editor" '"$@"'
1609 # Show the help messages.
1610 do_help()
1612 _www=
1613 if { [ "$1" = "-h" ] || [ "$1" = "--help" ]; } && [ "$2" = "-w" ]; then
1614 shift 2
1615 set -- -w -h "$@"
1617 if [ "$1" = "-w" ]; then
1618 _www=1
1619 shift
1621 if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
1622 shift
1623 set -- "help" "$@"
1625 if [ "$1" = "st" ]; then
1626 shift
1627 set -- "status" "$@"
1629 if [ -z "$1" ] ; then
1630 # This is currently invoked in all kinds of circumstances,
1631 # including when the user made a usage error. Should we end up
1632 # providing more than a short help message, then we should
1633 # differentiate.
1634 # Petr's comment:
1635 # https://lore.kernel.org/git/20081120131807.GE10491@machine.or.cz/
1637 ## Build available commands list for help output
1639 cmds="$({
1640 printf '%s\n' 'help' 'st[atus]'
1641 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1642 ! [ -r "$cmd" ] && continue
1643 # strip directory part and "tg-" prefix
1644 cmd="${cmd##*/}"
1645 cmd="${cmd#tg-}"
1646 printf '%s\n' "$cmd"
1647 done; } | sort -fu | awk '
1648 NF=1 {s[++n]=$1}
1649 END {
1651 for(i=1;i<=n;++i)
1652 if(length(s[i])>l) l=length(s[i])
1653 if (n<1 || l<1) exit
1654 w=8*int((l+2+7)/8)
1655 c=int(78/w); if (c<1) c=1
1656 r=int((n+c-1)/c)
1657 for (i=1;i<=r;++i) {
1658 printf " "
1659 for (j=0;j<c;++j) {
1660 t=s[i+j*r]
1661 if (t=="")break
1662 if ((i+j*r+r) in s)
1663 printf "%*s", -w, t
1664 else
1665 printf "%s", t
1667 printf "\n"
1671 echo "\
1672 TopGit version $TG_VERSION - A different patch queue manager
1674 Usage: $tgname [<global-option>...] <command> [<command-option-or-arg>...]
1675 Or: $tgname help [-w] [<command>]
1677 Use \"$tgdisplaydir$tgname help tg\" for an overview of TopGit
1678 Use \"$tgdisplaydir$tgname help -w tg\" for an overview of TopGit in a browser
1680 Global Options:
1681 -C <dir> Change directory to <dir> before doing anything more
1682 -r <remote> Pretend 'topgit.remote' is set to <remote>
1683 -u Pretend 'topgit.remote' is not set
1684 -c <name>=<val> Pass config option to git (may be repeated)
1685 --no-pager / -P Disable all pagers (by both TopGit and Git)
1686 --pager / -p Enable use of a pager (aka '--paginate')
1687 -w [:]<tgtag> Activate wayback machine using tg tag <tgtag>
1688 --top-bases Show top-bases location for repository and exit
1689 --exec-path Show command scripts location and exit
1691 Available tg commands:
1693 $cmds"
1694 elif [ -r "$TG_INST_CMDDIR"/tg-$1 ] || [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1695 if [ -n "$_www" ]; then
1696 nohtml=
1697 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1698 echo "${0##*/}: missing html help file:" \
1699 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1700 nohtml=1
1702 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1703 echo "${0##*/}: missing html help file:" \
1704 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1705 nohtml=1
1707 if [ -n "$nohtml" ]; then
1708 echo "${0##*/}: use" \
1709 "\"${0##*/} help $1\" instead" 1>&2
1710 exit 1
1712 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1713 exit
1715 output()
1717 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1718 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1719 echo
1720 elif [ "$1" = "help" ]; then
1721 printf '%s\n' "Usage: ${tgname:-tg} help [-w] [<command>]" \
1722 "Options:" \
1723 " -w view help in browser"
1724 echo
1725 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1726 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1727 echo
1729 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1730 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1733 page output "$1"
1734 else
1735 echo "${0##*/}: no help for $1" 1>&2
1736 do_help
1737 exit 1
1741 check_status()
1743 git_state=
1744 git_remove=
1745 tg_state=
1746 tg_remove=
1747 tg_topmerge=
1748 setup_git_dir_is_bare
1749 [ -z "$git_dir_is_bare" ] || return 0
1751 if [ -e "$git_dir/MERGE_HEAD" ]; then
1752 git_state="merge"
1753 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1754 git_state="am"
1755 git_remove="$git_dir/rebase-apply"
1756 elif [ -e "$git_dir/rebase-apply" ]; then
1757 git_state="rebase"
1758 git_remove="$git_dir/rebase-apply"
1759 elif [ -e "$git_dir/rebase-merge" ]; then
1760 git_state="rebase"
1761 git_remove="$git_dir/rebase-merge"
1762 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1763 git_state="cherry-pick"
1764 elif [ -e "$git_dir/BISECT_LOG" ]; then
1765 git_state="bisect"
1766 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1767 git_state="revert"
1769 if [ -z "$git_state" ] && [ -f "$git_dir/sequencer/todo" ]; then
1770 # See Git's contrib/completion/git-prompt.sh
1771 # the logic in the __git_sequencer_status function
1773 # read will return non-0 status if there's no
1774 # actual EOL character to read, but it will still
1775 # set the variable and Git does not care about the EOL
1776 _stline=
1777 IFS= read -r _stline <"$git_dir/sequencer/todo" || :
1778 [ -n "$_stline" ]
1779 then
1780 # Git does this, git-prompt.sh does not.
1781 # No easy way to trim only leading whitespace
1782 # Without forking, but there usually isn't any.
1783 while [ "${_stline#[$tab ]}" != "$_stline" ]; do
1784 _stline="${_stline#?}"
1785 done
1786 # Git does actually require the following tab or space
1787 # for the mode to be active, but it does NOT require
1788 # anything after the tab or space not even an EOL char!
1789 case "$_stline" in
1790 p["$tab "]*|pick["$tab "]*) git_state="cherry-pick";;
1791 revert["$tab "]*) git_state="revert";;
1792 esac
1795 git_remove="${git_remove#./}"
1798 [ -d "$git_dir/tg-state" ] &&
1799 [ -s "$git_dir/tg-state/state" ] &&
1800 read -r _astate <"$git_dir/tg-state/state" &&
1801 [ "$_astate" = "update" ]
1802 then
1803 tg_state="update"
1804 tg_remove="$git_dir/tg-state"
1805 ! [ -s "$git_dir/tg-state/merging_topfiles" ] || tg_topmerge=1
1807 tg_remove="${tg_remove#./}"
1810 # Show status information
1811 do_status()
1813 do_status_result=0
1814 do_status_verbose=
1815 do_status_help=
1816 abbrev=refs
1817 pfx=
1818 while [ $# -gt 0 ] && case "$1" in
1819 --help|-h)
1820 do_status_help=1
1821 break;;
1822 -vv)
1823 # kludge in this common bundling option
1824 abbrev=
1825 do_status_verbose=1
1826 pfx="## "
1828 --verbose|-v)
1829 [ -z "$do_status_verbose" ] || abbrev=
1830 do_status_verbose=1
1831 pfx="## "
1833 --exit-code)
1834 do_status_result=2
1837 die "unknown status argument: $1"
1839 esac; do shift; done
1840 if [ -n "$do_status_help" ]; then
1841 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1842 return
1844 check_status
1845 symref="$(git symbolic-ref --quiet HEAD)" || :
1846 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1847 if [ -n "$symref" ]; then
1848 uprefpart=
1849 if [ -n "$headrv" ]; then
1850 upref="$(git rev-parse --revs-only --symbolic-full-name @{upstream} -- 2>/dev/null)" || :
1851 if [ -n "$upref" ]; then
1852 uprefpart=" ... ${upref#$abbrev/remotes/}"
1853 mbase="$(git merge-base HEAD "$upref")" || :
1854 ahead="$(git rev-list --count HEAD ${mbase:+--not} $mbase)" || ahead=0
1855 behind="$(git rev-list --count "$upref" ${mbase:+--not} $mbase)" || behind=0
1856 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1857 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1858 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1859 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1860 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1863 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1864 else
1865 echol "${pfx}HEAD -> ${headrv:-?}"
1867 if [ -n "$tg_state" ]; then
1868 extra=
1869 if [ "$tg_state" = "update" ]; then
1870 IFS= read -r uname <"$git_dir/tg-state/name" || :
1871 [ -z "$uname" ] ||
1872 extra="; currently updating branch '$uname'"
1874 echol "${pfx}tg $tg_state in progress$extra"
1875 if [ -s "$git_dir/tg-state/fullcmd" ] && [ -s "$git_dir/tg-state/names" ]; then
1876 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1877 cat "$git_dir/tg-state/fullcmd"
1878 bcnt="$(( $(wc -w < "$git_dir/tg-state/names") ))"
1879 if [ $bcnt -gt 1 ]; then
1880 pcnt=0
1881 ! [ -s "$git_dir/tg-state/processed" ] ||
1882 pcnt="$(( $(wc -w < "$git_dir/tg-state/processed") ))"
1883 echo "${pfx}$pcnt of $bcnt branches updated so far"
1886 if [ "$tg_state" = "update" ]; then
1887 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1888 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1889 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1890 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1893 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1894 if [ "$git_state" = "merge" ]; then
1895 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1896 if [ $ucnt -gt 0 ]; then
1897 echo "${pfx}"'fix conflicts and then "git commit" the result'
1898 else
1899 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1902 if [ -z "$git_state" ]; then
1903 setup_git_dir_is_bare
1904 [ -z "$git_dir_is_bare" ] || return 0
1905 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository???
1906 gspcnt=0
1907 [ -z "$gsp" ] ||
1908 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1909 untr=
1910 if [ "$gspcnt" -eq 0 ]; then
1911 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1912 echo "${pfx}working directory is clean$untr"
1913 [ -n "$tg_state" ] || do_status_result=0
1914 else
1915 echo "${pfx}working directory is DIRTY"
1916 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1921 ## Pager stuff
1923 # isatty FD
1924 isatty()
1926 test -t $1
1929 # pass "diff" to get pager.diff
1930 # if pager.$1 is a boolean false returns cat
1931 # if set to true or unset fails
1932 # otherwise succeeds and returns the value
1933 get_pager()
1935 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1936 [ "$_x" != "true" ] || return 1
1937 echo "cat"
1938 return 0
1940 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1941 echol "$_x"
1942 return 0
1944 return 1
1947 # setup_pager
1948 # Set TG_PAGER to a valid executable
1949 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1950 # See also the following "page" function for ease of use
1951 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1952 # Preference is (same as Git):
1953 # 1. GIT_PAGER
1954 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1955 # 3. core.pager (only if set)
1956 # 4. PAGER
1957 # 5. git var GIT_PAGER
1958 # 6. less
1959 setup_pager()
1961 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1963 emptypager=
1964 if [ -z "$TG_PAGER_IN_USE" ]; then
1965 # TG_PAGER = GIT_PAGER | PAGER | less
1966 # NOTE: GIT_PAGER='' is significant
1967 if [ -n "${GIT_PAGER+set}" ]; then
1968 TG_PAGER="$GIT_PAGER"
1969 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1970 TG_PAGER="$_dp"
1971 elif _cp="$(git config core.pager 2>/dev/null)"; then
1972 TG_PAGER="$_cp"
1973 elif [ -n "${PAGER+set}" ]; then
1974 TG_PAGER="$PAGER"
1975 else
1976 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1977 [ "$_gp" != ":" ] || _gp=
1978 TG_PAGER="${_gp:-less}"
1980 if [ -z "$TG_PAGER" ]; then
1981 emptypager=1
1982 TG_PAGER=cat
1984 else
1985 emptypager=1
1986 TG_PAGER=cat
1989 # Set pager default environment variables
1990 # see pager.c:setup_pager
1991 if [ -z "${LESS+set}" ]; then
1992 LESS="-FRX"
1993 export LESS
1995 if [ -z "${LV+set}" ]; then
1996 LV="-c"
1997 export LV
2000 # this is needed so e.g. $(git diff) will still colorize it's output if
2001 # requested in ~/.gitconfig with color.diff=auto
2002 GIT_PAGER_IN_USE=1
2003 export GIT_PAGER_IN_USE
2005 # this is needed so we don't get nested pagers
2006 TG_PAGER_IN_USE=1
2007 export TG_PAGER_IN_USE
2010 # page eval_arg [arg ...]
2012 # Calls setup_pager then evals the first argument passing it all the rest
2013 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
2014 # by setup_pager (in which case the output is left as-is).
2016 # However, if the first argument starts with '. ' then the rest of the
2017 # arguments are _NOT_ passed to it since the dot command does not take
2018 # arguments, but as it will be evaluated in the scope of this function,
2019 # any arguments it needs to look at must be passed to this function to
2020 # make sure they remain set -- they just shouldn't be passed to the 'dot'
2021 # command itself.
2023 # To handle arbitrary paging duties, collect lines to be paged into a
2024 # function and then call page with the function name or perhaps func_name "$@".
2026 # If no arguments at all are passed in do nothing (return with success).
2027 page()
2029 [ $# -gt 0 ] || return 0
2030 setup_pager
2031 _evalarg="$1"; shift
2032 _evalargs='"$@"'
2033 [ ". ${_evalarg#. }" != "$_evalarg" ] || _evalargs=
2034 if [ -n "$emptypager" ]; then
2035 eval "$_evalarg" $_evalargs
2036 else
2037 { eval "$_evalarg" $_evalargs; } | eval "$TG_PAGER"
2041 # get_temp NAME [-d]
2042 # creates a new temporary file (or directory with -d) in the global
2043 # temporary directory $tg_tmp_dir with pattern prefix NAME
2044 get_temp()
2046 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
2049 # automatically called by strftime
2050 # does nothing if already setup
2051 # may be called explicitly if the first call would otherwise be in a subshell
2052 # so that the setup is only done once before subshells start being spawned
2053 setup_strftime()
2055 [ -z "$strftime_is_setup" ] || return 0
2057 # date option to format raw epoch seconds values
2058 daterawopt=
2059 _testes='951807788'
2060 _testdt='2000-02-29 07:03:08 UTC'
2061 _testfm='%Y-%m-%d %H:%M:%S %Z'
2062 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
2063 daterawopt='-d@'
2064 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
2065 daterawopt='-r'
2067 strftime_is_setup=1
2070 # $1 => strftime format string to use
2071 # $2 => raw timestamp as seconds since epoch
2072 # $3 => optional time zone string (empty/absent for local time zone)
2073 strftime()
2075 setup_strftime
2076 if [ -n "$daterawopt" ]; then
2077 if [ -n "$3" ]; then
2078 TZ="$3" date "$daterawopt$2" "+$1"
2079 else
2080 date "$daterawopt$2" "+$1"
2082 else
2083 if [ -n "$3" ]; then
2084 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
2085 else
2086 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
2091 got_cdup_result=
2092 git_cdup_result=
2093 v_get_show_cdup()
2095 if [ -z "$got_cdup_result" ]; then
2096 git_cdup_result="$(git rev-parse --show-cdup)"
2097 got_cdup_result=1
2099 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
2102 got_toplevel_result=
2103 git_toplevel_result=
2104 v_get_show_toplevel()
2106 if [ -z "$got_toplevel_result" ]; then
2107 git_toplevel_result="$(git rev-parse --show-toplevel)"
2108 got_toplevel_result=1
2110 [ -z "$1" ] || eval "$1="'"$git_toplevel_result"'
2113 git_dir_is_bare_setup=
2114 setup_git_dir_is_bare()
2116 if [ -z "$git_dir_is_bare_setup" ]; then
2117 git_dir_is_bare="$(git rev-parse --is-bare-repository)"
2118 [ z"$git_dir_is_bare" = z"true" ] || git_dir_is_bare=
2119 git_dir_is_bare_setup=1
2123 git_hooks_pat_list="\
2124 [a]pplypatch-ms[g] [p]re-applypatc[h] [p]ost-applypatc[h] [p]re-commi[t] \
2125 [p]repare-commit-ms[g] [c]ommit-ms[g] [p]ost-commi[t] [p]re-rebas[e] \
2126 [p]ost-checkou[t] [p]ost-merg[e] [p]re-pus[h] [p]re-receiv[e] [u]pdat[e] \
2127 [p]ost-receiv[e] [p]ost-updat[e] [p]ush-to-checkou[t] [p]re-auto-g[c] \
2128 [p]ost-rewrit[e]"
2130 # git_hooks_dir must already be set to the value of core.hooksPath which
2131 # exists and is an absolute path. The first and only argument is the
2132 # "pwd -P" of the $git_hooks_dir directory. If the core.hooksPath setting
2133 # appears to be "friendly" attempt to alter it to be an absolute path to
2134 # "$git_common_dir/hooks" instead. A "friendly" core.hooksPath setting
2135 # points to a directory for which "$git_common_dir/hooks" already has
2136 # entries which are symbolic links to the same core.hooksPath items.
2137 # There's no POSIX readlink utility, but there is a 'cmp -s' utility so we
2138 # use that instead to check. Also the "friendly" core.hooksPath must be
2139 # something that's recognizable as belonging to a "friendly".
2140 maybe_adjust_friendly_hooks_path()
2142 case "$1" in */_global/hooks);;*) return 0; esac
2143 [ -n "$1" ] && [ -d "$1" ] && [ -d "$git_common_dir/hooks" ] || return 0
2144 [ -w "$git_common_dir" ] || return 0
2145 ! [ -e "$git_common_dir/config" ] || {
2146 [ -f "$git_common_dir/config" ] && [ -w "$git_common_dir/config" ]
2147 } || return 0
2148 oktoswitch=1
2149 for ghook in $(cd "$1" && eval "echo $git_hooks_pat_list"); do
2150 case "$ghook" in "["*) continue; esac
2151 [ -x "$1/$ghook" ] &&
2152 [ -f "$1/$ghook" ] || continue
2153 [ -x "$git_common_dir/hooks/$ghook" ] &&
2154 [ -f "$git_common_dir/hooks/$ghook" ] &&
2155 cmp -s "$1/$ghook" "$git_common_dir/hooks/$ghook" || {
2156 oktoswitch=
2157 break
2159 done
2160 if [ -n "$oktoswitch" ]; then
2161 # a known "friendly" was detected and the hooks match;
2162 # go ahead and silently switch the path
2163 ! git config core.hooksPath "$git_common_dir/hooks" >/dev/null 2>&1 ||
2164 git_hooks_dir="$git_common_dir/hooks"
2166 unset_ oktoswitch
2167 return 0
2170 git_hooks_dir=
2171 setup_git_hooks_dir()
2173 [ -z "$git_hooks_dir" ] || return 0
2174 git_hooks_dir="$git_common_dir/hooks"
2175 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
2176 case "$gchp" in
2177 /[!/]*)
2178 if [ -d "$gchp" ]; then
2179 # if core.hooksPath is just another name for
2180 # $git_common_dir/hooks, keep referring to it
2181 # by $git_common_dir/hooks
2182 abscdh="$(cd "$git_common_dir" && pwd -P)/hooks"
2183 abshpd="$(cd "$gchp" && pwd -P)"
2184 if [ "$abshpd" != "$abscdh" ]; then
2185 git_hooks_dir="$gchp"
2186 maybe_adjust_friendly_hooks_path "$abshpd"
2188 unset_ abscdh abshpd
2189 else
2190 [ -n "$1" ] || warn "ignoring non-existent core.hooksPath: $gchp"
2194 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
2196 esac
2197 unset_ gchp
2201 setup_git_dirs()
2203 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
2204 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
2205 git_dir="$(cd "$git_dir" && pwd)"
2207 if [ -z "$git_common_dir" ]; then
2208 if vcmp "$git_version" '>=' "2.5"; then
2209 # rev-parse --git-common-dir is broken and may give
2210 # an incorrect result unless the current directory is
2211 # already set to the top level directory
2212 v_get_show_cdup
2213 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
2214 else
2215 git_common_dir="$git_dir"
2218 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
2219 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
2220 # disallow alternate ref backends
2221 _rfv="$(git config --int --get core.repositoryformatversion 2>/dev/null)" || :
2222 if [ "${_rfv:-0}" -ge 1 ]; then
2223 _rrs="$(git config --get extensions.refstorage 2>/dev/null)" || :
2224 [ -z "$_rrs" ] || die "Unsupported extensions.refStorage=$_rrs repository format"
2226 activate_awksome $1
2229 mtblob=
2230 setup_hashalgo_vars()
2232 test -z "$mtblob" || return 0
2234 # the empty blob will match the hash algorithm of the repository (if any)
2236 mtblob="$(git hash-object -t blob --stdin </dev/null 2>/dev/null)" ||
2237 die "git hash-object failed"
2238 case "${#mtblob}" in
2240 nullsha="0000000000000000000000000000000000000000"
2241 mttree="4b825dc642cb6eb9a060e54bf8d69288fbee4904"
2242 octethl="$octet20"
2245 nullsha="0000000000000000000000000000000000000000000000000000000000000000"
2246 mttree="6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321"
2247 octethl="$octet32"
2250 die "git hash-object failed"
2251 esac
2254 ## Include awk scripts and their utility functions (separated for easier debugging)
2255 awksome_loaded=
2256 activate_awksome()
2258 test -z "$awksome_loaded" || return 0
2260 # tg--awksome requires that mtblob be set before sourcing it;
2261 # mtblob is configured by setup_hashalgo_vars;
2262 # therefore run setup_hashalgo_vars first.
2264 setup_hashalgo_vars $1
2265 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
2266 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
2267 . "$TG_INST_CMDDIR/tg--awksome"
2269 awksome_loaded=1
2272 basic_setup_remote()
2274 if [ -z "$base_remote" ]; then
2275 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
2276 base_remote="$TG_EXPLICIT_REMOTE"
2277 else
2278 base_remote="$(git config topgit.remote 2>/dev/null)" || :
2283 basic_setup()
2285 setup_git_dirs $1
2286 basic_setup_remote
2287 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
2288 tgnosequester=
2289 [ "$tgsequester" != "false" ] || tgnosequester=1
2290 unset_ tgsequester
2292 # catch errors if topbases is used without being set
2293 unset_ tg_topbases_set
2294 topbases="programmer*:error"
2295 topbasesrx="programmer*:error}"
2296 oldbases="$topbases"
2299 tmpdir_cleanup()
2301 test -z "$tg_tmp_dir" || ! test -d "$tg_tmp_dir" || ${TG_DEBUG:+echo} rm -rf "$tg_tmp_dir" >&2 || :
2304 tmpdir_setup()
2306 [ -z "$tg_tmp_dir" ] || return 0
2307 if [ -n "$TG_TMPDIR" ] && [ -d "$TG_TMPDIR" ] && [ -w "$TG_TMPDIR" ] &&
2308 { >"$TG_TMPDIR/.check"; } >/dev/null 2>&1; then
2309 tg_tmp_dir="$TG_TMPDIR"
2310 else
2311 tg_tmp_dir=
2312 TRAPEXIT_='tmpdir_cleanup'
2313 trap 'trapexit_ 129' HUP
2314 trap 'trapexit_ 130' INT
2315 trap 'trapexit_ 131' QUIT
2316 trap 'trapexit_ 134' ABRT
2317 trap 'trapexit_ 141' PIPE
2318 trap 'trapexit_ 143' TERM
2319 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2320 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2321 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2322 [ -z "$tg_tmp_dir" ] || tg_tmp_dir="$(cd "$tg_tmp_dir" && pwd -P)"
2324 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_tmp_dir/.check"; } >/dev/null 2>&1 ||
2325 die "could not create a writable temporary directory"
2327 # whenever tg_tmp_dir is != "" these must always be set
2328 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
2329 tg_ref_cache_br="$tg_ref_cache.br"
2330 tg_ref_cache_rbr="$tg_ref_cache.rbr"
2331 tg_ref_cache_ann="$tg_ref_cache.ann"
2332 tg_ref_cache_dep="$tg_ref_cache.dep"
2335 cachedir_setup()
2337 [ -z "$tg_cache_dir" ] || return 0
2338 user_id_no="$(id -u)" || :
2339 : "${user_id_no:=_99_}"
2340 tg_cache_dir="$git_common_dir/tg-cache"
2341 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2342 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
2343 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2344 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2345 if [ -z "$tg_cache_dir" ]; then
2346 tg_cache_dir="$tg_tmp_dir/tg-cache"
2347 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2348 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2350 [ -n "$tg_cache_dir" ] ||
2351 die "could not create a writable tg-cache directory (even a temporary one)"
2353 if [ -n "$2" ]; then
2354 # allow the wayback machine to share a separate cache
2355 [ -d "$tg_cache_dir/wayback" ] || mkdir "$tg_cache_dir/wayback" >/dev/null 2>&1 || :
2356 ! [ -d "$tg_cache_dir/wayback" ] || ! { >"$tg_cache_dir/wayback/.tgcache"; } >/dev/null 2>&1 ||
2357 tg_cache_dir="$tg_cache_dir/wayback"
2361 # set up alternate deb dirs
2362 altodb_setup()
2364 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
2365 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
2366 # so we avoid it if possible and require v2.11.1 to do it at all
2367 # otherwise just don't make an alternates temporary store in that case;
2368 # it's okay to not have one; everything will still work; the nicety of
2369 # making the temporary tree objects vanish when tg exits just won't
2370 # happen in that case but nothing will break also be sure to reuse
2371 # the parent's if we've been recursively invoked and it's for the
2372 # same repository we were invoked on
2374 tg_use_alt_odb=1
2375 _fullodbdir=
2376 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
2377 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] && _fullodbdir="$(cd "$_odbdir" && pwd -P)" ||
2378 die "could not find objects directory"
2379 if [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
2380 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
2381 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
2382 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
2383 tg_use_alt_odb=2
2386 _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
2387 if [ "$tg_use_alt_odb" = "1" ]; then
2388 # create an alternate objects database to keep the ephemeral objects in
2389 mkdir -p "$tg_tmp_dir/objects/info"
2390 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
2391 [ "$_fullodbdir" = "$TG_OBJECT_DIRECTORY" ] ||
2392 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
2394 case "$_fulltmpdir" in *[";:"]*|'"'*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
2395 if [ "$tg_use_alt_odb" = "1" ]; then
2396 case "$TG_OBJECT_DIRECTORY" in
2397 *[";:"]*|'"'*)
2398 # surround in "..." and backslash-escape internal '"' and '\\'
2399 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
2400 sed 's/\([""\\]\)/\\\1/g')\""
2403 _altodbdq="$TG_OBJECT_DIRECTORY"
2405 esac
2406 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2407 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2408 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2409 else
2410 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
2412 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
2413 if [ -n "$GIT_OBJECT_DIRECTORY" ]; then
2414 export GIT_OBJECT_DIRECTORY
2415 else
2416 unset_ GIT_OBJECT_DIRECTORY
2421 noalt_setup()
2423 if [ "${TG_PRESERVED_ALTERNATES+set}" = "set" ]; then
2424 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
2425 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2426 export GIT_ALTERNATE_OBJECT_DIRECTORIES
2427 else
2428 unset_ GIT_ALTERNATE_OBJECT_DIRECTORIES
2431 unset_ TG_TMPDIR TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES tg_use_alt_odb
2434 ## Initial setup
2435 initial_setup()
2437 # suppress the merge log editor feature since git 1.7.10
2439 GIT_MERGE_AUTOEDIT=no
2440 export GIT_MERGE_AUTOEDIT
2442 basic_setup $1
2443 iowopt=
2444 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
2445 gcfbopt= crlopt=
2446 ! vcmp "$git_version" '>=' "2.6" || { gcfbopt="--buffer"; crlopt="--create-reflog"; }
2447 gferc=
2448 ! vcmp "$git_version" '>=' "2.7" || gferc=1
2449 auhopt=
2450 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
2451 v_get_show_cdup root_dir
2452 root_dir="${root_dir:-.}"
2453 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
2454 [ "$logrefupdates" = "true" ] || logrefupdates=
2456 # make sure root_dir doesn't end with a trailing slash.
2458 root_dir="${root_dir%/}"
2460 # create global temporary and cache directories, usually inside GIT_DIR
2462 tmpdir_setup
2463 unset_ TG_TMPDIR
2464 cachedir_setup
2466 # the wayback machine directory serves as its own "altodb"
2467 [ -n "$wayback" ] || altodb_setup
2470 activate_wayback_machine()
2472 [ -n "${1#:}" ] || [ -n "$2" ] || { wayback=; return 0; }
2473 setup_git_dirs
2474 tmpdir_setup
2475 altodb_setup
2476 tgwbr=
2477 tgwbr2=
2478 if [ -n "${1#:}" ]; then
2479 tgwbr="$(get_temp wbinfo)"
2480 tgwbr2="${tgwbr}2"
2481 tg revert --list --no-short "${1#:}" >"$tgwbr" && test -s "$tgwbr" || return 1
2482 # tg revert will likely leave a revert-tag-only cache which is not what we want
2483 remove_ref_cache
2485 cachedir_setup "" 1 # use a separate wayback cache dir
2486 # but don't step on the normal one if the separate one could not be set up
2487 case "$tg_cache_dir" in */wayback);;*) tg_cache_dir=; esac
2488 altodb="$TG_OBJECT_DIRECTORY"
2489 if [ -n "$3" ] && [ -n "$2" ]; then
2490 [ -d "$3" ] || { mkdir -p "$3" && [ -d "$3" ]; } ||
2491 die "could not create wayback directory: $3"
2492 tg_wayback_dir="$(cd "$3" && pwd -P)" || die "could not get wayback directory full path"
2493 [ -d "$tg_wayback_dir/.git" ] || { mkdir -p "$tg_wayback_dir/.git" && [ -d "$tg_wayback_dir/.git" ]; } ||
2494 die "could not initialize wayback directory: $3"
2495 is_empty_dir "$tg_wayback_dir" ".git" && is_empty_dir "$tg_wayback_dir/.git" "." ||
2496 die "wayback directory is not empty: $3"
2497 mkdir "$tg_wayback_dir/.git/objects"
2498 mkdir "$tg_wayback_dir/.git/objects/info"
2499 cat "$altodb/info/alternates" >"$tg_wayback_dir/.git/objects/info/alternates"
2500 else
2501 tg_wayback_dir="$tg_tmp_dir/wayback"
2502 mkdir "$tg_wayback_dir"
2503 mkdir "$tg_wayback_dir/.git"
2504 ln -s "$altodb" "$tg_wayback_dir/.git/objects"
2506 mkdir "$tg_wayback_dir/.git/refs"
2507 printf '0 Wayback Machine' >"$tg_wayback_dir/.git/gc.pid"
2508 qpesc="$(printf '%s\n' "$git_common_dir" | sed -e 's/\([\\""]\)/\\\1/g' -e '$!s/$/\\n/' | tr -d '\n')"
2509 laru="false"
2510 [ -z "$2" ] || laru="true"
2511 rfv=0
2512 ofmt=
2513 if [ "${#mtblob}" = 64 ]; then
2514 rfv=1
2515 ofmt="$lf${tab}objectFormat = sha256"
2517 printf '%s' "\
2518 [include]
2519 path = \"$qpesc/config\"
2520 [core]
2521 bare = false
2522 logAllRefUpdates = $laru
2523 repositoryFormatVersion = $rfv
2524 [extensions]$ofmt
2525 preciousObjects = true
2526 [gc]
2527 auto = 0
2528 autoDetach = false
2529 autoPackLimit = 0
2530 packRefs = false
2531 [remote \"wayback\"]
2532 url = \"$qpesc\"
2533 [push]
2534 default = nothing
2535 followTags = true
2536 [alias]
2537 wayback-updates = fetch -u --force --no-tags --dry-run wayback refs/*:refs/*
2538 " >"$tg_wayback_dir/.git/config"
2539 cat "$git_dir/HEAD" >"$tg_wayback_dir/.git/HEAD"
2540 case "$1" in ":"?*);;*)
2541 git show-ref >"$tg_wayback_dir/.git/packed-refs"
2542 git --git-dir="$tg_wayback_dir/.git" pack-refs --all
2543 esac
2544 noalt_setup
2545 TG_OBJECT_DIRECTORY="$altodb" && export TG_OBJECT_DIRECTORY
2546 if [ -n "${1#:}" ]; then
2547 <"$tgwbr" sed 's/^\([^ ][^ ]*\) \([^ ][^ ]*\)$/update \2 \1/' |
2548 git --git-dir="$tg_wayback_dir/.git" update-ref -m "wayback to $1" ${2:+$crlopt} --stdin
2550 if test -n "$2"; then
2551 # extra setup for potential shell
2552 qpesc2="$(printf '%s\n' "$git_common_dir" | sed -e 's/\([\\""]\)/\\\\\1/g' -e '$!s/$/\\n/' | tr -d '\n')"
2553 printf '\twayback-repository = "!printf '\''%%s\\\\n'\'' \\"%s\\""\n' "$qpesc2" >>"$tg_wayback_dir/.git/config"
2554 qtesc="$(printf '%s\n' "${1:-:}" | sed 's/\([""]\)/\\\1/g')"
2555 printf '\twayback-tag = "!printf '\''%%s\\\\n'\'' \\"%s\\""\n' "$qtesc" >>"$tg_wayback_dir/.git/config"
2556 if [ -d "$git_common_dir/rr-cache" ]; then
2557 ln -s "$git_common_dir/rr-cache" "$tg_wayback_dir/.git/rr-cache"
2558 printf "[rerere]\n\tenabled = true\n" >>"$tg_wayback_dir/.git/config"
2560 if [ z"$2" != z"2" ]; then
2561 wbauth=
2562 wbprnt=
2563 if [ -n "${1#:}" ]; then
2564 [ -n "$tgwbr2" ] || tgwbr2="$(get_temp wbtag)"
2565 git --git-dir="$git_common_dir" cat-file tag "${1#:}" >"$tgwbr2" || return 1
2566 wbprnt="${lf}parent $(git --git-dir="$git_common_dir" rev-parse --verify --quiet "${1#:}"^0 -- 2>/dev/null)" || wbprnt=
2567 wbauth="$(<"$tgwbr2" awk '{if(!$0)exit;if($1=="tagger")print "author" substr($0,7)}')"
2569 wbcmtr="committer Wayback Machine <-> $(date "+%s %z")"
2570 [ -n "$wbauth" ] || wbauth="author${wbcmtr#committer}"
2571 wbtree="$(git --git-dir="$tg_wayback_dir/.git" mktree </dev/null)"
2572 wbcmt="$({
2573 printf '%s\n' "tree $wbtree$wbprnt" "$wbauth" "$wbcmtr" ""
2574 if [ -n "$tgwbr2" ]; then
2575 <"$tgwbr2" sed -e '1,/^$/d' -e '/^-----BEGIN/,$d' | git stripspace
2576 else
2577 echo "Wayback Machine"
2579 } | git --git-dir="$tg_wayback_dir/.git" hash-object -t commit -w --stdin)"
2580 test -n "$wbcmt" || return 1
2581 echo "$wbcmt" >"$tg_wayback_dir/.git/HEAD"
2584 cd "$tg_wayback_dir"
2585 unset git_dir git_common_dir
2588 set_topbases()
2590 # refer to "top-bases" in a refname with $topbases
2592 [ -z "$tg_topbases_set" ] || return 0
2594 activate_awksome # may not have been loaded yet
2595 topbases_implicit_default=1
2596 # See if topgit.top-bases is set to heads or refs
2597 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
2598 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
2599 if [ -n "$1" ]; then
2600 # never die on the hook script
2601 unset_ tgtb
2602 else
2603 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
2606 if [ -n "$tgtb" ]; then
2607 case "$tgtb" in
2608 heads)
2609 topbases="heads/{top-bases}"
2610 topbasesrx="heads/[{]top-bases[}]"
2611 oldbases="top-bases";;
2612 refs)
2613 topbases="top-bases"
2614 topbasesrx="top-bases"
2615 oldbases="heads/{top-bases}";;
2616 esac
2617 # MUST NOT be exported
2618 unset_ tgtb tg_topbases_set topbases_implicit_default
2619 tg_topbases_set=1
2620 return 0
2622 unset_ tgtb
2624 # check heads and top-bases and see what state the current
2625 # repository is in. remotes are ignored.
2627 rc=0 activebases=
2628 activebases="$(
2629 git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null |
2630 run_awk_ref_prefixes ${1:+-e} -n -- "refs/heads/{top-bases}" "refs/top-bases" "refs/heads")" ||
2631 rc=$?
2632 if [ "$rc" = "65" ]; then
2633 # Complain and die
2634 err "repository contains existing TopGit branches"
2635 err "but some use refs/top-bases/... for the base"
2636 err "and some use refs/heads/{top-bases}/... for the base"
2637 err "with the latter being the new, preferred location"
2638 err "set \"topgit.top-bases\" to either \"heads\" to use"
2639 err "the new heads/{top-bases} location or \"refs\" to use"
2640 err "the old top-bases location."
2641 err "(the tg migrate-bases command can also resolve this issue)"
2642 die "schizophrenic repository requires topgit.top-bases setting"
2644 [ -z "$activebases" ] || unset_ topbases_implicit_default
2645 if [ "$activebases" = "refs/heads/{top-bases}" ]; then
2646 topbases="heads/{top-bases}"
2647 topbasesrx="heads/[{]top-bases[}]"
2648 oldbases="top-bases"
2649 else
2650 # default is still top-bases for now
2651 topbases="top-bases"
2652 topbasesrx="top-bases"
2653 oldbases="heads/{top-bases}"
2655 # MUST NOT be exported
2656 unset_ rc activebases tg_topases_set
2657 tg_topbases_set=1
2658 return 0
2661 # $1 is remote name to check
2662 # $2 is optional variable name to set to result of check
2663 # $3 is optional command name to use in message (defaults to $cmd)
2664 # Fatal error if remote has schizophrenic top-bases
2665 # No error (and $2, if provided, will be set to empty) if remote has no top-bases at all
2666 check_remote_topbases()
2668 [ -n "$1" ] || die "programmer error: check_remote_topbases called with no remote argument"
2669 _crrc=0 _crremotebases=
2670 _crremotebases="$(
2671 git for-each-ref --format='%(refname)' "refs/remotes/$1" 2>/dev/null |
2672 run_awk_ref_prefixes -n -- "refs/remotes/$1/{top-bases}" "refs/remotes/$1/top-bases" "refs/remotes/$1")" ||
2673 _crrc=$?
2674 if [ "$_crrc" = "65" ]; then
2675 err "remote \"$1\" has top-bases in both locations:"
2676 err " refs/remotes/$1/{top-bases}/..."
2677 err " refs/remotes/$1/top-bases/..."
2678 err "set \"topgit.top-bases\" to \"heads\" for the first, preferred location"
2679 err "or set \"topgit.top-bases\" to \"refs\" for the second, old location"
2680 err "(the \"-c topgit.top-bases=<val>\" option can be used for this)"
2681 err "then re-run the tg ${3:-$cmd} command"
2682 err "(the tg migrate-bases command can also help with this problem)"
2683 die "schizophrenic remote \"$1\" requires topgit.top-bases setting"
2685 [ "$_crrc" != "66" ] || _crremotebases= # just to be sure
2686 [ -z "$2" ] || eval "$2="'"$_crremotebases"'
2687 unset _crrc _crremotebases
2688 return 0
2691 # init_reflog "ref"
2692 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
2693 # an empty log file to exist so that ref changes will be logged
2694 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
2695 # However, if "$1" is "refs/tgstash" then always make the reflog
2696 # The only ref not under refs/ that Git will write a reflog for is HEAD;
2697 # no matter what, it will NOT update a reflog for any other bare refs so
2698 # just quietly succeed when passed TG_STASH without doing anything.
2699 init_reflog()
2701 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
2702 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
2703 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
2704 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
2705 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
2708 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
2709 # a symbolic link. The directory part must exist, but the basename need not.
2710 v_get_abs_path()
2712 [ -n "$1" ] && [ -n "$2" ] || return 1
2713 set -- "$1" "$2" "${2%/}"
2714 case "$3" in
2715 */*) set -- "$1" "$2" "${3%/*}";;
2716 * ) set -- "$1" "$2" ".";;
2717 esac
2718 case "$2" in */)
2719 set -- "$1" "${2%/}" "$3" "/"
2720 esac
2721 [ -d "$3" ] || return 1
2722 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
2725 ## Startup
2727 : "${TG_INST_CMDDIR:=@cmddir@}"
2728 : "${TG_INST_SHAREDIR:=@sharedir@}"
2729 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
2731 [ -d "$TG_INST_CMDDIR" ] ||
2732 die "No command directory: '$TG_INST_CMDDIR'"
2734 if [ -n "$tg__include" ]; then
2736 # We were sourced from another script for our utility functions;
2737 # this is set by hooks. Skip the rest of the file. A simple return doesn't
2738 # work as expected in every shell. See https://bugs.debian.org/516188
2740 # ensure setup happens
2742 initial_setup 1
2743 set_topbases 1
2744 noalt_setup
2746 else
2748 set -e
2750 tgbin="$0"
2751 tgdir="${tgbin%/}"
2752 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
2753 tgdir="${tgdir%/*}/"
2754 tgname="${tgbin##*/}"
2755 [ "$0" != "$tgname" ] || tgdir=""
2757 # If tg contains a '/' but does not start with one then replace it with an absolute path
2759 case "$0" in /*) ;; */*)
2760 tgdir="$(cd "${0%/*}" && pwd -P)/"
2761 tgbin="$tgdir$tgname"
2762 esac
2764 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
2765 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2767 tgdisplaydir="$tgdir"
2768 tgdisplay="$tgbin"
2769 tgdisplayac="$tgdisplay"
2771 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2772 _tgabs="$_tgnameabs" &&
2773 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2774 [ "$_tgabs" = "$_tgnameabs" ]
2775 then
2776 tgdisplaydir=""
2777 tgdisplay="$tgname"
2778 tgdisplayac="$tgdisplay"
2780 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2781 unset_ _tgabs _tgnameabs
2783 tg() (
2784 TG_TMPDIR="$tg_tmp_dir" && export TG_TMPDIR &&
2785 exec "$tgbin" "$@"
2788 explicit_remote=
2789 explicit_dir=
2790 gitcdopt=
2791 noremote=
2792 forcepager=
2793 wayback=
2795 cmd=
2796 while :; do case "$1" in
2798 help|--help|-h)
2799 cmd=help
2800 shift
2801 break;;
2803 status|--status)
2804 cmd=status
2805 shift
2806 break;;
2808 --hooks-path)
2809 cmd=hooks-path
2810 shift
2811 break;;
2813 --exec-path)
2814 cmd=exec-path
2815 shift
2816 break;;
2818 --awk-path)
2819 cmd=awk-path
2820 shift
2821 break;;
2823 --top-bases)
2824 cmd=top-bases
2825 shift
2826 break;;
2828 --no-pager|-P)
2829 forcepager=0
2830 shift;;
2832 --pager|-p|--paginate)
2833 forcepager=1
2834 shift;;
2837 shift
2838 if [ -z "$1" ]; then
2839 echo "Option -r requires an argument." >&2
2840 do_help
2841 exit 1
2843 unset_ noremote
2844 base_remote="$1"
2845 explicit_remote="$base_remote"
2846 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2847 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2848 shift;;
2851 unset_ base_remote explicit_remote
2852 noremote=1
2853 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2854 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2855 shift;;
2858 shift
2859 if [ -z "$1" ]; then
2860 echo "Option -C requires an argument." >&2
2861 do_help
2862 exit 1
2864 cd "$1"
2865 unset_ GIT_DIR GIT_COMMON_DIR GIT_OBJECT_DIRECTORY
2866 if [ -z "$explicit_dir" ]; then
2867 explicit_dir="$1"
2868 else
2869 explicit_dir="$PWD"
2871 gitcdopt=" -C \"$explicit_dir\""
2872 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2873 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2874 tgdisplayac="$tgdisplay"
2875 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2876 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2877 shift;;
2880 shift
2881 if [ -z "$1" ]; then
2882 echo "Option -c requires an argument." >&2
2883 do_help
2884 exit 1
2886 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2887 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2888 export GIT_CONFIG_PARAMETERS
2889 shift;;
2892 if [ -n "$wayback" ]; then
2893 echo "Option -w may be used at most once." >&2
2894 do_help
2895 exit 1
2897 shift
2898 if [ -z "$1" ]; then
2899 echo "Option -w requires an argument." >&2
2900 do_help
2901 exit 1
2903 wayback="$1"
2904 shift;;
2907 shift
2908 break;;
2911 echo "Invalid option $1 (command options must appear AFTER the command)." >&2
2912 do_help
2913 exit 1;;
2916 break;;
2918 esac; done
2919 if [ z"$forcepager" = z"0" ]; then
2920 GIT_PAGER_IN_USE=1 TG_PAGER_IN_USE=1 &&
2921 export GIT_PAGER_IN_USE TG_PAGER_IN_USE
2924 [ -n "$cmd" ] || [ $# -lt 1 ] || { cmd="$1"; shift; }
2926 ## Dispatch
2928 [ -n "$cmd" ] || { do_help; exit 1; }
2930 case "$cmd" in
2932 help)
2933 do_help "$@"
2934 exit 0;;
2936 status|st)
2937 unset_ base_remote
2938 basic_setup
2939 set_topbases
2940 do_status "$@"
2941 exit ${do_status_result:-0};;
2943 hooks-path)
2944 # Internal command
2945 echol "$TG_INST_HOOKSDIR";;
2947 exec-path)
2948 # Internal command
2949 echol "$TG_INST_CMDDIR";;
2951 awk-path)
2952 # Internal command
2953 echol "$TG_INST_CMDDIR/awk";;
2955 top-bases)
2956 # Maintenance command
2957 do_topbases_help=
2958 show_remote_topbases=
2959 case "$1" in
2960 --help|-h)
2961 do_topbases_help=0;;
2962 -r|--remote)
2963 if [ $# -eq 2 ] && [ -n "$2" ]; then
2964 # unadvertised, but make it work
2965 base_remote="$2"
2966 shift
2968 show_remote_topbases=1;;
2970 [ $# -eq 0 ] || do_topbases_help=1;;
2971 esac
2972 [ $# -le 1 ] || do_topbases_help=1
2973 if [ -n "$do_topbases_help" ]; then
2974 helpcmd='echo "Usage: ${tgname:-tg} [-r <remote>] --top-bases [-r]"'
2975 [ $do_topbases_help -eq 0 ] || helpcmd="$helpcmd >&2"
2976 eval "$helpcmd"
2977 exit $do_topbases_help
2979 git_dir=
2980 if git_dir="$(git rev-parse --git-dir 2>&1)"; then
2981 [ -z "$wayback" ] || activate_wayback_machine "$wayback"
2982 setup_git_dirs
2984 set_topbases
2985 if [ -n "$show_remote_topbases" ]; then
2986 basic_setup_remote
2987 [ -n "$base_remote" ] ||
2988 die "no remote location given. Either use -r <remote> option or set topgit.remote"
2989 rbases=
2990 [ -z "$topbases_implicit_default" ] ||
2991 check_remote_topbases "$base_remote" rbases "--top-bases"
2992 if [ -n "$rbases" ]; then
2993 echol "$rbases"
2994 else
2995 echol "refs/remotes/$base_remote/${topbases#heads/}"
2997 else
2998 echol "refs/$topbases"
2999 fi;;
3002 isutil=
3003 case "$cmd" in index-merge-one-file)
3004 isutil="-"
3005 esac
3006 [ -r "$TG_INST_CMDDIR/tg-$isutil$cmd" ] || {
3007 looplevel="$TG_ALIAS_DEPTH"
3008 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
3009 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
3010 looplevel=0
3011 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
3012 if [ -z "$tgalias" ]; then
3013 if [ "$cmd" = "goto" ]; then
3014 tgalias="checkout goto"
3015 else
3016 echo "Unknown command: $cmd" >&2
3017 do_help
3018 exit 1
3021 looplevel=$(( $looplevel + 1 ))
3022 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
3023 TG_ALIAS_DEPTH="$looplevel"
3024 export TG_ALIAS_DEPTH
3025 if [ "!${tgalias#?}" = "$tgalias" ]; then
3026 [ -z "$wayback" ] ||
3027 die "-w is not allowed before an '!' alias command"
3028 unset_ GIT_PREFIX
3029 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
3030 GIT_PREFIX="$pfx"
3031 export GIT_PREFIX
3033 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
3034 if [ $# -gt 0 ]; then
3035 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
3036 else
3037 exec @SHELL_PATH@ -c "${tgalias#?}" @SHELL_PATH@
3039 else
3040 eval 'exec "$tgbin"' "${wayback:+-w \"\$wayback\"}" "$tgalias" '"$@"'
3042 die "alias execution failed for: $tgalias"
3044 unset_ TG_ALIAS_DEPTH
3046 showing_help=
3047 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
3048 showing_help=1
3051 nomergesetup="$showing_help"
3052 case "$cmd" in base|contains|export|files|info|log|mail|next|patch|prev|rebase|revert|shell|summary|tag)
3053 # avoid merge setup where not necessary
3055 nomergesetup=1
3056 esac
3058 if [ -n "$wayback" ] && [ -z "$showing_help" ]; then
3059 [ -n "$nomergesetup" ] ||
3060 die "the wayback machine cannot be used with the \"$cmd\" command"
3061 if [ "$cmd" = "shell" ]; then
3062 # this is ugly; `tg shell` should handle this but it's too
3063 # late there so we have to do it here
3064 wayback_dir=
3065 case "$1" in
3066 "--directory="?*)
3067 wayback_dir="${1#--directory=}" && shift;;
3068 "--directory=")
3069 die "--directory requires an argument";;
3070 "--directory")
3071 [ $# -ge 2 ] || die "--directory requires an argument"
3072 wayback_dir="$2" && shift 2;;
3073 esac
3074 activate_wayback_machine "$wayback" 1 "$wayback_dir"
3075 else
3076 _fullwb=
3077 # export might drop out into a shell for conflict resolution
3078 [ "$cmd" != "export" ] || _fullwb=2
3079 activate_wayback_machine "$wayback" "$_fullwb"
3080 fi ||
3081 die "failed to set the wayback machine to target \"$wayback\""
3084 [ -n "$showing_help" ] || initial_setup
3085 [ -z "$noremote" ] || unset_ base_remote
3087 # Include merging support functions for commands that need them
3089 case "$cmd$showing_help" in annihilate|create|depend|update)
3090 [ -f "$TG_INST_CMDDIR/tg--merging" ] && [ -r "$TG_INST_CMDDIR/tg--merging" ] ||
3091 die "Missing merging support: '$TG_INST_CMDDIR/tg--merging'"
3092 . "$TG_INST_CMDDIR/tg--merging"
3093 esac
3095 if [ -z "$nomergesetup" ]; then
3096 # make sure merging the .top* files will always behave sanely
3098 setup_ours
3099 setup_hook "pre-commit"
3102 # everything but rebase needs topbases set
3103 carefully="$showing_help"
3104 [ "$cmd" != "migrate-bases" ] || carefully=1
3105 [ "$cmd" = "rebase" ] || set_topbases $carefully
3107 _use_ref_cache=
3108 tg_read_only=1
3109 _suppress_alt=
3110 case "$cmd$showing_help" in
3111 contains|info|summary|tag)
3112 _use_ref_cache=1;;
3113 "export")
3114 _use_ref_cache=1
3115 _suppress_alt=1;;
3116 annihilate|create|delete|depend|import|update)
3117 tg_read_only=
3118 _suppress_alt=1;;
3119 esac
3120 [ -z "$_suppress_alt" ] || noalt_setup
3121 [ -z "$_use_ref_cache" ] || v_create_ref_cache
3123 fullcmd="${tgname:-tg} $cmd $*"
3124 fullcmd="${fullcmd% }"
3125 if [ z"$forcepager" = z"1" ]; then
3126 page '. "$TG_INST_CMDDIR"/tg-$isutil$cmd' "$@"
3127 else
3128 . "$TG_INST_CMDDIR"/tg-$isutil$cmd
3129 fi;;
3130 esac