tg.sh: next version is 0.19.11
[topgit/pro.git] / tg.sh
blobd1d8b4b643f2358bab1190434ba5ad9dde5b3db7
1 #!/bin/sh
2 # TopGit - A different patch queue manager
3 # Copyright (C) 2008 Petr Baudis <pasky@suse.cz>
4 # Copyright (C) 2014-2018 Kyle J. McKay <mackyle@gmail.com>
5 # All rights reserved.
6 # GPLv2
8 TG_VERSION="0.19.11-PRE"
10 # Update in Makefile if you add any code that requires a newer version of git
11 GIT_MINIMUM_VERSION="@mingitver@"
13 ## SHA-1 pattern
15 octet='[0-9a-f][0-9a-f]'
16 octet4="$octet$octet$octet$octet"
17 octet19="$octet4$octet4$octet4$octet4$octet$octet$octet"
18 octet20="$octet4$octet4$octet4$octet4$octet4"
19 nullsha="0000000000000000000000000000000000000000" # :|git mktree|tr 0-9a-f 0
20 mtblob="e69de29bb2d1d6434b8b29ae775ad8c2e48c5391" # :|git hash-object --stdin -w
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_()
32 EXITCODE_=${1:-$?}
33 trap - EXIT
34 eval "${TRAPEXIT_:-exit $EXITCODE_}"
35 exit $EXITCODE_
37 trap 'trapexit_ $?' EXIT
39 # unset that ignores error code that shouldn't be produced according to POSIX
40 unset_()
42 { unset "$@"; } >/dev/null 2>&1 || :
45 # Preserves current $? value while triggering a non-zero set -e exit if active
46 # This works even for shells that sometimes fail to correctly trigger a -e exit
47 check_exit_code()
49 return $?
52 # This is the POSIX equivalent of which
53 cmd_path()
55 { "unset" -f command unset unalias "$1"; } >/dev/null 2>&1 || :
56 { "unalias" -a || unalias -m "*"; } >/dev/null 2>&1 || :
57 command -v "$1"
60 # helper for wrappers
61 # note deliberate use of '(' ... ')' rather than '{' ... '}'
62 exec_lc_all_c()
64 { "unset" -f "$1" || :; } >/dev/null 2>&1 &&
65 shift &&
66 LC_ALL="C" &&
67 export LC_ALL &&
68 exec "$@"
71 # These tools work better for us with LC_ALL=C and by using these little
72 # convenience functions LC_ALL=C does not have to appear in the code but
73 # any Git translations will still appear for Git commands
74 awk() { exec_lc_all_c awk @AWK_PATH@ "$@"; }
75 cat() { exec_lc_all_c cat cat "$@"; }
76 cmp() { exec_lc_all_c cmp cmp "$@"; }
77 cut() { exec_lc_all_c cut cut "$@"; }
78 find() { exec_lc_all_c find find "$@"; }
79 grep() { exec_lc_all_c grep grep "$@"; }
80 join() { exec_lc_all_c join join "$@"; }
81 paste() { exec_lc_all_c paste paste "$@"; }
82 sed() { exec_lc_all_c sed sed "$@"; }
83 sort() { exec_lc_all_c sort sort "$@"; }
84 tr() { exec_lc_all_c tr tr "$@"; }
85 wc() { exec_lc_all_c wc wc "$@"; }
86 xargs() { exec_lc_all_c xargs xargs "$@"; }
88 # Output arguments without any possible interpretation
89 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
90 echol()
92 printf '%s\n' "$*"
95 info()
97 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
100 warn()
102 info "warning: $*" >&2
105 err()
107 info "error: $*" >&2
110 fatal()
112 info "fatal: $*" >&2
115 die()
117 fatal "$@"
118 exit 1
121 # shift off first arg then return "$*" properly quoted in single-quotes
122 # if $1 was '' output goes to stdout otherwise it's assigned to $1
123 # the final \n, if any, is omitted from the result but any others are included
124 v_quotearg()
126 _quotearg_v="$1"
127 shift
128 set -- "$_quotearg_v" \
129 "sed \"s/'/'\\\\\\''/g;1s/^/'/;\\\$s/\\\$/'/;s/'''/'/g;1s/^''\\(.\\)/\\1/\"" "$*"
130 unset_ _quotearg_v
131 if [ -z "$3" ]; then
132 if [ -z "$1" ]; then
133 echo "''"
134 else
135 eval "$1=\"''\""
137 else
138 if [ -z "$1" ]; then
139 printf "%s$4" "$3" | eval "$2"
140 else
141 eval "$1="'"$(printf "%s$4" "$3" | eval "$2")"'
146 # same as v_quotearg except there's no extra $1 so output always goes to stdout
147 quotearg()
149 v_quotearg '' "$@"
152 vcmp()
154 # Compare $1 to $3 each of which must match ^[^0-9]*\d*(\.\d*)*.*$
155 # where only the "\d*" parts in the regex participate in the comparison
156 # Since EVERY string matches that regex this function is easy to use
157 # An empty string ('') for $1 or $3 or any "\d*" part is treated as 0
158 # $2 is a compare op '<', '<=', '=', '==', '!=', '>=', '>'
159 # Return code is 0 for true, 1 for false (or unknown compare op)
160 # There is NO difference in behavior between '=' and '=='
161 # Note that "vcmp 1.8 == 1.8.0.0.0.0" correctly returns 0
162 set -- "$1" "$2" "$3" "${1%%[0-9]*}" "${3%%[0-9]*}"
163 set -- "${1#"$4"}" "$2" "${3#"$5"}"
164 set -- "${1%%[!0-9.]*}" "$2" "${3%%[!0-9.]*}"
165 while
166 vcmp_a_="${1%%.*}"
167 vcmp_b_="${3%%.*}"
168 [ "z$vcmp_a_" != "z" ] || [ "z$vcmp_b_" != "z" ]
170 if [ "${vcmp_a_:-0}" -lt "${vcmp_b_:-0}" ]; then
171 unset_ vcmp_a_ vcmp_b_
172 case "$2" in "<"|"<="|"!=") return 0; esac
173 return 1
174 elif [ "${vcmp_a_:-0}" -gt "${vcmp_b_:-0}" ]; then
175 unset_ vcmp_a_ vcmp_b_
176 case "$2" in ">"|">="|"!=") return 0; esac
177 return 1;
179 vcmp_a_="${1#$vcmp_a_}"
180 vcmp_b_="${3#$vcmp_b_}"
181 set -- "${vcmp_a_#.}" "$2" "${vcmp_b_#.}"
182 done
183 unset_ vcmp_a_ vcmp_b_
184 case "$2" in "="|"=="|"<="|">=") return 0; esac
185 return 1
188 # true if "$1" is an existing dir and is empty except for
189 # any additional files given as extra arguments. If "$2"
190 # is the single character "." then all ".*" files will be
191 # ignored for the test (plus any further args, if any)
192 is_empty_dir() {
193 test -n "$1" && test -d "$1" || return 1
194 iedd_="$1"
195 shift
196 ieddnok_='\.?$'
197 if [ z"$1" = z"." ]; then
198 ieddnok_=
199 shift
200 while ! case "$1" in "."*) ! :; esac; do shift; done
202 if [ $# -eq 0 ]; then
203 ! \ls -a1 "$iedd_" | grep -q -E -v '^\.'"$ieddnok_"
204 else
205 # we only handle ".git" right now for efficiency
206 [ z"$*" = z".git" ] || {
207 fatal "[BUG] is_empty_dir not implemented for arguments: $*"
208 exit 70
210 ! \ls -a1 "$iedd_" | grep -q -E -v -i -e '^\.\.?$' -e '^\.git$'
214 precheck() {
215 if ! git_version="$(git version)"; then
216 die "'git version' failed"
218 case "$git_version" in [Gg]"it version "*);;*)
219 die "'git version' output does not start with 'git version '"
220 esac
222 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
223 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
226 case "$1" in version|--version|-V)
227 echo "TopGit version $TG_VERSION"
228 exit 0
229 esac
231 [ $# -eq 1 ] && [ "$1" = "--make-empty-blob" ] || precheck
232 [ $# -ne 1 ] || [ "$1" != "precheck" ] || exit 0
234 cat_depsmsg_internal()
236 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
237 if [ -s "$tg_cache_dir/refs/heads/$1/.$2" ]; then
238 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
239 _line=
240 while IFS= read -r _line || [ -n "$_line" ]; do
241 printf '%s\n' "$_line"
242 done
243 return 0
244 fi <"$tg_cache_dir/refs/heads/$1/.$2"
246 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null || :
247 if [ -d "$tg_cache_dir/refs/heads/$1" ]; then
248 printf '%s\n' "$_rev" >"$tg_cache_dir/refs/heads/$1/.$2"
249 _line=
250 git cat-file blob "$_rev:.$2" 2>/dev/null |
251 while IFS= read -r _line || [ -n "$_line" ]; do
252 printf '%s\n' "$_line" >&3
253 printf '%s\n' "$_line"
254 done 3>>"$tg_cache_dir/refs/heads/$1/.$2"
255 else
256 git cat-file blob "$_rev:.$2" 2>/dev/null
260 # cat_deps BRANCHNAME
261 # Caches result
262 cat_deps()
264 cat_depsmsg_internal "$1" topdeps
267 # cat_msg BRANCHNAME
268 # Caches result
269 cat_msg()
271 cat_depsmsg_internal "$1" topmsg
274 # cat_file TOPIC:PATH [FROM]
275 # cat the file PATH from branch TOPIC when FROM is empty.
276 # FROM can be -i or -w, than the file will be from the index or worktree,
277 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
278 cat_file()
280 path="$1"
281 case "$2" in
283 cat "$root_dir/${path#*:}"
286 # ':file' means cat from index
287 git cat-file blob ":${path#*:}" 2>/dev/null
290 case "$path" in
291 refs/heads/*:.topdeps)
292 _temp="${path%:.topdeps}"
293 cat_deps "${_temp#refs/heads/}"
295 refs/heads/*:.topmsg)
296 _temp="${path%:.topmsg}"
297 cat_msg "${_temp#refs/heads/}"
300 git cat-file blob "$path" 2>/dev/null
302 esac
305 die "Wrong argument to cat_file: '$2'"
307 esac
310 # if use_alt_temp_odb and tg_use_alt_odb are true try to write the object(s)
311 # into the temporary alt odb area instead of the usual location
312 git_temp_alt_odb_cmd()
314 if [ -n "$use_alt_temp_odb" ] && [ -n "$tg_use_alt_odb" ] &&
315 [ -n "$TG_OBJECT_DIRECTORY" ] &&
316 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
318 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
319 GIT_OBJECT_DIRECTORY="$TG_OBJECT_DIRECTORY"
320 unset_ TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES
321 export GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
322 git "$@"
324 else
325 git "$@"
329 git_write_tree() { git_temp_alt_odb_cmd write-tree "$@"; }
330 git_mktree() { git_temp_alt_odb_cmd mktree "$@"; }
332 make_mtblob() {
333 use_alt_temp_odb=1
334 tg_use_alt_odb=1
335 git_temp_alt_odb_cmd hash-object -t blob -w --stdin </dev/null >/dev/null 2>&1
337 # short-circuit this for speed
338 [ $# -eq 1 ] && [ "$1" = "--make-empty-blob" ] && { make_mtblob || :; exit 0; }
340 # get tree for the committed topic
341 get_tree_()
343 echo "refs/heads/$1"
346 # get tree for the base
347 get_tree_b()
349 echo "refs/$topbases/$1"
352 # get tree for the index
353 get_tree_i()
355 git_write_tree
358 # get tree for the worktree
359 get_tree_w()
361 i_tree=$(git_write_tree)
363 # the file for --index-output needs to sit next to the
364 # current index file
365 cd "$root_dir"
366 : ${GIT_INDEX_FILE:="$git_dir/index"}
367 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
368 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
369 GIT_INDEX_FILE="$TMP_INDEX" &&
370 export GIT_INDEX_FILE &&
371 git diff --name-only -z HEAD |
372 git update-index -z --add --remove --stdin &&
373 git_write_tree &&
374 rm -f "$TMP_INDEX"
378 # get tree for arbitrary ref
379 get_tree_r()
381 echo "$1"
384 # strip_ref "$(git symbolic-ref HEAD)"
385 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
386 strip_ref()
388 case "$1" in
389 refs/"$topbases"/*)
390 echol "${1#refs/$topbases/}"
392 refs/heads/*)
393 echol "${1#refs/heads/}"
396 echol "$1"
397 esac
400 # pretty_tree [-t] NAME [-b | -i | -w | -r]
401 # Output tree ID of a cleaned-up tree without tg's artifacts.
402 # NAME will be ignored for -i and -w, but needs to be present
403 # With -r NAME must be a full ref name to a treeish (it's used as-is)
404 # If -t is used the tree is written into the alternate temporary objects area
405 pretty_tree()
407 use_alt_temp_odb=
408 [ "$1" != "-t" ] || { shift; use_alt_temp_odb=1; }
409 name="$1"
410 source="${2#?}"
411 git ls-tree --full-tree "$(get_tree_$source "$name")" |
412 sed -ne '/ \.top.*$/!p' |
413 git_mktree
416 # return an empty-tree root commit -- date is either passed in or current
417 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
418 # An invalid secs causes the current date to be used, an invalid zone offset
419 # causes +0000 to be used
420 make_empty_commit()
422 # the empty tree is guaranteed to always be there even in a repo with
423 # zero objects, but for completeness we force it to exist as a real object
424 SECS=
425 read -r SECS ZONE JUNK <<-EOT || :
428 case "$SECS" in *[!0-9]*) SECS=; esac
429 if [ -z "$SECS" ]; then
430 MTDATE="$(date '+%s %z')"
431 else
432 case "$ZONE" in
433 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
435 [01][0-9][0-5][0-9])
436 ZONE="+$ZONE"
439 ZONE="+0000"
440 esac
441 MTDATE="$SECS $ZONE"
443 EMPTYID="- <-> $MTDATE"
444 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
445 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
446 git hash-object -t commit -w --stdin
449 # standard input is a diff
450 # standard output is the "+" lines with leading "+ " removed
451 # beware that old lines followed by the dreaded '\ No newline at end of file'
452 # will appear to be new lines if lines are added after them
453 # the git diff --ignore-space-at-eol option can be used to prevent this
454 diff_added_lines()
456 awk '
457 BEGIN { in_hunk = 0; }
458 /^@@ / { in_hunk = 1; }
459 /^\+/ { if (in_hunk == 1) printf("%s\n", substr($0, 2)); }
460 !/^\\ No newline at end of file/ &&
461 /^[^@ +-]/ { in_hunk = 0; }
465 # $1 is name of new branch to create locally if all of these are true:
466 # a) exists as a remote TopGit branch for "$base_remote"
467 # b) the branch "name" does not have any invalid characters in it
468 # c) neither of the two branch refs (branch or base) exist locally
469 # returns success only if a new local branch was created (and dumps message)
470 auto_create_local_remote()
472 case "$1" in ""|*[" $tab$lf~^:\\*?["]*|.*|*/.*|*.|*./|/*|*/|*//*) return 1; esac
473 [ -n "$base_remote" ] &&
474 git update-ref --stdin <<-EOT >/dev/null 2>&1 &&
475 verify refs/remotes/$base_remote/${topbases#heads/}/$1 refs/remotes/$base_remote/${topbases#heads/}/$1
476 verify refs/remotes/$base_remote/$1 refs/remotes/$base_remote/$1
477 create refs/$topbases/$1 refs/remotes/$base_remote/${topbases#heads/}/$1^0
478 create refs/heads/$1 refs/remotes/$base_remote/$1^0
480 { init_reflog "refs/$topbases/$1" || :; } &&
481 info "topic branch '$1' automatically set up from remote '$base_remote'"
484 is_writable_hook()
486 if [ -n "$1" ] && [ -e "$1" ] && [ ! -L "$1" ] && [ -f "$1" ] && [ -r "$1" ] && [ -w "$1" ] && [ -x "$1" ]; then
487 hook_links="$(ls -ld "$1" 2>/dev/null | awk '{print $2}')" || :
488 [ "$hook_links" != "1" ] || return 0
490 return 1
493 # setup_hook NAME
494 setup_hook()
496 setup_git_dir_is_bare
497 [ -z "$git_dir_is_bare" ] || return 0
498 setup_git_hooks_dir
499 tgname="${0##*/}"
500 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
501 if [ -f "$git_hooks_dir/$1" ] && grep -Fq "$hook_call" "$git_hooks_dir/$1"; then
502 # Another job well done!
503 return
505 # Prepare incantation
506 hook_chain=
507 if [ -e "$git_hooks_dir/$1" ] || [ -L "$git_hooks_dir/$1" ]; then
508 hook_call="$hook_call"' || exit $?'
510 ! is_writable_hook "$git_hooks_dir/$1" ||
511 ! sed -n 1p <"$git_hooks_dir/$1" | grep -Fqx "#!@SHELL_PATH@"
512 then
513 chain_num=
514 while [ -e "$git_hooks_dir/$1-chain$chain_num" ] || [ -L "$git_hooks_dir/$1-chain$chain_num" ]; do
515 chain_num=$(( $chain_num + 1 ))
516 done
517 mv -f "$git_hooks_dir/$1" "$git_hooks_dir/$1-chain$chain_num"
518 hook_chain=1
520 else
521 hook_call="exec $hook_call"
522 [ -d "$git_hooks_dir" ] || mkdir -p "$git_hooks_dir" || :
524 # Don't call hook if tg is not installed
525 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
526 # Insert call into the hook
528 echol "#!@SHELL_PATH@"
529 echol "$hook_call"
530 if [ -n "$hook_chain" ]; then
531 echol "test -f \"\$0-chain$chain_num\" &&"
532 echol "test -x \"\$0-chain$chain_num\" &&"
533 echol "exec \"\$0-chain$chain_num\" \"\$@\" || :"
534 else
535 [ ! -s "$git_hooks_dir/$1" ] || cat "$git_hooks_dir/$1"
537 } >"$git_hooks_dir/$1+"
538 chmod a+x "$git_hooks_dir/$1+"
539 mv "$git_hooks_dir/$1+" "$git_hooks_dir/$1"
542 # setup_ours (no arguments)
543 setup_ours()
545 setup_git_dir_is_bare
546 [ -z "$git_dir_is_bare" ] || return 0
547 if [ ! -s "$git_common_dir/info/attributes" ] || ! grep -q topmsg "$git_common_dir/info/attributes"; then
548 [ -d "$git_common_dir/info" ] || mkdir "$git_common_dir/info"
550 echo ".topmsg merge=ours"
551 echo ".topdeps merge=ours"
552 } >>"$git_common_dir/info/attributes"
554 if ! git config merge.ours.driver >/dev/null; then
555 git config merge.ours.name '"always keep ours" merge driver'
556 git config merge.ours.driver 'touch %A'
560 # measure_branch NAME [BASE] [EXTRAHEAD...]
561 measure_branch()
563 _bname="$1"; _base="$2"
564 shift; shift
565 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
566 # The caller should've verified $name is valid
567 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
568 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
569 if [ $_commits -ne 1 ]; then
570 _suffix="commits"
571 else
572 _suffix="commit"
574 echo "$_commits/$_nmcommits $_suffix"
577 # true if $1 is contained by (or the same as) $2
578 # this is never slower than merge-base --is-ancestor and is often slightly faster
579 contained_by()
581 [ "$(git rev-list --count --max-count=1 "$1" --not "$2" --)" = "0" ]
584 # branch_contains B1 B2
585 # Whether B1 is a superset of B2.
586 branch_contains()
588 _revb1="$(ref_exists_rev "$1")" || return 0
589 _revb2="$(ref_exists_rev "$2")" || return 0
590 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
591 if read _result _rev_matchb1 _rev_matchb2 &&
592 [ "$_revb1" = "$_rev_matchb1" ] && [ "$_revb2" = "$_rev_matchb2" ]; then
593 return $_result
594 fi <"$tg_cache_dir/$1/.bc/$2/.d"
596 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
597 _result=0
598 contained_by "$_revb2" "$_revb1" || _result=1
599 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
600 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
602 return $_result
605 create_ref_dirs()
607 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" ] && [ -s "$tg_ref_cache" ] || return 0
608 mkdir -p "$tg_tmp_dir/cached/refs"
609 awk '{x=$1; sub(/^refs\//,"",x); if (x != "") {gsub(/[^A-Za-z0-9\/_.+-]/,"\\\\&",x); print x;}}' <"$tg_ref_cache" |
611 cd "$tg_tmp_dir/cached/refs" &&
612 xargs mkdir -p
614 awk -v p="$tg_tmp_dir/cached/" '
615 NF == 2 &&
616 $1 ~ /^refs\/./ &&
617 $2 ~ /^[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]+$/ {
618 fn = p $1 "/.ref"
619 print "0 " $2 >fn
620 close(fn)
622 ' <"$tg_ref_cache"
623 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
626 # If the first argument is non-empty, stores "1" there if this call created the cache
627 v_create_ref_cache()
629 [ -n "$tg_ref_cache" ] && ! [ -s "$tg_ref_cache" ] || return 0
630 _remotespec=
631 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
632 [ -z "$1" ] || eval "$1=1"
633 git for-each-ref --format='%(refname) %(objectname)' \
634 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
635 create_ref_dirs
638 remove_ref_cache()
640 [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ] || return 0
641 >"$tg_ref_cache"
642 >"$tg_ref_cache_br"
643 >"$tg_ref_cache_rbr"
644 >"$tg_ref_cache_ann"
645 >"$tg_ref_cache_dep"
648 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
649 rev_parse()
651 rev_parse_code_=1
652 if [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
653 rev_parse_code_=0
654 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache" ||
655 rev_parse_code_=$?
657 [ $rev_parse_code_ -ne 0 ] && [ -z "$tg_ref_cache_only" ] || return $rev_parse_code_
658 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
661 # ref_exists_rev REF
662 # Whether REF is a valid ref name
663 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
664 # or, if $base_remote is set, refs/remotes/$base_remote/
665 # Caches result if $tg_read_only and outputs HASH on success
666 ref_exists_rev()
668 case "$1" in
669 refs/*)
671 $octet20)
672 printf '%s' "$1"
673 return;;
675 die "ref_exists_rev requires fully-qualified ref name (given: $1)"
676 esac
677 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
678 _result=
679 _result_rev=
680 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
681 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
682 _result=0
683 _result_rev="$(rev_parse "$1")" || _result=$?
684 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
685 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
686 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
687 printf '%s' "$_result_rev"
688 return $_result
691 # Same as ref_exists_rev but output is abbreviated hash
692 # Optional second argument defaults to --short but may be any --short=.../--no-short option
693 ref_exists_rev_short()
695 case "$1" in
696 refs/*)
698 $octet20)
701 die "ref_exists_rev_short requires fully-qualified ref name"
702 esac
703 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
704 _result=
705 _result_rev=
706 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
707 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
708 _result=0
709 _result_rev="$(rev_parse "$1")" || _result=$?
710 if [ $_result -eq 0 ]; then
711 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev^0" --)"
712 _result=$?
714 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
715 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
716 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
717 printf '%s' "$_result_rev"
718 return $_result
721 # ref_exists REF
722 # Whether REF is a valid ref name
723 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
724 # or, if $base_remote is set, refs/remotes/$base_remote/
725 # Caches result
726 ref_exists()
728 ref_exists_rev "$1" >/dev/null
731 # rev_parse_tree REF
732 # Runs git rev-parse REF^{tree}
733 # Caches result if $tg_read_only
734 rev_parse_tree()
736 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
737 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
738 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
739 printf '%s\n' "$_result"
740 return 0
742 return 1
744 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
745 if [ -d "$tg_tmp_dir/cached/$1" ]; then
746 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
747 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
748 printf '%s\n' "$_result"
749 return 0
751 return 1
753 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
756 # has_remote BRANCH
757 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
758 has_remote()
760 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
763 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
764 # If -z "$1" still set return code but do not return result
765 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
766 # refs/heads/... then ... will be verified instead.
767 # if "$3" = "-f" (for fail) then return an error rather than dying.
768 v_verify_topgit_branch()
770 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
771 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
772 [ -n "$_verifyname" ] || [ "$3" = "-f" ] || die "HEAD is not a symbolic ref"
773 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
774 [ "$3" != "-f" ] || return 1
775 die "HEAD is not a symbolic ref to the refs/heads namespace"
776 esac
777 set -- "$1" "$_verifyname" "$3"
779 case "$2" in
780 refs/"$topbases"/*)
781 _verifyname="${2#refs/$topbases/}"
783 refs/heads/*)
784 _verifyname="${2#refs/heads/}"
787 _verifyname="$2"
789 esac
790 if ! ref_exists "refs/heads/$_verifyname"; then
791 [ "$3" != "-f" ] || return 1
792 die "no such branch: $_verifyname"
794 if ! ref_exists "refs/$topbases/$_verifyname"; then
795 [ "$3" != "-f" ] || return 1
796 die "not a TopGit-controlled branch: $_verifyname"
798 [ -z "$1" ] || eval "$1="'"$_verifyname"'
801 # Return the verified TopGit branch name or die with an error.
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 "$2" = "-f" (for fail) then return an error rather than dying.
805 verify_topgit_branch()
807 v_verify_topgit_branch _verifyname "$@" || return
808 printf '%s' "$_verifyname"
811 # Caches result
812 # $1 = branch name (i.e. "t/foo/bar")
813 # $2 = optional result of rev-parse "refs/heads/$1"
814 # $3 = optional result of rev-parse "refs/$topbases/$1"
815 branch_annihilated()
817 _branch_name="$1"
818 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
819 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
821 _result=
822 _result_rev=
823 _result_rev_base=
824 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/refs/heads/$_branch_name/.ann"; } 2>/dev/null || :
825 [ -z "$_result" ] || [ "$_result_rev" != "$_rev" ] || [ "$_result_rev_base" != "$_rev_base" ] || return $_result
827 # use the merge base in case the base is ahead.
828 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
830 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
831 _result=$?
832 [ -d "$tg_cache_dir/refs/heads/$_branch_name" ] || mkdir -p "$tg_cache_dir/refs/heads/$_branch_name" 2>/dev/null
833 [ ! -d "$tg_cache_dir/refs/heads/$_branch_name" ] ||
834 echo $_result $_rev $_rev_base >"$tg_cache_dir/refs/heads/$_branch_name/.ann" 2>/dev/null || :
835 return $_result
838 non_annihilated_branches()
840 refscacheopt="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
841 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
842 refscacheopt="$refscacheopt"'-r="$tg_ref_cache" "refs/$topbases"'
844 eval run_awk_topgit_branches -n "$refscacheopt" '"refs/$topbases" "$@"'
847 # Make sure our tree is clean
848 # if optional "$1" given also verify that a checkout to "$1" would succeed
849 ensure_clean_tree()
851 check_status
852 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
853 git update-index --ignore-submodules --refresh ||
854 die "the working directory has uncommitted changes (see above) - first commit or reset them"
855 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
856 die "the index has uncommited changes"
857 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
858 die "git checkout \"$1\" would fail"
861 # Make sure .topdeps and .topmsg are "clean"
862 # They are considered "clean" if each is identical in worktree, index and HEAD
863 # With "-u" as the argument skip the HEAD check (-u => unborn)
864 # untracked .topdeps and/or .topmsg files are always considered "dirty" as well
865 # with -u them just existing constitutes "dirty"
866 ensure_clean_topfiles()
868 _dirtw=0
869 _dirti=0
870 _dirtu=0
871 _check="$(git diff-files --ignore-submodules --name-only -- :/.topdeps :/.topmsg)" &&
872 [ -z "$_check" ] || _dirtw=1
873 if [ "$1" != "-u" ]; then
874 _check="$(git diff-index --cached --ignore-submodules --name-only HEAD -- :/.topdeps :/.topmsg)" &&
875 [ -z "$_check" ] || _dirti=1
877 if [ "$_dirti$_dirtw" = "00" ]; then
878 v_get_show_cdup
879 if [ -e "${git_cdup_result}.topdeps" ] || [ -e "${git_cdup_result}.topmsg" ]; then
880 [ "$1" != "-u" ] &&
881 _check="$(git status --porcelain --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg)" &&
882 [ -z "$_check" ] || _dirtu=1
885 if [ "$_dirtu$_dirti$_dirtw" != "000" ]; then
886 git status --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg || :
887 case "$_dirtu$_dirti$_dirtw" in
888 001) die "the working directory has uncommitted changes (see above) - first commit or reset them";;
889 010) die "the index has uncommited changes (see above)";;
890 011) die "the working directory and index have uncommitted changes (see above) - first commit or reset them";;
891 100) die "the working directory has untracked files that would be overwritten (see above)";;
892 esac
896 # is_sha1 REF
897 # Whether REF is a SHA1 (compared to a symbolic name).
898 is_sha1()
900 case "$1" in $octet20) return 0;; esac
901 return 1
904 # navigate_deps <run_awk_topgit_navigate options and arguments>
905 # all options and arguments are passed through to run_awk_topgit_navigate
906 # except for a leading -td= option, if any, which is picked off for deps
907 # after arranging to feed it a suitable deps list
908 navigate_deps()
910 dogfer=
911 dorad=1
912 userc=
913 tmpdep=
914 ratd_opts="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
915 ratn_opts=
916 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
917 userc=1
918 tmprfs="$tg_ref_cache"
919 tmptgbr="$tg_ref_cache_br"
920 tmpann="$tg_ref_cache_ann"
921 tmpdep="$tg_ref_cache_dep"
922 [ -s "$tg_ref_cache" ] || dogfer=1
923 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
924 else
925 ratd_opts="${ratd_opts}-rmr"
926 ratn_opts="-rma -rmb"
927 tmprfs="$tg_tmp_dir/refs.$$"
928 tmpann="$tg_tmp_dir/ann.$$"
929 tmptgbr="$tg_tmp_dir/tgbr.$$"
930 dogfer=1
932 refpats="\"refs/heads\" \"refs/\$topbases\""
933 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
934 [ -z "$dogfer" ] ||
935 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
936 depscmd="run_awk_topgit_deps $ratd_opts"
937 case "$1" in -td=*)
938 userc=
939 depscmd="$depscmd $1"
940 shift
941 esac
942 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -s "refs/$topbases"'
943 if [ -n "$userc" ]; then
944 if [ -n "$dorad" ]; then
945 eval "$depscmd" >"$tmpdep"
947 depscmd='<"$tmpdep" '
948 else
949 depscmd="$depscmd |"
951 eval "$depscmd" run_awk_topgit_navigate '-a="$tmpann" -b="$tmptgbr"' "$ratn_opts" '"$@"'
954 # recurse_deps_internal NAME [BRANCHPATH...]
955 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
956 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
957 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
958 # (but missing and remotes are always "0")
959 # followed by a 0 for no excess visits or a positive number of excess visits
960 # then the branch name followed by its depedency chain (which might be empty)
961 # An output line might look like this:
962 # 0 1 1 0 t/foo/leaf t/foo/int t/stage
963 # If no_remotes is non-empty, exclude remotes
964 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
965 # If with_top_level is non-empty, include the top-level that's normally omitted
966 # any branch names in the space-separated recurse_deps_exclude variable
967 # are skipped (along with their dependencies)
968 recurse_deps_internal()
970 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
971 ratr_opts="${recurse_preorder:+-f} ${with_top_level:+-s}"
972 dogfer=
973 dorad=1
974 userc=
975 tmpdep=
976 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
977 userc=1
978 tmprfs="$tg_ref_cache"
979 tmptgbr="$tg_ref_cache_br"
980 tmpann="$tg_ref_cache_ann"
981 tmpdep="$tg_ref_cache_dep"
982 [ -s "$tg_ref_cache" ] || dogfer=1
983 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
984 else
985 ratr_opts="$ratr_opts -rmh -rma -rmb"
986 tmprfs="$tg_tmp_dir/refs.$$"
987 tmpann="$tg_tmp_dir/ann.$$"
988 tmptgbr="$tg_tmp_dir/tgbr.$$"
989 dogfer=1
991 refpats="\"refs/heads\" \"refs/\$topbases\""
992 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
993 tmptgrmtbr=
994 dorab=1
995 if [ -z "$no_remotes" ] && [ -n "$base_remote" ]; then
996 if [ -n "$userc" ]; then
997 tmptgrmtbr="$tg_ref_cache_rbr"
998 [ -n "$dogfer" ] || ! [ -s "$tmptgrmtbr" ] || dorab=
999 else
1000 tmptgrmtbr="$tg_tmp_dir/tgrmtbr.$$"
1001 ratr_opts="$ratr_opts -rmr"
1003 ratr_opts="$ratr_opts -r=\"\$tmptgrmtbr\" -u=\":refs/remotes/\$base_remote/\${topbases#heads/}\""
1005 [ -z "$dogfer" ] ||
1006 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
1007 if [ -n "$tmptgrmtbr" ] && [ -n "$dorab" ]; then
1008 run_awk_topgit_branches -n -h="refs/remotes/$base_remote" -r="$tmprfs" \
1009 "refs/remotes/$base_remote/${topbases#heads/}" >"$tmptgrmtbr"
1011 depscmd="run_awk_topgit_deps -s${TG_DEBUG:+ -p=\"\$tg_ref_cache.pre\"}"
1012 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" "refs/$topbases"'
1013 if [ -n "$userc" ]; then
1014 if [ -n "$dorad" ]; then
1015 eval "$depscmd" >"$tmpdep"
1017 depscmd='<"$tmpdep" '
1018 else
1019 depscmd="$depscmd |"
1021 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
1022 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
1025 # do_eval CMD
1026 # helper for recurse_deps so that a return statement executed inside CMD
1027 # does not return from recurse_deps. This shouldn't be necessary, but it
1028 # seems that it actually is.
1029 do_eval()
1031 eval "$@"
1034 # becomes read-only for caching purposes
1035 # assigns new value to tg_read_only
1036 # become_cacheable/undo_become_cacheable calls may be nested
1037 become_cacheable()
1039 _old_tg_read_only="$tg_read_only"
1040 if [ -z "$tg_read_only" ]; then
1041 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1042 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1043 tg_read_only=1
1045 _my_ref_cache=
1046 v_create_ref_cache _my_ref_cache
1047 _my_ref_cache="${_my_ref_cache:+1}"
1048 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
1051 # restores tg_read_only and ref_cache to state before become_cacheable call
1052 # become_cacheable/undo_bocome_cacheable calls may be nested
1053 undo_become_cacheable()
1055 case "$tg_read_only" in
1056 "undo"[01]"-"*)
1057 _suffix="${tg_read_only#undo?-}"
1058 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
1059 tg_read_only="$_suffix"
1060 esac
1063 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
1064 become_non_cacheable()
1066 remove_ref_cache
1067 tg_read_only=
1068 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1069 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1072 # call this to make sure the current Git repository has an associated work tree
1073 # also make sure we are not in wayback mode
1074 ensure_work_tree()
1076 [ -z "$wayback" ] ||
1077 die "the wayback machine cannot be used with the specified options"
1078 setup_git_dir_is_bare
1079 [ -n "$git_dir_is_bare" ] || return 0
1080 die "This operation must be run in a work tree"
1083 # call this to make sure Git will not complain about a missing user/email
1084 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
1085 ensure_ident_available()
1087 [ -z "$TG_IDENT_CHECKED" ] || return 0
1088 git var GIT_AUTHOR_IDENT >/dev/null &&
1089 git var GIT_COMMITTER_IDENT >/dev/null || exit
1090 TG_IDENT_CHECKED=1
1091 export TG_IDENT_CHECKED
1092 return 0
1095 # recurse_deps [-o=<options string>] CMD NAME [BRANCHPATH...]
1096 # Recursively eval CMD on all dependencies of NAME.
1097 # Dependencies are visited in topological order.
1098 # If <options string> is given, it's eval'd into the recurse_deps_internal
1099 # call just before the "--" that's passed just before NAME
1100 # CMD can refer to the following variables:
1102 # _ret starts as 0; CMD can change; will be final return result
1103 # _dep bare branch name or ":refs/remotes/..." for a remote
1104 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
1105 # _depchain 0+ space-sep branch names (_name first) form a path to top
1106 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
1107 # _dep_is_leaf boolean "1" if leaf; "" if not
1108 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
1109 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
1110 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
1111 # _dep_xvisits non-negative integer number of excess visits (often 0)
1113 # CMD may use a "return" statement without issue; its return value is ignored,
1114 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
1115 # will stop immediately and the value with the leading "-" stripped off will
1116 # be the final result code
1118 # CMD can refer to $_name for queried branch name,
1119 # $_dep for dependency name,
1120 # $_depchain for space-seperated branch backtrace,
1121 # $_dep_missing boolean to check whether $_dep is present
1122 # and the $_dep_is_tgish and $_dep_annihilated booleans.
1123 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
1124 # It can modify $_ret to affect the return value
1125 # of the whole function.
1126 # If recurse_deps() hits missing dependencies, it will append
1127 # them to space-separated $missing_deps list and skip them
1128 # after calling CMD with _dep_missing set.
1129 # remote dependencies are processed if no_remotes is unset.
1130 # any branch names in the space-separated recurse_deps_exclude variable
1131 # are skipped (along with their dependencies)
1133 # If no_remotes is non-empty, exclude remotes
1134 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1135 # If with_top_level is non-empty, include the top-level that's normally omitted
1136 # any branch names in the space-separated recurse_deps_exclude variable
1137 # are skipped (along with their dependencies)
1138 recurse_deps()
1140 _opts=
1141 case "$1" in -o=*) _opts="${1#-o=}"; shift; esac
1142 _cmd="$1"; shift
1144 _depsfile="$(get_temp tg-depsfile)"
1145 eval recurse_deps_internal "$_opts" -- '"$@"' >"$_depsfile" || :
1147 _ret=0
1148 while read _ismissing _istgish _isleaf _dep_xvisits _dep _name _deppath; do
1149 _depchain="$_name${_deppath:+ $_deppath}"
1150 _dep_is_tgish=
1151 [ "$_istgish" = "0" ] || _dep_is_tgish=1
1152 _dep_has_remote=
1153 [ "$_istgish" != "2" ] || _dep_has_remote=1
1154 _dep_missing=
1155 if [ "$_ismissing" != "0" ]; then
1156 _dep_missing=1
1157 case " $missing_deps " in *" $_dep "*);;*)
1158 missing_deps="${missing_deps:+$missing_deps }$_dep"
1159 esac
1161 _dep_annihilated=
1162 _dep_is_leaf=
1163 if [ "$_isleaf" = "1" ]; then
1164 _dep_is_leaf=1
1165 elif [ "$_isleaf" = "2" ]; then
1166 _dep_annihilated=1
1168 do_eval "$_cmd" || :
1169 if [ "${_ret#-}" != "$_ret" ]; then
1170 _ret="${_ret#-}"
1171 break
1173 done <"$_depsfile"
1174 rm -f "$_depsfile"
1175 return ${_ret:-0}
1178 # find_leaves NAME
1179 # output (one per line) the unique leaves of NAME
1180 # a leaf is either
1181 # 1) a non-tgish dependency
1182 # 2) the base of a tgish dependency with no non-annihilated dependencies
1183 # duplicates are suppressed (by commit rev) and remotes are always ignored
1184 # if a leaf has an exact tag match that will be output
1185 # note that recurse_deps_exclude IS honored for this operation
1186 find_leaves()
1188 no_remotes=1
1189 with_top_level=1
1190 recurse_preorder=
1191 seen_leaf_refs=
1192 seen_leaf_revs=
1193 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1194 [ "$_isleaf" = "1" ] && [ "$_ismissing" = "0" ] || continue
1195 if [ "$_istgish" != "0" ]; then
1196 fulldep="refs/$topbases/$_dep"
1197 else
1198 fulldep="refs/heads/$_dep"
1200 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1201 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1202 if fullrev="$(ref_exists_rev "$fulldep")"; then
1203 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1204 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1205 # See if Git knows it by another name
1206 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1207 echo "refs/tags/$tagname"
1208 else
1209 echo "$fulldep"
1211 esac
1213 esac
1214 done <<-EOT
1215 $(recurse_deps_internal -l -o=1 -- "$1")
1217 with_top_level=
1220 # branch_needs_update
1221 # This is a helper function for determining whether given branch
1222 # is up-to-date wrt. its dependencies. It expects input as if it
1223 # is called as a recurse_deps() helper.
1224 # In case the branch does need update, it will echo it together
1225 # with the branch backtrace on the output (see needs_update()
1226 # description for details) and set $_ret to non-zero.
1227 branch_needs_update()
1229 if [ -n "$_dep_missing" ]; then
1230 echo "! $_dep $_depchain"
1231 return 0
1234 if [ -n "$_dep_is_tgish" ]; then
1235 [ -z "$_dep_annihilated" ] || return 0
1237 if [ -n "$_dep_has_remote" ]; then
1238 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" || {
1239 echo ":refs/remotes/$base_remote/$_dep $_dep $_depchain"
1240 _ret=1
1243 # We want to sync with our base first and should output this before
1244 # the remote branch, but the order does not actually matter to tg-update
1245 # as it just recurses regardless, but it does matter for tg-info (which
1246 # treats out-of-date bases as though they were already merged in) so
1247 # we output the remote before the base.
1248 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1249 echo ": $_dep $_depchain"
1250 _ret=1
1251 return
1255 if [ -n "$_name" ]; then
1256 case "$_dep" in :*) _fulldep="${_dep#:}";; *) _fulldep="refs/heads/$_dep";; esac
1257 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1258 # Some new commits in _dep
1259 echo "$_dep $_depchain"
1260 _ret=1
1265 # needs_update NAME
1266 # This function is recursive; it outputs reverse path from NAME
1267 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1268 # inner paths first. Innermost name can be :refs/remotes/<remote>/<name>
1269 # if the head is not in sync with the <remote> branch <name>, ':' if
1270 # the head is not in sync with the base (in this order of priority)
1271 # or '!' if dependency is missing. Note that the remote branch, base
1272 # order is reversed from the order they will actually be updated in
1273 # order to accomodate tg info which treats out-of-date items that are
1274 # only in the base as already being in the head for status purposes.
1275 # It will also return non-zero status if NAME needs update (seems backwards
1276 # but think of it as non-zero status if any non-missing output lines produced)
1277 # If needs_update() hits missing dependencies, it will append
1278 # them to space-separated $missing_deps list and skip them.
1279 needs_update()
1281 recurse_deps branch_needs_update "$1"
1284 # append second arg to first arg variable gluing with space if first already set
1285 vplus()
1287 eval "$1=\"\${$1:+\$$1 }\$2\""
1290 # true if whitespace separated first var name list contains second arg
1291 # use `vcontains 3 "value" "some list"` for a literal list
1292 vcontains()
1294 eval case "\" \${$1} \"" in '*" $2 "*) return 0; esac; return 1'
1297 # if the $1 var does not already contain $2 it's appended
1298 vsetadd()
1300 vcontains "$1" "$2" || vplus "$1" "$2"
1303 # reset needs_update_check results to empty
1304 needs_update_check_clear()
1306 unset_ needs_update_processed needs_update_behind needs_update_ahead needs_update_partial
1309 # needs_update_check NAME...
1311 # A faster version of needs_update that always succeeds
1312 # No output and unsuitable for actually performing updates themselves
1313 # If any of NAME... are NOT up-to-date AND they were not already processed
1314 # return status always will be zero however a simple check of
1315 # needs_update_behind after the call will answer the:
1316 # "are any out of date?": test -n "$needs_update_behind"
1317 # "is <x> out of date?": vcontains needs_update_behind "<x>"
1319 # Note that results are cumulative and "no_remotes" is honored as well as other
1320 # variables that modify recurse_deps_internal behavior. See the preceding
1321 # function to reset the results to empty when accumulation should start over.
1323 # Unlike needs_update, the branch names are themselves also checked to see if
1324 # they are out-of-date with respect to their bases or remote branches (not just
1325 # their remote bases). However, this can muddy some status results so this
1326 # can be disabled by setting needs_update_check_no_self to a non-empty value.
1328 # Unlike needs_update, here the remote base check is handled together with the
1329 # remote head check so if one is modified the other is too in the same way.
1331 # Dependencies are normally considered "behind" if they need an update from
1332 # their base or remote but this can be suppressed by setting the
1333 # needs_update_check_no_same to a non-empty value. This will NOT prevent
1334 # parents of those dependencies from still being considered behind in such a
1335 # case even though the dependency itself will not be. Note that setting
1336 # needs_update_check_no_same also implies needs_update_check_no_self.
1338 # The following whitespace-separated lists are updated with the results:
1340 # The "no_remotes" setting is obeyed but remote names themselves will never
1341 # appear in any of the lists
1343 # needs_update_processed
1344 # The branch names in here have been processed and will be skipped
1346 # needs_update_behind
1347 # Any branch named in here needs an update from one or more of its
1348 # direct or indirect dependencies (i.e. it's "out-of-date")
1350 # needs_update_ahead
1351 # Any branch named in here is NOT fully contained by at least one of
1352 # its dependents (i.e. it's a source of "out-of-date (aka dirty)"ness
1354 # needs_update_partial
1355 # Any branch names in here are either missing themselves or have one
1356 # or more detected missing dependencies (a completely missing remote
1357 # branch is never "detected")
1358 needs_update_check()
1360 # each head must be processed independently or else there will be
1361 # confusion about who's missing what and which branches actually are
1362 # out of date
1363 tmptgrdi="$tg_tmp_dir/tgrdi.$$"
1364 for nucname in "$@"; do
1365 ! vcontains needs_update_processed "$nucname" || continue
1366 # no need to fuss with recurse_deps, just use
1367 # recurse_deps_internal directly
1368 recurse_deps_internal -s -o=-1 "$nucname" >"$tmptgrdi"
1369 while read -r _rdi_m _rdi_t _rdi_l _rdi_v _rdi_node _rdi_parent _rdi_chain; do
1370 case "$_rdi_node" in ""|:*) continue; esac # empty or checked with remote
1371 vsetadd needs_update_processed "$_rdi_node"
1372 if [ "$_rdi_m" != "0" ]; then # missing
1373 vsetadd needs_update_partial "$_rdi_node"
1374 [ -z "$_rdi_parent" ] || vsetadd needs_update_partial "$_rdi_parent"
1375 continue
1377 [ "$_rdi_t$_rdi_l" != "12" ] || continue # always skip annihilated
1378 _rdi_dertee= # :)
1379 if [ -n "$_rdi_parent" ]; then # not a "self" line
1380 ! vcontains needs_update_partial "$_rdi_node" || vsetadd needs_update_partial "$_rdi_parent"
1381 ! vcontains needs_update_behind "$_rdi_node" || _rdi_dertee=2
1382 else
1383 [ -z "$needs_update_check_no_self$needs_update_check_no_same" ] || continue # skip self
1385 if [ -z "$_rdi_dertee" ]; then
1386 if [ "$_rdi_t" != "0" ]; then # tgish
1387 if branch_contains "refs/heads/$_rdi_node" "refs/$topbases/$_rdi_node"; then
1388 if [ "$_rdi_t" = "2" ]; then # will never be "2" when no_remotes is set
1389 branch_contains "refs/heads/$_rdi_node" "refs/remotes/$base_remote/$_rdi_node" &&
1390 branch_contains "refs/$topbases/$_rdi_node" "refs/remotes/$base_remote/${topbases#heads/}/$_rdi_node" ||
1391 _rdi_dertee=3
1393 else
1394 _rdi_dertee=3
1396 [ -z "$_rdi_dertee" ] || [ -n "$needs_update_check_no_same" ] || _rdi_dertee=1
1399 [ z"$_rdi_dertee" != z"1" ] || vsetadd needs_update_behind "$_rdi_node"
1400 [ -n "$_rdi_parent" ] || continue # self line
1401 if ! branch_contains "refs/$topbases/$_rdi_parent" "refs/heads/$_rdi_node"; then
1402 _rdi_dertee=1
1403 vsetadd needs_update_ahead "$_rdi_node"
1405 [ -z "$_rdi_dertee" ] || vsetadd needs_update_behind "$_rdi_parent"
1406 done <"$tmptgrdi"
1407 done
1410 # branch_empty NAME [-i | -w]
1411 branch_empty()
1413 if [ -z "$2" ]; then
1414 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1415 _result=
1416 _result_rev=
1417 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1418 [ -z "$_result" ] || [ "$_result_rev" != "$_rev" ] || return $_result
1419 _result=0
1420 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1421 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1422 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1423 return $_result
1424 else
1425 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1429 v_get_tdmopt_internal()
1431 [ -n "$1" ] && [ -n "$3" ] || return 0
1432 [ "$2" = "-i" ] || [ "$2" = "-w" ] || return 0
1433 ensure_work_tree
1434 _optval=
1435 if v_verify_topgit_branch _tghead "HEAD" -f; then
1436 if [ "$2" = "-w" ] && [ -f "$root_dir/$3" ] && [ -r "$root_dir/$3" ]; then
1437 _opthash=
1438 if _opthash="$(git hash-object -w -t blob --stdin <"$root_dir/$3")" && [ -n "$_opthash" ]; then
1439 _optval="$4\"$_tghead:$_opthash\""
1441 elif [ "$2" = "-i" ]; then
1442 if _opthash="$(git rev-parse --quiet --verify ":0:$3" --)" && [ -n "$_opthash" ]; then
1443 _optval="$4\"$_tghead:$_opthash\""
1447 eval "$1="'"$_optval"'
1450 # set var $1 to the correct -td= option for use in an eval for $2 -i or -w mode
1451 v_get_tdopt() { v_get_tdmopt_internal "$1" "$2" ".topdeps" "-td="; }
1453 # set var $1 to the correct -tm= option for use in an eval for $2 -i or -w mode
1454 v_get_tmopt() { v_get_tdmopt_internal "$1" "$2" ".topmsg" "-tm="; }
1456 # checkout_symref_full [-f] FULLREF [SEED]
1457 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1458 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1459 # MUST be a committish which if present will be used instead of current FULLREF
1460 # (and FULLREF will be updated to it as well in that case)
1461 # Any merge state is always cleared by this function
1462 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1463 # instead of -m) but it will clear out any unmerged entries
1464 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1465 checkout_symref_full()
1467 _mode=-m
1468 _head="HEAD"
1469 if [ "$1" = "-f" ]; then
1470 _mode="--reset"
1471 _head=
1472 shift
1474 _ishash=
1475 case "$1" in
1476 refs/?*)
1478 $octet20)
1479 _ishash=1
1480 [ -z "$2" ] || [ "$1" = "$2" ] ||
1481 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1482 set -- HEAD "$1"
1485 die "programmer error: invalid checkout_symref_full \"$1\""
1487 esac
1488 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1489 die "invalid committish: \"${2:-$1}\""
1490 # Clear out any MERGE_HEAD kruft
1491 rm -f "$git_dir/MERGE_HEAD" || :
1492 # We have to do all the hard work ourselves :/
1493 # This is like git checkout -b "$1" "$2"
1494 # (or just git checkout "$1"),
1495 # but never creates a detached HEAD (unless $1 is a hash)
1496 git read-tree -u $_mode $_head "$_seedrev" &&
1498 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1499 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1500 } && {
1501 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1505 # switch_to_base NAME [SEED]
1506 switch_to_base()
1508 checkout_symref_full "refs/$topbases/$1" "$2"
1511 # run editor with arguments
1512 # the editor setting will be cached in $tg_editor (which is eval'd)
1513 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1514 # just in case, noalt_setup will be in effect while the editor is running
1515 run_editor()
1517 tg_editor="$GIT_EDITOR"
1518 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1520 noalt_setup
1521 eval "$tg_editor" '"$@"'
1525 # Show the help messages.
1526 do_help()
1528 _www=
1529 if [ "$1" = "-w" ]; then
1530 _www=1
1531 shift
1533 if [ "$1" = "st" ]; then
1534 shift
1535 set -- "status" "$@"
1537 if [ -z "$1" ] ; then
1538 # This is currently invoked in all kinds of circumstances,
1539 # including when the user made a usage error. Should we end up
1540 # providing more than a short help message, then we should
1541 # differentiate.
1542 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1544 ## Build available commands list for help output
1546 cmds=
1547 sep=
1548 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1549 ! [ -r "$cmd" ] && continue
1550 # strip directory part and "tg-" prefix
1551 cmd="${cmd##*/}"
1552 cmd="${cmd#tg-}"
1553 [ "$cmd" != "migrate-bases" ] || continue
1554 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1555 cmds="$cmds$sep$cmd"
1556 sep="|"
1557 done
1559 echo "TopGit version $TG_VERSION - A different patch queue manager"
1560 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u]" \
1561 "[-c <name>=<val>] [--[no-]pager|-p] [-w [:]<tgtag>] ($cmds) ..."
1562 echo " Or: $tgname help [-w] [<command>]"
1563 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1564 elif [ -r "$TG_INST_CMDDIR"/tg-$1 ] || [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1565 if [ -n "$_www" ]; then
1566 nohtml=
1567 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1568 echo "${0##*/}: missing html help file:" \
1569 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1570 nohtml=1
1572 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1573 echo "${0##*/}: missing html help file:" \
1574 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1575 nohtml=1
1577 if [ -n "$nohtml" ]; then
1578 echo "${0##*/}: use" \
1579 "\"${0##*/} help $1\" instead" 1>&2
1580 exit 1
1582 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1583 exit
1585 output()
1587 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1588 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1589 echo
1590 elif [ "$1" = "help" ]; then
1591 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1592 echo
1593 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1594 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1595 echo
1597 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1598 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1601 page output "$1"
1602 else
1603 echo "${0##*/}: no help for $1" 1>&2
1604 do_help
1605 exit 1
1609 check_status()
1611 git_state=
1612 git_remove=
1613 tg_state=
1614 tg_remove=
1615 tg_topmerge=
1616 setup_git_dir_is_bare
1617 [ -z "$git_dir_is_bare" ] || return 0
1619 if [ -e "$git_dir/MERGE_HEAD" ]; then
1620 git_state="merge"
1621 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1622 git_state="am"
1623 git_remove="$git_dir/rebase-apply"
1624 elif [ -e "$git_dir/rebase-apply" ]; then
1625 git_state="rebase"
1626 git_remove="$git_dir/rebase-apply"
1627 elif [ -e "$git_dir/rebase-merge" ]; then
1628 git_state="rebase"
1629 git_remove="$git_dir/rebase-merge"
1630 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1631 git_state="cherry-pick"
1632 elif [ -e "$git_dir/BISECT_LOG" ]; then
1633 git_state="bisect"
1634 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1635 git_state="revert"
1637 git_remove="${git_remove#./}"
1639 if [ -e "$git_dir/tg-update" ]; then
1640 tg_state="update"
1641 tg_remove="$git_dir/tg-update"
1642 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1644 tg_remove="${tg_remove#./}"
1647 # Show status information
1648 do_status()
1650 do_status_result=0
1651 do_status_verbose=
1652 do_status_help=
1653 abbrev=refs
1654 pfx=
1655 while [ $# -gt 0 ] && case "$1" in
1656 --help|-h)
1657 do_status_help=1
1658 break;;
1659 -vv)
1660 # kludge in this common bundling option
1661 abbrev=
1662 do_status_verbose=1
1663 pfx="## "
1665 --verbose|-v)
1666 [ -z "$do_status_verbose" ] || abbrev=
1667 do_status_verbose=1
1668 pfx="## "
1670 --exit-code)
1671 do_status_result=2
1674 die "unknown status argument: $1"
1676 esac; do shift; done
1677 if [ -n "$do_status_help" ]; then
1678 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1679 return
1681 check_status
1682 symref="$(git symbolic-ref --quiet HEAD)" || :
1683 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1684 if [ -n "$symref" ]; then
1685 uprefpart=
1686 if [ -n "$headrv" ]; then
1687 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1688 if [ -n "$upref" ]; then
1689 uprefpart=" ... ${upref#$abbrev/remotes/}"
1690 mbase="$(git merge-base HEAD "$upref")" || :
1691 ahead="$(git rev-list --count HEAD ${mbase:+--not} $mbase)" || ahead=0
1692 behind="$(git rev-list --count "$upref" ${mbase:+--not} $mbase)" || behind=0
1693 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1694 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1695 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1696 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1697 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1700 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1701 else
1702 echol "${pfx}HEAD -> ${headrv:-?}"
1704 if [ -n "$tg_state" ]; then
1705 extra=
1706 if [ "$tg_state" = "update" ]; then
1707 IFS= read -r uname <"$git_dir/tg-update/name" || :
1708 [ -z "$uname" ] ||
1709 extra="; currently updating branch '$uname'"
1711 echol "${pfx}tg $tg_state in progress$extra"
1712 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1713 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1714 cat "$git_dir/tg-update/fullcmd"
1715 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1716 if [ $bcnt -gt 1 ]; then
1717 pcnt=0
1718 ! [ -s "$git_dir/tg-update/processed" ] ||
1719 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1720 echo "${pfx}$pcnt of $bcnt branches updated so far"
1723 if [ "$tg_state" = "update" ]; then
1724 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1725 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1726 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1727 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1730 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1731 if [ "$git_state" = "merge" ]; then
1732 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1733 if [ $ucnt -gt 0 ]; then
1734 echo "${pfx}"'fix conflicts and then "git commit" the result'
1735 else
1736 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1739 if [ -z "$git_state" ]; then
1740 setup_git_dir_is_bare
1741 [ -z "$git_dir_is_bare" ] || return 0
1742 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository???
1743 gspcnt=0
1744 [ -z "$gsp" ] ||
1745 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1746 untr=
1747 if [ "$gspcnt" -eq 0 ]; then
1748 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1749 echo "${pfx}working directory is clean$untr"
1750 [ -n "$tg_state" ] || do_status_result=0
1751 else
1752 echo "${pfx}working directory is DIRTY"
1753 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1758 ## Pager stuff
1760 # isatty FD
1761 isatty()
1763 test -t $1
1766 # pass "diff" to get pager.diff
1767 # if pager.$1 is a boolean false returns cat
1768 # if set to true or unset fails
1769 # otherwise succeeds and returns the value
1770 get_pager()
1772 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1773 [ "$_x" != "true" ] || return 1
1774 echo "cat"
1775 return 0
1777 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1778 echol "$_x"
1779 return 0
1781 return 1
1784 # setup_pager
1785 # Set TG_PAGER to a valid executable
1786 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1787 # See also the following "page" function for ease of use
1788 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1789 # Preference is (same as Git):
1790 # 1. GIT_PAGER
1791 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1792 # 3. core.pager (only if set)
1793 # 4. PAGER
1794 # 5. git var GIT_PAGER
1795 # 6. less
1796 setup_pager()
1798 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1800 emptypager=
1801 if [ -z "$TG_PAGER_IN_USE" ]; then
1802 # TG_PAGER = GIT_PAGER | PAGER | less
1803 # NOTE: GIT_PAGER='' is significant
1804 if [ -n "${GIT_PAGER+set}" ]; then
1805 TG_PAGER="$GIT_PAGER"
1806 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1807 TG_PAGER="$_dp"
1808 elif _cp="$(git config core.pager 2>/dev/null)"; then
1809 TG_PAGER="$_cp"
1810 elif [ -n "${PAGER+set}" ]; then
1811 TG_PAGER="$PAGER"
1812 else
1813 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1814 [ "$_gp" != ":" ] || _gp=
1815 TG_PAGER="${_gp:-less}"
1817 if [ -z "$TG_PAGER" ]; then
1818 emptypager=1
1819 TG_PAGER=cat
1821 else
1822 emptypager=1
1823 TG_PAGER=cat
1826 # Set pager default environment variables
1827 # see pager.c:setup_pager
1828 if [ -z "${LESS+set}" ]; then
1829 LESS="-FRX"
1830 export LESS
1832 if [ -z "${LV+set}" ]; then
1833 LV="-c"
1834 export LV
1837 # this is needed so e.g. $(git diff) will still colorize it's output if
1838 # requested in ~/.gitconfig with color.diff=auto
1839 GIT_PAGER_IN_USE=1
1840 export GIT_PAGER_IN_USE
1842 # this is needed so we don't get nested pagers
1843 TG_PAGER_IN_USE=1
1844 export TG_PAGER_IN_USE
1847 # page eval_arg [arg ...]
1849 # Calls setup_pager then evals the first argument passing it all the rest
1850 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1851 # by setup_pager (in which case the output is left as-is).
1853 # To handle arbitrary paging duties, collect lines to be paged into a
1854 # function and then call page with the function name or perhaps func_name "$@".
1856 # If no arguments at all are passed in do nothing (return with success).
1857 page()
1859 [ $# -gt 0 ] || return 0
1860 setup_pager
1861 _evalarg="$1"; shift
1862 if [ -n "$emptypager" ]; then
1863 eval "$_evalarg" '"$@"'
1864 else
1865 { eval "$_evalarg" '"$@"';} | eval "$TG_PAGER"
1869 # get_temp NAME [-d]
1870 # creates a new temporary file (or directory with -d) in the global
1871 # temporary directory $tg_tmp_dir with pattern prefix NAME
1872 get_temp()
1874 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1877 # automatically called by strftime
1878 # does nothing if already setup
1879 # may be called explicitly if the first call would otherwise be in a subshell
1880 # so that the setup is only done once before subshells start being spawned
1881 setup_strftime()
1883 [ -z "$strftime_is_setup" ] || return 0
1885 # date option to format raw epoch seconds values
1886 daterawopt=
1887 _testes='951807788'
1888 _testdt='2000-02-29 07:03:08 UTC'
1889 _testfm='%Y-%m-%d %H:%M:%S %Z'
1890 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1891 daterawopt='-d@'
1892 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1893 daterawopt='-r'
1895 strftime_is_setup=1
1898 # $1 => strftime format string to use
1899 # $2 => raw timestamp as seconds since epoch
1900 # $3 => optional time zone string (empty/absent for local time zone)
1901 strftime()
1903 setup_strftime
1904 if [ -n "$daterawopt" ]; then
1905 if [ -n "$3" ]; then
1906 TZ="$3" date "$daterawopt$2" "+$1"
1907 else
1908 date "$daterawopt$2" "+$1"
1910 else
1911 if [ -n "$3" ]; then
1912 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1913 else
1914 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1919 got_cdup_result=
1920 git_cdup_result=
1921 v_get_show_cdup()
1923 if [ -z "$got_cdup_result" ]; then
1924 git_cdup_result="$(git rev-parse --show-cdup)"
1925 got_cdup_result=1
1927 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1930 git_dir_is_bare_setup=
1931 setup_git_dir_is_bare()
1933 if [ -z "$git_dir_is_bare_setup" ]; then
1934 git_dir_is_bare="$(git rev-parse --is-bare-repository)"
1935 [ z"$git_dir_is_bare" = z"true" ] || git_dir_is_bare=
1936 git_dir_is_bare_setup=1
1940 git_hooks_pat_list="\
1941 [a]pplypatch-ms[g] [p]re-applypatc[h] [p]ost-applypatc[h] [p]re-commi[t] \
1942 [p]repare-commit-ms[g] [c]ommit-ms[g] [p]ost-commi[t] [p]re-rebas[e] \
1943 [p]ost-checkou[t] [p]ost-merg[e] [p]re-pus[h] [p]re-receiv[e] [u]pdat[e] \
1944 [p]ost-receiv[e] [p]ost-updat[e] [p]ush-to-checkou[t] [p]re-auto-g[c] \
1945 [p]ost-rewrit[e]"
1947 # git_hooks_dir must already be set to the value of core.hooksPath which
1948 # exists and is an absolute path. The first and only argument is the
1949 # "pwd -P" of the $git_hooks_dir directory. If the core.hooksPath setting
1950 # appears to be "friendly" attempt to alter it to be an absolute path to
1951 # "$git_common_dir/hooks" instead. A "friendly" core.hooksPath setting
1952 # points to a directory for which "$git_common_dir/hooks" already has
1953 # entries which are symbolic links to the same core.hooksPath items.
1954 # There's no POSIX readlink utility, but there is a 'cmp -s' utility so we
1955 # use that instead to check. Also the "friendly" core.hooksPath must be
1956 # something that's recognizable as belonging to a "friendly".
1957 maybe_adjust_friendly_hooks_path()
1959 case "$1" in */_global/hooks);;*) return 0; esac
1960 [ -n "$1" ] && [ -d "$1" ] && [ -d "$git_common_dir/hooks" ] || return 0
1961 [ -w "$git_common_dir" ] || return 0
1962 ! [ -e "$git_common_dir/config" ] || {
1963 [ -f "$git_common_dir/config" ] && [ -w "$git_common_dir/config" ]
1964 } || return 0
1965 oktoswitch=1
1966 for ghook in $(cd "$1" && eval "echo $git_hooks_pat_list"); do
1967 case "$ghook" in "["*) continue; esac
1968 [ -x "$1/$ghook" ] &&
1969 [ -f "$1/$ghook" ] || continue
1970 [ -x "$git_common_dir/hooks/$ghook" ] &&
1971 [ -f "$git_common_dir/hooks/$ghook" ] &&
1972 cmp -s "$1/$ghook" "$git_common_dir/hooks/$ghook" || {
1973 oktoswitch=
1974 break
1976 done
1977 if [ -n "$oktoswitch" ]; then
1978 # a known "friendly" was detected and the hooks match;
1979 # go ahead and silently switch the path
1980 ! git config core.hooksPath "$git_common_dir/hooks" >/dev/null 2>&1 ||
1981 git_hooks_dir="$git_common_dir/hooks"
1983 unset_ oktoswitch
1984 return 0
1987 git_hooks_dir=
1988 setup_git_hooks_dir()
1990 [ -z "$git_hooks_dir" ] || return 0
1991 git_hooks_dir="$git_common_dir/hooks"
1992 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1993 case "$gchp" in
1994 /[!/]*)
1995 if [ -d "$gchp" ]; then
1996 # if core.hooksPath is just another name for
1997 # $git_common_dir/hooks, keep referring to it
1998 # by $git_common_dir/hooks
1999 abscdh="$(cd "$git_common_dir" && pwd -P)/hooks"
2000 abshpd="$(cd "$gchp" && pwd -P)"
2001 if [ "$abshpd" != "$abscdh" ]; then
2002 git_hooks_dir="$gchp"
2003 maybe_adjust_friendly_hooks_path "$abshpd"
2005 unset_ abscdh abshpd
2006 else
2007 [ -n "$1" ] || warn "ignoring non-existent core.hooksPath: $gchp"
2011 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
2013 esac
2014 unset_ gchp
2018 setup_git_dirs()
2020 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
2021 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
2022 git_dir="$(cd "$git_dir" && pwd)"
2024 if [ -z "$git_common_dir" ]; then
2025 if vcmp "$git_version" '>=' "2.5"; then
2026 # rev-parse --git-common-dir is broken and may give
2027 # an incorrect result unless the current directory is
2028 # already set to the top level directory
2029 v_get_show_cdup
2030 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
2031 else
2032 git_common_dir="$git_dir"
2035 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
2036 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
2039 basic_setup_remote()
2041 if [ -z "$base_remote" ]; then
2042 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
2043 base_remote="$TG_EXPLICIT_REMOTE"
2044 else
2045 base_remote="$(git config topgit.remote 2>/dev/null)" || :
2050 basic_setup()
2052 setup_git_dirs $1
2053 basic_setup_remote
2054 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
2055 tgnosequester=
2056 [ "$tgsequester" != "false" ] || tgnosequester=1
2057 unset_ tgsequester
2059 # catch errors if topbases is used without being set
2060 unset_ tg_topbases_set
2061 topbases="programmer*:error"
2062 topbasesrx="programmer*:error}"
2063 oldbases="$topbases"
2066 tmpdir_cleanup()
2068 test -z "$tg_tmp_dir" || ! test -d "$tg_tmp_dir" || ${TG_DEBUG:+echo} rm -rf "$tg_tmp_dir" >&2 || :
2071 tmpdir_setup()
2073 [ -z "$tg_tmp_dir" ] || return 0
2074 if [ -n "$TG_TMPDIR" ] && [ -d "$TG_TMPDIR" ] && [ -w "$TG_TMPDIR" ] &&
2075 { >"$TG_TMPDIR/.check"; } >/dev/null 2>&1; then
2076 tg_tmp_dir="$TG_TMPDIR"
2077 else
2078 tg_tmp_dir=
2079 TRAPEXIT_='tmpdir_cleanup'
2080 trap 'trapexit_ 129' HUP
2081 trap 'trapexit_ 130' INT
2082 trap 'trapexit_ 131' QUIT
2083 trap 'trapexit_ 134' ABRT
2084 trap 'trapexit_ 141' PIPE
2085 trap 'trapexit_ 143' TERM
2086 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2087 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2088 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2089 [ -z "$tg_tmp_dir" ] || tg_tmp_dir="$(cd "$tg_tmp_dir" && pwd -P)"
2091 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_tmp_dir/.check"; } >/dev/null 2>&1 ||
2092 die "could not create a writable temporary directory"
2094 # whenever tg_tmp_dir is != "" these must always be set
2095 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
2096 tg_ref_cache_br="$tg_ref_cache.br"
2097 tg_ref_cache_rbr="$tg_ref_cache.rbr"
2098 tg_ref_cache_ann="$tg_ref_cache.ann"
2099 tg_ref_cache_dep="$tg_ref_cache.dep"
2102 cachedir_setup()
2104 [ -z "$tg_cache_dir" ] || return 0
2105 user_id_no="$(id -u)" || :
2106 : "${user_id_no:=_99_}"
2107 tg_cache_dir="$git_common_dir/tg-cache"
2108 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2109 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
2110 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2111 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2112 if [ -z "$tg_cache_dir" ]; then
2113 tg_cache_dir="$tg_tmp_dir/tg-cache"
2114 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2115 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2117 [ -n "$tg_cache_dir" ] ||
2118 die "could not create a writable tg-cache directory (even a temporary one)"
2120 if [ -n "$2" ]; then
2121 # allow the wayback machine to share a separate cache
2122 [ -d "$tg_cache_dir/wayback" ] || mkdir "$tg_cache_dir/wayback" >/dev/null 2>&1 || :
2123 ! [ -d "$tg_cache_dir/wayback" ] || ! { >"$tg_cache_dir/wayback/.tgcache"; } >/dev/null 2>&1 ||
2124 tg_cache_dir="$tg_cache_dir/wayback"
2128 # set up alternate deb dirs
2129 altodb_setup()
2131 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
2132 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
2133 # so we avoid it if possible and require v2.11.1 to do it at all
2134 # otherwise just don't make an alternates temporary store in that case;
2135 # it's okay to not have one; everything will still work; the nicety of
2136 # making the temporary tree objects vanish when tg exits just won't
2137 # happen in that case but nothing will break also be sure to reuse
2138 # the parent's if we've been recursively invoked and it's for the
2139 # same repository we were invoked on
2141 tg_use_alt_odb=1
2142 _fullodbdir=
2143 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
2144 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] && _fullodbdir="$(cd "$_odbdir" && pwd -P)" ||
2145 die "could not find objects directory"
2146 if [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
2147 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
2148 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
2149 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
2150 tg_use_alt_odb=2
2153 _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
2154 if [ "$tg_use_alt_odb" = "1" ]; then
2155 # create an alternate objects database to keep the ephemeral objects in
2156 mkdir -p "$tg_tmp_dir/objects/info"
2157 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
2158 [ "$_fullodbdir" = "$TG_OBJECT_DIRECTORY" ] ||
2159 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
2161 case "$_fulltmpdir" in *[";:"]*|'"'*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
2162 if [ "$tg_use_alt_odb" = "1" ]; then
2163 case "$TG_OBJECT_DIRECTORY" in
2164 *[";:"]*|'"'*)
2165 # surround in "..." and backslash-escape internal '"' and '\\'
2166 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
2167 sed 's/\([""\\]\)/\\\1/g')\""
2170 _altodbdq="$TG_OBJECT_DIRECTORY"
2172 esac
2173 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2174 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2175 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2176 else
2177 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
2179 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
2180 if [ -n "$GIT_OBJECT_DIRECTORY" ]; then
2181 export GIT_OBJECT_DIRECTORY
2182 else
2183 unset_ GIT_OBJECT_DIRECTORY
2188 noalt_setup()
2190 if [ "${TG_PRESERVED_ALTERNATES+set}" = "set" ]; then
2191 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
2192 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2193 export GIT_ALTERNATE_OBJECT_DIRECTORIES
2194 else
2195 unset_ GIT_ALTERNATE_OBJECT_DIRECTORIES
2198 unset_ TG_TMPDIR TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES tg_use_alt_odb
2201 ## Initial setup
2202 initial_setup()
2204 # suppress the merge log editor feature since git 1.7.10
2206 GIT_MERGE_AUTOEDIT=no
2207 export GIT_MERGE_AUTOEDIT
2209 basic_setup $1
2210 iowopt=
2211 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
2212 gcfbopt=
2213 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
2214 auhopt=
2215 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
2216 v_get_show_cdup root_dir
2217 root_dir="${root_dir:-.}"
2218 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
2219 [ "$logrefupdates" = "true" ] || logrefupdates=
2221 # make sure root_dir doesn't end with a trailing slash.
2223 root_dir="${root_dir%/}"
2225 # create global temporary and cache directories, usually inside GIT_DIR
2227 tmpdir_setup
2228 unset_ TG_TMPDIR
2229 cachedir_setup
2231 # the wayback machine directory serves as its own "altodb"
2232 [ -n "$wayback" ] || altodb_setup
2235 activate_wayback_machine()
2237 [ -n "${1#:}" ] || [ -n "$2" ] || { wayback=; return 0; }
2238 setup_git_dirs
2239 tmpdir_setup
2240 altodb_setup
2241 tgwbr=
2242 tgwbr2=
2243 if [ -n "${1#:}" ]; then
2244 tgwbr="$(get_temp wbinfo)"
2245 tgwbr2="${tgwbr}2"
2246 tg revert --list --no-short "${1#:}" >"$tgwbr" && test -s "$tgwbr" || return 1
2247 # tg revert will likely leave a revert-tag-only cache which is not what we want
2248 remove_ref_cache
2250 cachedir_setup "" 1 # use a separate wayback cache dir
2251 # but don't step on the normal one if the separate one could not be set up
2252 case "$tg_cache_dir" in */wayback);;*) tg_cache_dir=; esac
2253 altodb="$TG_OBJECT_DIRECTORY"
2254 if [ -n "$3" ] && [ -n "$2" ]; then
2255 [ -d "$3" ] || { mkdir -p "$3" && [ -d "$3" ]; } ||
2256 die "could not create wayback directory: $3"
2257 tg_wayback_dir="$(cd "$3" && pwd -P)" || die "could not get wayback directory full path"
2258 [ -d "$tg_wayback_dir/.git" ] || { mkdir -p "$tg_wayback_dir/.git" && [ -d "$tg_wayback_dir/.git" ]; } ||
2259 die "could not initialize wayback directory: $3"
2260 is_empty_dir "$tg_wayback_dir" ".git" && is_empty_dir "$tg_wayback_dir/.git" "." ||
2261 die "wayback directory is not empty: $3"
2262 mkdir "$tg_wayback_dir/.git/objects"
2263 mkdir "$tg_wayback_dir/.git/objects/info"
2264 cat "$altodb/info/alternates" >"$tg_wayback_dir/.git/objects/info/alternates"
2265 else
2266 tg_wayback_dir="$tg_tmp_dir/wayback"
2267 mkdir "$tg_wayback_dir"
2268 mkdir "$tg_wayback_dir/.git"
2269 ln -s "$altodb" "$tg_wayback_dir/.git/objects"
2271 mkdir "$tg_wayback_dir/.git/refs"
2272 printf '0 Wayback Machine' >"$tg_wayback_dir/.git/gc.pid"
2273 qpesc="$(printf '%s\n' "$git_common_dir" | sed -e 's/\([\\""]\)/\\\1/g' -e '$!s/$/\\n/' | tr -d '\n')"
2274 laru="false"
2275 [ -z "$2" ] || laru="true"
2276 printf '%s' "\
2277 [include]
2278 path = \"$qpesc/config\"
2279 [core]
2280 bare = false
2281 logAllRefUpdates = $laru
2282 repositoryFormatVersion = 0
2283 [extensions]
2284 preciousObjects = true
2285 [gc]
2286 auto = 0
2287 autoDetach = false
2288 autoPackLimit = 0
2289 packRefs = false
2290 [remote \"wayback\"]
2291 url = \"$qpesc\"
2292 [push]
2293 default = nothing
2294 followTags = true
2295 [alias]
2296 wayback-updates = fetch -u --force --no-tags --dry-run wayback refs/*:refs/*
2297 " >"$tg_wayback_dir/.git/config"
2298 cat "$git_dir/HEAD" >"$tg_wayback_dir/.git/HEAD"
2299 case "$1" in ":"?*);;*)
2300 git show-ref >"$tg_wayback_dir/.git/packed-refs"
2301 git --git-dir="$tg_wayback_dir/.git" pack-refs --all
2302 esac
2303 noalt_setup
2304 TG_OBJECT_DIRECTORY="$altodb" && export TG_OBJECT_DIRECTORY
2305 if [ -n "${1#:}" ]; then
2306 <"$tgwbr" sed 's/^\([^ ][^ ]*\) \([^ ][^ ]*\)$/update \2 \1/' |
2307 git --git-dir="$tg_wayback_dir/.git" update-ref -m "wayback to $1" ${2:+--create-reflog} --stdin
2309 if test -n "$2"; then
2310 # extra setup for potential shell
2311 qpesc2="$(printf '%s\n' "$git_common_dir" | sed -e 's/\([\\""]\)/\\\\\1/g' -e '$!s/$/\\n/' | tr -d '\n')"
2312 printf '\twayback-repository = "!printf '\''%%s\\\\n'\'' \\"%s\\""\n' "$qpesc2" >>"$tg_wayback_dir/.git/config"
2313 qtesc="$(printf '%s\n' "${1:-:}" | sed 's/\([""]\)/\\\1/g')"
2314 printf '\twayback-tag = "!printf '\''%%s\\\\n'\'' \\"%s\\""\n' "$qtesc" >>"$tg_wayback_dir/.git/config"
2315 if [ -d "$git_common_dir/rr-cache" ]; then
2316 ln -s "$git_common_dir/rr-cache" "$tg_wayback_dir/.git/rr-cache"
2317 printf "[rerere]\n\tenabled = true\n" >>"$tg_wayback_dir/.git/config"
2319 if [ z"$2" != z"2" ]; then
2320 wbauth=
2321 wbprnt=
2322 if [ -n "${1#:}" ]; then
2323 [ -n "$tgwbr2" ] || tgwbr2="$(get_temp wbtag)"
2324 git --git-dir="$git_common_dir" cat-file tag "${1#:}" >"$tgwbr2" || return 1
2325 wbprnt="${lf}parent $(git --git-dir="$git_common_dir" rev-parse --verify --quiet "${1#:}"^0 -- 2>/dev/null)" || wbprnt=
2326 wbauth="$(<"$tgwbr2" awk '{if(!$0)exit;if($1=="tagger")print "author" substr($0,7)}')"
2328 wbcmtr="committer Wayback Machine <-> $(date "+%s %z")"
2329 [ -n "$wbauth" ] || wbauth="author${wbcmtr#committer}"
2330 wbtree="$(git --git-dir="$tg_wayback_dir/.git" mktree </dev/null)"
2331 wbcmt="$({
2332 printf '%s\n' "tree $wbtree$wbprnt" "$wbauth" "$wbcmtr" ""
2333 if [ -n "$tgwbr2" ]; then
2334 <"$tgwbr2" sed -e '1,/^$/d' -e '/^-----BEGIN/,$d' | git stripspace
2335 else
2336 echo "Wayback Machine"
2338 } | git --git-dir="$tg_wayback_dir/.git" hash-object -t commit -w --stdin)"
2339 test -n "$wbcmt" || return 1
2340 echo "$wbcmt" >"$tg_wayback_dir/.git/HEAD"
2343 cd "$tg_wayback_dir"
2344 unset git_dir git_common_dir
2347 set_topbases()
2349 # refer to "top-bases" in a refname with $topbases
2351 [ -z "$tg_topbases_set" ] || return 0
2353 topbases_implicit_default=1
2354 # See if topgit.top-bases is set to heads or refs
2355 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
2356 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
2357 if [ -n "$1" ]; then
2358 # never die on the hook script
2359 unset_ tgtb
2360 else
2361 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
2364 if [ -n "$tgtb" ]; then
2365 case "$tgtb" in
2366 heads)
2367 topbases="heads/{top-bases}"
2368 topbasesrx="heads/[{]top-bases[}]"
2369 oldbases="top-bases";;
2370 refs)
2371 topbases="top-bases"
2372 topbasesrx="top-bases"
2373 oldbases="heads/{top-bases}";;
2374 esac
2375 # MUST NOT be exported
2376 unset_ tgtb tg_topbases_set topbases_implicit_default
2377 tg_topbases_set=1
2378 return 0
2380 unset_ tgtb
2382 # check heads and top-bases and see what state the current
2383 # repository is in. remotes are ignored.
2385 rc=0 activebases=
2386 activebases="$(
2387 git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null |
2388 run_awk_ref_prefixes ${1:+-e} -n -- "refs/heads/{top-bases}" "refs/top-bases" "refs/heads")" ||
2389 rc=$?
2390 if [ "$rc" = "65" ]; then
2391 # Complain and die
2392 err "repository contains existing TopGit branches"
2393 err "but some use refs/top-bases/... for the base"
2394 err "and some use refs/heads/{top-bases}/... for the base"
2395 err "with the latter being the new, preferred location"
2396 err "set \"topgit.top-bases\" to either \"heads\" to use"
2397 err "the new heads/{top-bases} location or \"refs\" to use"
2398 err "the old top-bases location."
2399 err "(the tg migrate-bases command can also resolve this issue)"
2400 die "schizophrenic repository requires topgit.top-bases setting"
2402 [ -z "$activebases" ] || unset_ topbases_implicit_default
2403 if [ "$activebases" = "refs/heads/{top-bases}" ]; then
2404 topbases="heads/{top-bases}"
2405 topbasesrx="heads/[{]top-bases[}]"
2406 oldbases="top-bases"
2407 else
2408 # default is still top-bases for now
2409 topbases="top-bases"
2410 topbasesrx="top-bases"
2411 oldbases="heads/{top-bases}"
2413 # MUST NOT be exported
2414 unset_ rc activebases tg_topases_set
2415 tg_topbases_set=1
2416 return 0
2419 # $1 is remote name to check
2420 # $2 is optional variable name to set to result of check
2421 # $3 is optional command name to use in message (defaults to $cmd)
2422 # Fatal error if remote has schizophrenic top-bases
2423 # No error (and $2, if provided, will be set to empty) if remote has no top-bases at all
2424 check_remote_topbases()
2426 [ -n "$1" ] || die "programmer error: check_remote_topbases called with no remote argument"
2427 _crrc=0 _crremotebases=
2428 _crremotebases="$(
2429 git for-each-ref --format='%(refname)' "refs/remotes/$1" 2>/dev/null |
2430 run_awk_ref_prefixes -n -- "refs/remotes/$1/{top-bases}" "refs/remotes/$1/top-bases" "refs/remotes/$1")" ||
2431 _crrc=$?
2432 if [ "$_crrc" = "65" ]; then
2433 err "remote \"$1\" has top-bases in both locations:"
2434 err " refs/remotes/$1/{top-bases}/..."
2435 err " refs/remotes/$1/top-bases/..."
2436 err "set \"topgit.top-bases\" to \"heads\" for the first, preferred location"
2437 err "or set \"topgit.top-bases\" to \"refs\" for the second, old location"
2438 err "(the \"-c topgit.top-bases=<val>\" option can be used for this)"
2439 err "then re-run the tg ${3:-$cmd} command"
2440 err "(the tg migrate-bases command can also help with this problem)"
2441 die "schizophrenic remote \"$1\" requires topgit.top-bases setting"
2443 [ "$_crrc" != "66" ] || _crremotebases= # just to be sure
2444 [ -z "$2" ] || eval "$2="'"$_crremotebases"'
2445 unset _crrc _crremotebases
2446 return 0
2449 # init_reflog "ref"
2450 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
2451 # an empty log file to exist so that ref changes will be logged
2452 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
2453 # However, if "$1" is "refs/tgstash" then always make the reflog
2454 # The only ref not under refs/ that Git will write a reflog for is HEAD;
2455 # no matter what, it will NOT update a reflog for any other bare refs so
2456 # just quietly succeed when passed TG_STASH without doing anything.
2457 init_reflog()
2459 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
2460 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
2461 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
2462 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
2463 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
2466 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
2467 # a symbolic link. The directory part must exist, but the basename need not.
2468 v_get_abs_path()
2470 [ -n "$1" ] && [ -n "$2" ] || return 1
2471 set -- "$1" "$2" "${2%/}"
2472 case "$3" in
2473 */*) set -- "$1" "$2" "${3%/*}";;
2474 * ) set -- "$1" "$2" ".";;
2475 esac
2476 case "$2" in */)
2477 set -- "$1" "${2%/}" "$3" "/"
2478 esac
2479 [ -d "$3" ] || return 1
2480 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
2483 ## Startup
2485 : "${TG_INST_CMDDIR:=@cmddir@}"
2486 : "${TG_INST_SHAREDIR:=@sharedir@}"
2487 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
2489 [ -d "$TG_INST_CMDDIR" ] ||
2490 die "No command directory: '$TG_INST_CMDDIR'"
2492 ## Include awk scripts and their utility functions (separated for easier debugging)
2494 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
2495 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
2496 . "$TG_INST_CMDDIR/tg--awksome"
2498 if [ -n "$tg__include" ]; then
2500 # We were sourced from another script for our utility functions;
2501 # this is set by hooks. Skip the rest of the file. A simple return doesn't
2502 # work as expected in every shell. See http://bugs.debian.org/516188
2504 # ensure setup happens
2506 initial_setup 1
2507 set_topbases 1
2508 noalt_setup
2510 else
2512 set -e
2514 tgbin="$0"
2515 tgdir="${tgbin%/}"
2516 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
2517 tgdir="${tgdir%/*}/"
2518 tgname="${tgbin##*/}"
2519 [ "$0" != "$tgname" ] || tgdir=""
2521 # If tg contains a '/' but does not start with one then replace it with an absolute path
2523 case "$0" in /*) ;; */*)
2524 tgdir="$(cd "${0%/*}" && pwd -P)/"
2525 tgbin="$tgdir$tgname"
2526 esac
2528 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
2529 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2531 tgdisplaydir="$tgdir"
2532 tgdisplay="$tgbin"
2533 tgdisplayac="$tgdisplay"
2535 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2536 _tgabs="$_tgnameabs" &&
2537 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2538 [ "$_tgabs" = "$_tgnameabs" ]
2539 then
2540 tgdisplaydir=""
2541 tgdisplay="$tgname"
2542 tgdisplayac="$tgdisplay"
2544 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2545 unset_ _tgabs _tgnameabs
2547 tg() (
2548 TG_TMPDIR="$tg_tmp_dir" && export TG_TMPDIR &&
2549 exec "$tgbin" "$@"
2552 explicit_remote=
2553 explicit_dir=
2554 gitcdopt=
2555 noremote=
2556 forcepager=
2557 wayback=
2559 cmd=
2560 while :; do case "$1" in
2562 help|--help|-h)
2563 cmd=help
2564 shift
2565 break;;
2567 status|--status)
2568 cmd=status
2569 shift
2570 break;;
2572 --hooks-path)
2573 cmd=hooks-path
2574 shift
2575 break;;
2577 --exec-path)
2578 cmd=exec-path
2579 shift
2580 break;;
2582 --awk-path)
2583 cmd=awk-path
2584 shift
2585 break;;
2587 --top-bases)
2588 cmd=top-bases
2589 shift
2590 break;;
2592 --no-pager)
2593 forcepager=0
2594 shift;;
2596 --pager|-p)
2597 forcepager=1
2598 shift;;
2601 shift
2602 if [ -z "$1" ]; then
2603 echo "Option -r requires an argument." >&2
2604 do_help
2605 exit 1
2607 unset_ noremote
2608 base_remote="$1"
2609 explicit_remote="$base_remote"
2610 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2611 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2612 shift;;
2615 unset_ base_remote explicit_remote
2616 noremote=1
2617 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2618 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2619 shift;;
2622 shift
2623 if [ -z "$1" ]; then
2624 echo "Option -C requires an argument." >&2
2625 do_help
2626 exit 1
2628 cd "$1"
2629 unset_ GIT_DIR GIT_COMMON_DIR
2630 if [ -z "$explicit_dir" ]; then
2631 explicit_dir="$1"
2632 else
2633 explicit_dir="$PWD"
2635 gitcdopt=" -C \"$explicit_dir\""
2636 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2637 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2638 tgdisplayac="$tgdisplay"
2639 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2640 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2641 shift;;
2644 shift
2645 if [ -z "$1" ]; then
2646 echo "Option -c requires an argument." >&2
2647 do_help
2648 exit 1
2650 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2651 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2652 export GIT_CONFIG_PARAMETERS
2653 shift;;
2656 if [ -n "$wayback" ]; then
2657 echo "Option -w may be used at most once." >&2
2658 do_help
2659 exit 1
2661 shift
2662 if [ -z "$1" ]; then
2663 echo "Option -w requires an argument." >&2
2664 do_help
2665 exit 1
2667 wayback="$1"
2668 shift;;
2671 shift
2672 break;;
2675 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2676 do_help
2677 exit 1;;
2680 break;;
2682 esac; done
2683 if [ z"$forcepager" = z"0" ]; then
2684 GIT_PAGER_IN_USE=1 TG_PAGER_IN_USE=1 &&
2685 export GIT_PAGER_IN_USE TG_PAGER_IN_USE
2688 [ -n "$cmd" ] || [ $# -lt 1 ] || { cmd="$1"; shift; }
2690 ## Dispatch
2692 [ -n "$cmd" ] || { do_help; exit 1; }
2694 case "$cmd" in
2696 help)
2697 do_help "$@"
2698 exit 0;;
2700 status|st)
2701 unset_ base_remote
2702 basic_setup
2703 set_topbases
2704 do_status "$@"
2705 exit ${do_status_result:-0};;
2707 hooks-path)
2708 # Internal command
2709 echol "$TG_INST_HOOKSDIR";;
2711 exec-path)
2712 # Internal command
2713 echol "$TG_INST_CMDDIR";;
2715 awk-path)
2716 # Internal command
2717 echol "$TG_INST_CMDDIR/awk";;
2719 top-bases)
2720 # Maintenance command
2721 do_topbases_help=
2722 show_remote_topbases=
2723 case "$1" in
2724 --help|-h)
2725 do_topbases_help=0;;
2726 -r|--remote)
2727 if [ $# -eq 2 ] && [ -n "$2" ]; then
2728 # unadvertised, but make it work
2729 base_remote="$2"
2730 shift
2732 show_remote_topbases=1;;
2734 [ $# -eq 0 ] || do_topbases_help=1;;
2735 esac
2736 [ $# -le 1 ] || do_topbases_help=1
2737 if [ -n "$do_topbases_help" ]; then
2738 helpcmd='echo "Usage: ${tgname:-tg} [-r <remote>] --top-bases [-r]"'
2739 [ $do_topbases_help -eq 0 ] || helpcmd="$helpcmd >&2"
2740 eval "$helpcmd"
2741 exit $do_topbases_help
2743 git_dir=
2744 if git_dir="$(git rev-parse --git-dir 2>&1)"; then
2745 [ -z "$wayback" ] || activate_wayback_machine "$wayback"
2746 setup_git_dirs
2748 set_topbases
2749 if [ -n "$show_remote_topbases" ]; then
2750 basic_setup_remote
2751 [ -n "$base_remote" ] ||
2752 die "no remote location given. Either use -r <remote> option or set topgit.remote"
2753 rbases=
2754 [ -z "$topbases_implicit_default" ] ||
2755 check_remote_topbases "$base_remote" rbases "--top-bases"
2756 if [ -n "$rbases" ]; then
2757 echol "$rbases"
2758 else
2759 echol "refs/remotes/$base_remote/${topbases#heads/}"
2761 else
2762 echol "refs/$topbases"
2763 fi;;
2766 isutil=
2767 case "$cmd" in index-merge-one-file)
2768 isutil="-"
2769 esac
2770 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2771 looplevel="$TG_ALIAS_DEPTH"
2772 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2773 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2774 looplevel=0
2775 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2776 [ -n "$tgalias" ] || {
2777 echo "Unknown subcommand: $cmd" >&2
2778 do_help
2779 exit 1
2781 looplevel=$(( $looplevel + 1 ))
2782 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2783 TG_ALIAS_DEPTH="$looplevel"
2784 export TG_ALIAS_DEPTH
2785 if [ "!${tgalias#?}" = "$tgalias" ]; then
2786 [ -z "$wayback" ] ||
2787 die "-w is not allowed before an '!' alias command"
2788 unset_ GIT_PREFIX
2789 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2790 GIT_PREFIX="$pfx"
2791 export GIT_PREFIX
2793 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2794 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2795 else
2796 eval 'exec "$tgbin"' "${wayback:+-w \"\$wayback\"}" "$tgalias" '"$@"'
2798 die "alias execution failed for: $tgalias"
2800 unset_ TG_ALIAS_DEPTH
2802 showing_help=
2803 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2804 showing_help=1
2807 nomergesetup="$showing_help"
2808 case "$cmd" in base|contains|export|files|info|log|mail|next|patch|prev|rebase|revert|shell|summary|tag)
2809 # avoid merge setup where not necessary
2811 nomergesetup=1
2812 esac
2814 if [ -n "$wayback" ] && [ -z "$showing_help" ]; then
2815 [ -n "$nomergesetup" ] ||
2816 die "the wayback machine cannot be used with the \"$cmd\" subcommand"
2817 if [ "$cmd" = "shell" ]; then
2818 # this is ugly; `tg shell` should handle this but it's too
2819 # late there so we have to do it here
2820 wayback_dir=
2821 case "$1" in
2822 "--directory="?*)
2823 wayback_dir="${1#--directory=}" && shift;;
2824 "--directory=")
2825 die "--directory requires an argument";;
2826 "--directory")
2827 [ $# -ge 2 ] || die "--directory requires an argument"
2828 wayback_dir="$2" && shift 2;;
2829 esac
2830 activate_wayback_machine "$wayback" 1 "$wayback_dir"
2831 else
2832 _fullwb=
2833 # export might drop out into a shell for conflict resolution
2834 [ "$cmd" != "export" ] || _fullwb=2
2835 activate_wayback_machine "$wayback" "$_fullwb"
2836 fi ||
2837 die "failed to set the wayback machine to target \"$wayback\""
2840 [ -n "$showing_help" ] || initial_setup
2841 [ -z "$noremote" ] || unset_ base_remote
2843 if [ -z "$nomergesetup" ]; then
2844 # make sure merging the .top* files will always behave sanely
2846 setup_ours
2847 setup_hook "pre-commit"
2850 # everything but rebase needs topbases set
2851 carefully="$showing_help"
2852 [ "$cmd" != "migrate-bases" ] || carefully=1
2853 [ "$cmd" = "rebase" ] || set_topbases $carefully
2855 _use_ref_cache=
2856 tg_read_only=1
2857 _suppress_alt=
2858 case "$cmd$showing_help" in
2859 contains|info|summary|tag)
2860 _use_ref_cache=1;;
2861 "export")
2862 _use_ref_cache=1
2863 _suppress_alt=1;;
2864 annihilate|create|delete|depend|import|update)
2865 tg_read_only=
2866 _suppress_alt=1;;
2867 esac
2868 [ -z "$_suppress_alt" ] || noalt_setup
2869 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2871 fullcmd="${tgname:-tg} $cmd $*"
2872 fullcmd="${fullcmd% }"
2873 if [ z"$forcepager" = z"1" ]; then
2874 page '. "$TG_INST_CMDDIR"/tg-$isutil$cmd' "$@"
2875 else
2876 . "$TG_INST_CMDDIR"/tg-$isutil$cmd
2877 fi;;
2878 esac