tg-checkout.sh: fix typo
[topgit/pro.git] / tg.sh
blob458da1b5bef85a4b7ca476af89de566707cabd93
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.10-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 cut() { exec_lc_all_c cut cut "$@"; }
77 find() { exec_lc_all_c find find "$@"; }
78 grep() { exec_lc_all_c grep grep "$@"; }
79 join() { exec_lc_all_c join join "$@"; }
80 paste() { exec_lc_all_c paste paste "$@"; }
81 sed() { exec_lc_all_c sed sed "$@"; }
82 sort() { exec_lc_all_c sort sort "$@"; }
83 tr() { exec_lc_all_c tr tr "$@"; }
84 wc() { exec_lc_all_c wc wc "$@"; }
85 xargs() { exec_lc_all_c xargs xargs "$@"; }
87 # Output arguments without any possible interpretation
88 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
89 echol()
91 printf '%s\n' "$*"
94 info()
96 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
99 warn()
101 info "warning: $*" >&2
104 err()
106 info "error: $*" >&2
109 fatal()
111 info "fatal: $*" >&2
114 die()
116 fatal "$@"
117 exit 1
120 # shift off first arg then return "$*" properly quoted in single-quotes
121 # if $1 was '' output goes to stdout otherwise it's assigned to $1
122 # the final \n, if any, is omitted from the result but any others are included
123 v_quotearg()
125 _quotearg_v="$1"
126 shift
127 set -- "$_quotearg_v" \
128 "sed \"s/'/'\\\\\\''/g;1s/^/'/;\\\$s/\\\$/'/;s/'''/'/g;1s/^''\\(.\\)/\\1/\"" "$*"
129 unset_ _quotearg_v
130 if [ -z "$3" ]; then
131 if [ -z "$1" ]; then
132 echo "''"
133 else
134 eval "$1=\"''\""
136 else
137 if [ -z "$1" ]; then
138 printf "%s$4" "$3" | eval "$2"
139 else
140 eval "$1="'"$(printf "%s$4" "$3" | eval "$2")"'
145 # same as v_quotearg except there's no extra $1 so output always goes to stdout
146 quotearg()
148 v_quotearg '' "$@"
151 vcmp()
153 # Compare $1 to $3 each of which must match ^[^0-9]*\d*(\.\d*)*.*$
154 # where only the "\d*" parts in the regex participate in the comparison
155 # Since EVERY string matches that regex this function is easy to use
156 # An empty string ('') for $1 or $3 or any "\d*" part is treated as 0
157 # $2 is a compare op '<', '<=', '=', '==', '!=', '>=', '>'
158 # Return code is 0 for true, 1 for false (or unknown compare op)
159 # There is NO difference in behavior between '=' and '=='
160 # Note that "vcmp 1.8 == 1.8.0.0.0.0" correctly returns 0
161 set -- "$1" "$2" "$3" "${1%%[0-9]*}" "${3%%[0-9]*}"
162 set -- "${1#"$4"}" "$2" "${3#"$5"}"
163 set -- "${1%%[!0-9.]*}" "$2" "${3%%[!0-9.]*}"
164 while
165 vcmp_a_="${1%%.*}"
166 vcmp_b_="${3%%.*}"
167 [ "z$vcmp_a_" != "z" ] || [ "z$vcmp_b_" != "z" ]
169 if [ "${vcmp_a_:-0}" -lt "${vcmp_b_:-0}" ]; then
170 unset_ vcmp_a_ vcmp_b_
171 case "$2" in "<"|"<="|"!=") return 0; esac
172 return 1
173 elif [ "${vcmp_a_:-0}" -gt "${vcmp_b_:-0}" ]; then
174 unset_ vcmp_a_ vcmp_b_
175 case "$2" in ">"|">="|"!=") return 0; esac
176 return 1;
178 vcmp_a_="${1#$vcmp_a_}"
179 vcmp_b_="${3#$vcmp_b_}"
180 set -- "${vcmp_a_#.}" "$2" "${vcmp_b_#.}"
181 done
182 unset_ vcmp_a_ vcmp_b_
183 case "$2" in "="|"=="|"<="|">=") return 0; esac
184 return 1
187 # true if "$1" is an existing dir and is empty except for
188 # any additional files given as extra arguments. If "$2"
189 # is the single character "." then all ".*" files will be
190 # ignored for the test (plus any further args, if any)
191 is_empty_dir() {
192 test -n "$1" && test -d "$1" || return 1
193 iedd_="$1"
194 shift
195 ieddnok_='\.?$'
196 if [ z"$1" = z"." ]; then
197 ieddnok_=
198 shift
199 while ! case "$1" in "."*) ! :; esac; do shift; done
201 if [ $# -eq 0 ]; then
202 ! \ls -a1 "$iedd_" | grep -q -E -v '^\.'"$ieddnok_"
203 else
204 # we only handle ".git" right now for efficiency
205 [ z"$*" = z".git" ] || {
206 fatal "[BUG] is_empty_dir not implemented for arguments: $*"
207 exit 70
209 ! \ls -a1 "$iedd_" | grep -q -E -v -i -e '^\.\.?$' -e '^\.git$'
213 precheck() {
214 if ! git_version="$(git version)"; then
215 die "'git version' failed"
217 case "$git_version" in [Gg]"it version "*);;*)
218 die "'git version' output does not start with 'git version '"
219 esac
221 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
222 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
225 case "$1" in version|--version|-V)
226 echo "TopGit version $TG_VERSION"
227 exit 0
228 esac
230 [ $# -eq 1 ] && [ "$1" = "--make-empty-blob" ] || precheck
231 [ $# -ne 1 ] || [ "$1" != "precheck" ] || exit 0
233 cat_depsmsg_internal()
235 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
236 if [ -s "$tg_cache_dir/refs/heads/$1/.$2" ]; then
237 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
238 _line=
239 while IFS= read -r _line || [ -n "$_line" ]; do
240 printf '%s\n' "$_line"
241 done
242 return 0
243 fi <"$tg_cache_dir/refs/heads/$1/.$2"
245 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null || :
246 if [ -d "$tg_cache_dir/refs/heads/$1" ]; then
247 printf '%s\n' "$_rev" >"$tg_cache_dir/refs/heads/$1/.$2"
248 _line=
249 git cat-file blob "$_rev:.$2" 2>/dev/null |
250 while IFS= read -r _line || [ -n "$_line" ]; do
251 printf '%s\n' "$_line" >&3
252 printf '%s\n' "$_line"
253 done 3>>"$tg_cache_dir/refs/heads/$1/.$2"
254 else
255 git cat-file blob "$_rev:.$2" 2>/dev/null
259 # cat_deps BRANCHNAME
260 # Caches result
261 cat_deps()
263 cat_depsmsg_internal "$1" topdeps
266 # cat_msg BRANCHNAME
267 # Caches result
268 cat_msg()
270 cat_depsmsg_internal "$1" topmsg
273 # cat_file TOPIC:PATH [FROM]
274 # cat the file PATH from branch TOPIC when FROM is empty.
275 # FROM can be -i or -w, than the file will be from the index or worktree,
276 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
277 cat_file()
279 path="$1"
280 case "$2" in
282 cat "$root_dir/${path#*:}"
285 # ':file' means cat from index
286 git cat-file blob ":${path#*:}" 2>/dev/null
289 case "$path" in
290 refs/heads/*:.topdeps)
291 _temp="${path%:.topdeps}"
292 cat_deps "${_temp#refs/heads/}"
294 refs/heads/*:.topmsg)
295 _temp="${path%:.topmsg}"
296 cat_msg "${_temp#refs/heads/}"
299 git cat-file blob "$path" 2>/dev/null
301 esac
304 die "Wrong argument to cat_file: '$2'"
306 esac
309 # if use_alt_temp_odb and tg_use_alt_odb are true try to write the object(s)
310 # into the temporary alt odb area instead of the usual location
311 git_temp_alt_odb_cmd()
313 if [ -n "$use_alt_temp_odb" ] && [ -n "$tg_use_alt_odb" ] &&
314 [ -n "$TG_OBJECT_DIRECTORY" ] &&
315 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
317 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
318 GIT_OBJECT_DIRECTORY="$TG_OBJECT_DIRECTORY"
319 unset_ TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES
320 export GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
321 git "$@"
323 else
324 git "$@"
328 git_write_tree() { git_temp_alt_odb_cmd write-tree "$@"; }
329 git_mktree() { git_temp_alt_odb_cmd mktree "$@"; }
331 make_mtblob() {
332 use_alt_temp_odb=1
333 tg_use_alt_odb=1
334 git_temp_alt_odb_cmd hash-object -t blob -w --stdin </dev/null >/dev/null 2>&1
336 # short-circuit this for speed
337 [ $# -eq 1 ] && [ "$1" = "--make-empty-blob" ] && { make_mtblob || :; exit 0; }
339 # get tree for the committed topic
340 get_tree_()
342 echo "refs/heads/$1"
345 # get tree for the base
346 get_tree_b()
348 echo "refs/$topbases/$1"
351 # get tree for the index
352 get_tree_i()
354 git_write_tree
357 # get tree for the worktree
358 get_tree_w()
360 i_tree=$(git_write_tree)
362 # the file for --index-output needs to sit next to the
363 # current index file
364 cd "$root_dir"
365 : ${GIT_INDEX_FILE:="$git_dir/index"}
366 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
367 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
368 GIT_INDEX_FILE="$TMP_INDEX" &&
369 export GIT_INDEX_FILE &&
370 git diff --name-only -z HEAD |
371 git update-index -z --add --remove --stdin &&
372 git_write_tree &&
373 rm -f "$TMP_INDEX"
377 # get tree for arbitrary ref
378 get_tree_r()
380 echo "$1"
383 # strip_ref "$(git symbolic-ref HEAD)"
384 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
385 strip_ref()
387 case "$1" in
388 refs/"$topbases"/*)
389 echol "${1#refs/$topbases/}"
391 refs/heads/*)
392 echol "${1#refs/heads/}"
395 echol "$1"
396 esac
399 # pretty_tree [-t] NAME [-b | -i | -w | -r]
400 # Output tree ID of a cleaned-up tree without tg's artifacts.
401 # NAME will be ignored for -i and -w, but needs to be present
402 # With -r NAME must be a full ref name to a treeish (it's used as-is)
403 # If -t is used the tree is written into the alternate temporary objects area
404 pretty_tree()
406 use_alt_temp_odb=
407 [ "$1" != "-t" ] || { shift; use_alt_temp_odb=1; }
408 name="$1"
409 source="${2#?}"
410 git ls-tree --full-tree "$(get_tree_$source "$name")" |
411 sed -ne '/ \.top.*$/!p' |
412 git_mktree
415 # return an empty-tree root commit -- date is either passed in or current
416 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
417 # An invalid secs causes the current date to be used, an invalid zone offset
418 # causes +0000 to be used
419 make_empty_commit()
421 # the empty tree is guaranteed to always be there even in a repo with
422 # zero objects, but for completeness we force it to exist as a real object
423 SECS=
424 read -r SECS ZONE JUNK <<-EOT || :
427 case "$SECS" in *[!0-9]*) SECS=; esac
428 if [ -z "$SECS" ]; then
429 MTDATE="$(date '+%s %z')"
430 else
431 case "$ZONE" in
432 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
434 [01][0-9][0-5][0-9])
435 ZONE="+$ZONE"
438 ZONE="+0000"
439 esac
440 MTDATE="$SECS $ZONE"
442 EMPTYID="- <-> $MTDATE"
443 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
444 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
445 git hash-object -t commit -w --stdin
448 # standard input is a diff
449 # standard output is the "+" lines with leading "+ " removed
450 # beware that old lines followed by the dreaded '\ No newline at end of file'
451 # will appear to be new lines if lines are added after them
452 # the git diff --ignore-space-at-eol option can be used to prevent this
453 diff_added_lines()
455 awk '
456 BEGIN { in_hunk = 0; }
457 /^@@ / { in_hunk = 1; }
458 /^\+/ { if (in_hunk == 1) printf("%s\n", substr($0, 2)); }
459 !/^\\ No newline at end of file/ &&
460 /^[^@ +-]/ { in_hunk = 0; }
464 # $1 is name of new branch to create locally if all of these are true:
465 # a) exists as a remote TopGit branch for "$base_remote"
466 # b) the branch "name" does not have any invalid characters in it
467 # c) neither of the two branch refs (branch or base) exist locally
468 # returns success only if a new local branch was created (and dumps message)
469 auto_create_local_remote()
471 case "$1" in ""|*[" $tab$lf~^:\\*?["]*|.*|*/.*|*.|*./|/*|*/|*//*) return 1; esac
472 [ -n "$base_remote" ] &&
473 git update-ref --stdin <<-EOT >/dev/null 2>&1 &&
474 verify refs/remotes/$base_remote/${topbases#heads/}/$1 refs/remotes/$base_remote/${topbases#heads/}/$1
475 verify refs/remotes/$base_remote/$1 refs/remotes/$base_remote/$1
476 create refs/$topbases/$1 refs/remotes/$base_remote/${topbases#heads/}/$1^0
477 create refs/heads/$1 refs/remotes/$base_remote/$1^0
479 { init_reflog "refs/$topbases/$1" || :; } &&
480 info "topic branch '$1' automatically set up from remote '$base_remote'"
483 # setup_hook NAME
484 setup_hook()
486 setup_git_dir_is_bare
487 [ -z "$git_dir_is_bare" ] || return 0
488 tgname="${0##*/}"
489 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
490 if [ -f "$git_hooks_dir/$1" ] && grep -Fq "$hook_call" "$git_hooks_dir/$1"; then
491 # Another job well done!
492 return
494 # Prepare incantation
495 hook_chain=
496 if [ -s "$git_hooks_dir/$1" ] && [ -x "$git_hooks_dir/$1" ]; then
497 hook_call="$hook_call"' || exit $?'
498 if [ -L "$git_hooks_dir/$1" ] || ! sed -n 1p <"$git_hooks_dir/$1" | grep -Fqx "#!@SHELL_PATH@"; then
499 chain_num=
500 while [ -e "$git_hooks_dir/$1-chain$chain_num" ]; do
501 chain_num=$(( $chain_num + 1 ))
502 done
503 mv -f "$git_hooks_dir/$1" "$git_hooks_dir/$1-chain$chain_num"
504 hook_chain=1
506 else
507 hook_call="exec $hook_call"
508 [ -d "$git_hooks_dir" ] || mkdir -p "$git_hooks_dir" || :
510 # Don't call hook if tg is not installed
511 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
512 # Insert call into the hook
514 echol "#!@SHELL_PATH@"
515 echol "$hook_call"
516 if [ -n "$hook_chain" ]; then
517 echol "exec \"\$0-chain$chain_num\" \"\$@\""
518 else
519 [ ! -s "$git_hooks_dir/$1" ] || cat "$git_hooks_dir/$1"
521 } >"$git_hooks_dir/$1+"
522 chmod a+x "$git_hooks_dir/$1+"
523 mv "$git_hooks_dir/$1+" "$git_hooks_dir/$1"
526 # setup_ours (no arguments)
527 setup_ours()
529 setup_git_dir_is_bare
530 [ -z "$git_dir_is_bare" ] || return 0
531 if [ ! -s "$git_common_dir/info/attributes" ] || ! grep -q topmsg "$git_common_dir/info/attributes"; then
532 [ -d "$git_common_dir/info" ] || mkdir "$git_common_dir/info"
534 echo ".topmsg merge=ours"
535 echo ".topdeps merge=ours"
536 } >>"$git_common_dir/info/attributes"
538 if ! git config merge.ours.driver >/dev/null; then
539 git config merge.ours.name '"always keep ours" merge driver'
540 git config merge.ours.driver 'touch %A'
544 # measure_branch NAME [BASE] [EXTRAHEAD...]
545 measure_branch()
547 _bname="$1"; _base="$2"
548 shift; shift
549 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
550 # The caller should've verified $name is valid
551 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
552 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
553 if [ $_commits -ne 1 ]; then
554 _suffix="commits"
555 else
556 _suffix="commit"
558 echo "$_commits/$_nmcommits $_suffix"
561 # true if $1 is contained by (or the same as) $2
562 # this is never slower than merge-base --is-ancestor and is often slightly faster
563 contained_by()
565 [ "$(git rev-list --count --max-count=1 "$1" --not "$2" --)" = "0" ]
568 # branch_contains B1 B2
569 # Whether B1 is a superset of B2.
570 branch_contains()
572 _revb1="$(ref_exists_rev "$1")" || return 0
573 _revb2="$(ref_exists_rev "$2")" || return 0
574 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
575 if read _result _rev_matchb1 _rev_matchb2 &&
576 [ "$_revb1" = "$_rev_matchb1" ] && [ "$_revb2" = "$_rev_matchb2" ]; then
577 return $_result
578 fi <"$tg_cache_dir/$1/.bc/$2/.d"
580 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
581 _result=0
582 contained_by "$_revb2" "$_revb1" || _result=1
583 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
584 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
586 return $_result
589 create_ref_dirs()
591 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" ] && [ -s "$tg_ref_cache" ] || return 0
592 mkdir -p "$tg_tmp_dir/cached/refs"
593 awk '{x=$1; sub(/^refs\//,"",x); if (x != "") {gsub(/[^A-Za-z0-9\/_.+-]/,"\\\\&",x); print x;}}' <"$tg_ref_cache" |
595 cd "$tg_tmp_dir/cached/refs" &&
596 xargs mkdir -p
598 awk -v p="$tg_tmp_dir/cached/" '
599 NF == 2 &&
600 $1 ~ /^refs\/./ &&
601 $2 ~ /^[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]+$/ {
602 fn = p $1 "/.ref"
603 print "0 " $2 >fn
604 close(fn)
606 ' <"$tg_ref_cache"
607 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
610 # If the first argument is non-empty, stores "1" there if this call created the cache
611 v_create_ref_cache()
613 [ -n "$tg_ref_cache" ] && ! [ -s "$tg_ref_cache" ] || return 0
614 _remotespec=
615 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
616 [ -z "$1" ] || eval "$1=1"
617 git for-each-ref --format='%(refname) %(objectname)' \
618 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
619 create_ref_dirs
622 remove_ref_cache()
624 [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ] || return 0
625 >"$tg_ref_cache"
626 >"$tg_ref_cache_br"
627 >"$tg_ref_cache_rbr"
628 >"$tg_ref_cache_ann"
629 >"$tg_ref_cache_dep"
632 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
633 rev_parse()
635 rev_parse_code_=1
636 if [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
637 rev_parse_code_=0
638 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache" ||
639 rev_parse_code_=$?
641 [ $rev_parse_code_ -ne 0 ] && [ -z "$tg_ref_cache_only" ] || return $rev_parse_code_
642 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
645 # ref_exists_rev REF
646 # Whether REF is a valid ref name
647 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
648 # or, if $base_remote is set, refs/remotes/$base_remote/
649 # Caches result if $tg_read_only and outputs HASH on success
650 ref_exists_rev()
652 case "$1" in
653 refs/*)
655 $octet20)
656 printf '%s' "$1"
657 return;;
659 die "ref_exists_rev requires fully-qualified ref name (given: $1)"
660 esac
661 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
662 _result=
663 _result_rev=
664 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
665 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
666 _result=0
667 _result_rev="$(rev_parse "$1")" || _result=$?
668 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
669 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
670 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
671 printf '%s' "$_result_rev"
672 return $_result
675 # Same as ref_exists_rev but output is abbreviated hash
676 # Optional second argument defaults to --short but may be any --short=.../--no-short option
677 ref_exists_rev_short()
679 case "$1" in
680 refs/*)
682 $octet20)
685 die "ref_exists_rev_short requires fully-qualified ref name"
686 esac
687 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
688 _result=
689 _result_rev=
690 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
691 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
692 _result=0
693 _result_rev="$(rev_parse "$1")" || _result=$?
694 if [ $_result -eq 0 ]; then
695 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev^0" --)"
696 _result=$?
698 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
699 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
700 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
701 printf '%s' "$_result_rev"
702 return $_result
705 # ref_exists REF
706 # Whether REF is a valid ref name
707 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
708 # or, if $base_remote is set, refs/remotes/$base_remote/
709 # Caches result
710 ref_exists()
712 ref_exists_rev "$1" >/dev/null
715 # rev_parse_tree REF
716 # Runs git rev-parse REF^{tree}
717 # Caches result if $tg_read_only
718 rev_parse_tree()
720 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
721 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
722 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
723 printf '%s\n' "$_result"
724 return 0
726 return 1
728 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
729 if [ -d "$tg_tmp_dir/cached/$1" ]; then
730 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
731 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
732 printf '%s\n' "$_result"
733 return 0
735 return 1
737 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
740 # has_remote BRANCH
741 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
742 has_remote()
744 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
747 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
748 # If -z "$1" still set return code but do not return result
749 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
750 # refs/heads/... then ... will be verified instead.
751 # if "$3" = "-f" (for fail) then return an error rather than dying.
752 v_verify_topgit_branch()
754 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
755 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
756 [ -n "$_verifyname" ] || [ "$3" = "-f" ] || die "HEAD is not a symbolic ref"
757 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
758 [ "$3" != "-f" ] || return 1
759 die "HEAD is not a symbolic ref to the refs/heads namespace"
760 esac
761 set -- "$1" "$_verifyname" "$3"
763 case "$2" in
764 refs/"$topbases"/*)
765 _verifyname="${2#refs/$topbases/}"
767 refs/heads/*)
768 _verifyname="${2#refs/heads/}"
771 _verifyname="$2"
773 esac
774 if ! ref_exists "refs/heads/$_verifyname"; then
775 [ "$3" != "-f" ] || return 1
776 die "no such branch: $_verifyname"
778 if ! ref_exists "refs/$topbases/$_verifyname"; then
779 [ "$3" != "-f" ] || return 1
780 die "not a TopGit-controlled branch: $_verifyname"
782 [ -z "$1" ] || eval "$1="'"$_verifyname"'
785 # Return the verified TopGit branch name or die with an error.
786 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
787 # refs/heads/... then ... will be verified instead.
788 # if "$2" = "-f" (for fail) then return an error rather than dying.
789 verify_topgit_branch()
791 v_verify_topgit_branch _verifyname "$@" || return
792 printf '%s' "$_verifyname"
795 # Caches result
796 # $1 = branch name (i.e. "t/foo/bar")
797 # $2 = optional result of rev-parse "refs/heads/$1"
798 # $3 = optional result of rev-parse "refs/$topbases/$1"
799 branch_annihilated()
801 _branch_name="$1"
802 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
803 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
805 _result=
806 _result_rev=
807 _result_rev_base=
808 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/refs/heads/$_branch_name/.ann"; } 2>/dev/null || :
809 [ -z "$_result" ] || [ "$_result_rev" != "$_rev" ] || [ "$_result_rev_base" != "$_rev_base" ] || return $_result
811 # use the merge base in case the base is ahead.
812 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
814 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
815 _result=$?
816 [ -d "$tg_cache_dir/refs/heads/$_branch_name" ] || mkdir -p "$tg_cache_dir/refs/heads/$_branch_name" 2>/dev/null
817 [ ! -d "$tg_cache_dir/refs/heads/$_branch_name" ] ||
818 echo $_result $_rev $_rev_base >"$tg_cache_dir/refs/heads/$_branch_name/.ann" 2>/dev/null || :
819 return $_result
822 non_annihilated_branches()
824 refscacheopt="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
825 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
826 refscacheopt="$refscacheopt"'-r="$tg_ref_cache" "refs/$topbases"'
828 eval run_awk_topgit_branches -n "$refscacheopt" '"refs/$topbases" "$@"'
831 # Make sure our tree is clean
832 # if optional "$1" given also verify that a checkout to "$1" would succeed
833 ensure_clean_tree()
835 check_status
836 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
837 git update-index --ignore-submodules --refresh ||
838 die "the working directory has uncommitted changes (see above) - first commit or reset them"
839 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
840 die "the index has uncommited changes"
841 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
842 die "git checkout \"$1\" would fail"
845 # Make sure .topdeps and .topmsg are "clean"
846 # They are considered "clean" if each is identical in worktree, index and HEAD
847 # With "-u" as the argument skip the HEAD check (-u => unborn)
848 # untracked .topdeps and/or .topmsg files are always considered "dirty" as well
849 # with -u them just existing constitutes "dirty"
850 ensure_clean_topfiles()
852 _dirtw=0
853 _dirti=0
854 _dirtu=0
855 _check="$(git diff-files --ignore-submodules --name-only -- :/.topdeps :/.topmsg)" &&
856 [ -z "$_check" ] || _dirtw=1
857 if [ "$1" != "-u" ]; then
858 _check="$(git diff-index --cached --ignore-submodules --name-only HEAD -- :/.topdeps :/.topmsg)" &&
859 [ -z "$_check" ] || _dirti=1
861 if [ "$_dirti$_dirtw" = "00" ]; then
862 v_get_show_cdup
863 if [ -e "${git_cdup_result}.topdeps" ] || [ -e "${git_cdup_result}.topmsg" ]; then
864 [ "$1" != "-u" ] &&
865 _check="$(git status --porcelain --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg)" &&
866 [ -z "$_check" ] || _dirtu=1
869 if [ "$_dirtu$_dirti$_dirtw" != "000" ]; then
870 git status --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg || :
871 case "$_dirtu$_dirti$_dirtw" in
872 001) die "the working directory has uncommitted changes (see above) - first commit or reset them";;
873 010) die "the index has uncommited changes (see above)";;
874 011) die "the working directory and index have uncommitted changes (see above) - first commit or reset them";;
875 100) die "the working directory has untracked files that would be overwritten (see above)";;
876 esac
880 # is_sha1 REF
881 # Whether REF is a SHA1 (compared to a symbolic name).
882 is_sha1()
884 case "$1" in $octet20) return 0;; esac
885 return 1
888 # navigate_deps <run_awk_topgit_navigate options and arguments>
889 # all options and arguments are passed through to run_awk_topgit_navigate
890 # except for a leading -td= option, if any, which is picked off for deps
891 # after arranging to feed it a suitable deps list
892 navigate_deps()
894 dogfer=
895 dorad=1
896 userc=
897 tmpdep=
898 ratd_opts="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
899 ratn_opts=
900 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
901 userc=1
902 tmprfs="$tg_ref_cache"
903 tmptgbr="$tg_ref_cache_br"
904 tmpann="$tg_ref_cache_ann"
905 tmpdep="$tg_ref_cache_dep"
906 [ -s "$tg_ref_cache" ] || dogfer=1
907 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
908 else
909 ratd_opts="${ratd_opts}-rmr"
910 ratn_opts="-rma -rmb"
911 tmprfs="$tg_tmp_dir/refs.$$"
912 tmpann="$tg_tmp_dir/ann.$$"
913 tmptgbr="$tg_tmp_dir/tgbr.$$"
914 dogfer=1
916 refpats="\"refs/heads\" \"refs/\$topbases\""
917 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
918 [ -z "$dogfer" ] ||
919 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
920 depscmd="run_awk_topgit_deps $ratd_opts"
921 case "$1" in -td=*)
922 userc=
923 depscmd="$depscmd $1"
924 shift
925 esac
926 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -s "refs/$topbases"'
927 if [ -n "$userc" ]; then
928 if [ -n "$dorad" ]; then
929 eval "$depscmd" >"$tmpdep"
931 depscmd='<"$tmpdep" '
932 else
933 depscmd="$depscmd |"
935 eval "$depscmd" run_awk_topgit_navigate '-a="$tmpann" -b="$tmptgbr"' "$ratn_opts" '"$@"'
938 # recurse_deps_internal NAME [BRANCHPATH...]
939 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
940 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
941 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
942 # (but missing and remotes are always "0")
943 # followed by a 0 for no excess visits or a positive number of excess visits
944 # then the branch name followed by its depedency chain (which might be empty)
945 # An output line might look like this:
946 # 0 1 1 0 t/foo/leaf t/foo/int t/stage
947 # If no_remotes is non-empty, exclude remotes
948 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
949 # If with_top_level is non-empty, include the top-level that's normally omitted
950 # any branch names in the space-separated recurse_deps_exclude variable
951 # are skipped (along with their dependencies)
952 recurse_deps_internal()
954 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
955 ratr_opts="${recurse_preorder:+-f} ${with_top_level:+-s}"
956 dogfer=
957 dorad=1
958 userc=
959 tmpdep=
960 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
961 userc=1
962 tmprfs="$tg_ref_cache"
963 tmptgbr="$tg_ref_cache_br"
964 tmpann="$tg_ref_cache_ann"
965 tmpdep="$tg_ref_cache_dep"
966 [ -s "$tg_ref_cache" ] || dogfer=1
967 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
968 else
969 ratr_opts="$ratr_opts -rmh -rma -rmb"
970 tmprfs="$tg_tmp_dir/refs.$$"
971 tmpann="$tg_tmp_dir/ann.$$"
972 tmptgbr="$tg_tmp_dir/tgbr.$$"
973 dogfer=1
975 refpats="\"refs/heads\" \"refs/\$topbases\""
976 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
977 tmptgrmtbr=
978 dorab=1
979 if [ -z "$no_remotes" ] && [ -n "$base_remote" ]; then
980 if [ -n "$userc" ]; then
981 tmptgrmtbr="$tg_ref_cache_rbr"
982 [ -n "$dogfer" ] || ! [ -s "$tmptgrmtbr" ] || dorab=
983 else
984 tmptgrmtbr="$tg_tmp_dir/tgrmtbr.$$"
985 ratr_opts="$ratr_opts -rmr"
987 ratr_opts="$ratr_opts -r=\"\$tmptgrmtbr\" -u=\":refs/remotes/\$base_remote/\${topbases#heads/}\""
989 [ -z "$dogfer" ] ||
990 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
991 if [ -n "$tmptgrmtbr" ] && [ -n "$dorab" ]; then
992 run_awk_topgit_branches -n -h="refs/remotes/$base_remote" -r="$tmprfs" \
993 "refs/remotes/$base_remote/${topbases#heads/}" >"$tmptgrmtbr"
995 depscmd="run_awk_topgit_deps -s${TG_DEBUG:+ -p=\"\$tg_ref_cache.pre\"}"
996 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" "refs/$topbases"'
997 if [ -n "$userc" ]; then
998 if [ -n "$dorad" ]; then
999 eval "$depscmd" >"$tmpdep"
1001 depscmd='<"$tmpdep" '
1002 else
1003 depscmd="$depscmd |"
1005 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
1006 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
1009 # do_eval CMD
1010 # helper for recurse_deps so that a return statement executed inside CMD
1011 # does not return from recurse_deps. This shouldn't be necessary, but it
1012 # seems that it actually is.
1013 do_eval()
1015 eval "$@"
1018 # becomes read-only for caching purposes
1019 # assigns new value to tg_read_only
1020 # become_cacheable/undo_become_cacheable calls may be nested
1021 become_cacheable()
1023 _old_tg_read_only="$tg_read_only"
1024 if [ -z "$tg_read_only" ]; then
1025 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1026 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1027 tg_read_only=1
1029 _my_ref_cache=
1030 v_create_ref_cache _my_ref_cache
1031 _my_ref_cache="${_my_ref_cache:+1}"
1032 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
1035 # restores tg_read_only and ref_cache to state before become_cacheable call
1036 # become_cacheable/undo_bocome_cacheable calls may be nested
1037 undo_become_cacheable()
1039 case "$tg_read_only" in
1040 "undo"[01]"-"*)
1041 _suffix="${tg_read_only#undo?-}"
1042 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
1043 tg_read_only="$_suffix"
1044 esac
1047 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
1048 become_non_cacheable()
1050 remove_ref_cache
1051 tg_read_only=
1052 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1053 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1056 # call this to make sure the current Git repository has an associated work tree
1057 # also make sure we are not in wayback mode
1058 ensure_work_tree()
1060 [ -z "$wayback" ] ||
1061 die "the wayback machine cannot be used with the specified options"
1062 setup_git_dir_is_bare
1063 [ -n "$git_dir_is_bare" ] || return 0
1064 die "This operation must be run in a work tree"
1067 # call this to make sure Git will not complain about a missing user/email
1068 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
1069 ensure_ident_available()
1071 [ -z "$TG_IDENT_CHECKED" ] || return 0
1072 git var GIT_AUTHOR_IDENT >/dev/null &&
1073 git var GIT_COMMITTER_IDENT >/dev/null || exit
1074 TG_IDENT_CHECKED=1
1075 export TG_IDENT_CHECKED
1076 return 0
1079 # recurse_deps [-o=<options string>] CMD NAME [BRANCHPATH...]
1080 # Recursively eval CMD on all dependencies of NAME.
1081 # Dependencies are visited in topological order.
1082 # If <options string> is given, it's eval'd into the recurse_deps_internal
1083 # call just before the "--" that's passed just before NAME
1084 # CMD can refer to the following variables:
1086 # _ret starts as 0; CMD can change; will be final return result
1087 # _dep bare branch name or ":refs/remotes/..." for a remote
1088 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
1089 # _depchain 0+ space-sep branch names (_name first) form a path to top
1090 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
1091 # _dep_is_leaf boolean "1" if leaf; "" if not
1092 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
1093 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
1094 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
1095 # _dep_xvisits non-negative integer number of excess visits (often 0)
1097 # CMD may use a "return" statement without issue; its return value is ignored,
1098 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
1099 # will stop immediately and the value with the leading "-" stripped off will
1100 # be the final result code
1102 # CMD can refer to $_name for queried branch name,
1103 # $_dep for dependency name,
1104 # $_depchain for space-seperated branch backtrace,
1105 # $_dep_missing boolean to check whether $_dep is present
1106 # and the $_dep_is_tgish and $_dep_annihilated booleans.
1107 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
1108 # It can modify $_ret to affect the return value
1109 # of the whole function.
1110 # If recurse_deps() hits missing dependencies, it will append
1111 # them to space-separated $missing_deps list and skip them
1112 # after calling CMD with _dep_missing set.
1113 # remote dependencies are processed if no_remotes is unset.
1114 # any branch names in the space-separated recurse_deps_exclude variable
1115 # are skipped (along with their dependencies)
1117 # If no_remotes is non-empty, exclude remotes
1118 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1119 # If with_top_level is non-empty, include the top-level that's normally omitted
1120 # any branch names in the space-separated recurse_deps_exclude variable
1121 # are skipped (along with their dependencies)
1122 recurse_deps()
1124 _opts=
1125 case "$1" in -o=*) _opts="${1#-o=}"; shift; esac
1126 _cmd="$1"; shift
1128 _depsfile="$(get_temp tg-depsfile)"
1129 eval recurse_deps_internal "$_opts" -- '"$@"' >"$_depsfile" || :
1131 _ret=0
1132 while read _ismissing _istgish _isleaf _dep_xvisits _dep _name _deppath; do
1133 _depchain="$_name${_deppath:+ $_deppath}"
1134 _dep_is_tgish=
1135 [ "$_istgish" = "0" ] || _dep_is_tgish=1
1136 _dep_has_remote=
1137 [ "$_istgish" != "2" ] || _dep_has_remote=1
1138 _dep_missing=
1139 if [ "$_ismissing" != "0" ]; then
1140 _dep_missing=1
1141 case " $missing_deps " in *" $_dep "*);;*)
1142 missing_deps="${missing_deps:+$missing_deps }$_dep"
1143 esac
1145 _dep_annihilated=
1146 _dep_is_leaf=
1147 if [ "$_isleaf" = "1" ]; then
1148 _dep_is_leaf=1
1149 elif [ "$_isleaf" = "2" ]; then
1150 _dep_annihilated=1
1152 do_eval "$_cmd" || :
1153 if [ "${_ret#-}" != "$_ret" ]; then
1154 _ret="${_ret#-}"
1155 break
1157 done <"$_depsfile"
1158 rm -f "$_depsfile"
1159 return ${_ret:-0}
1162 # find_leaves NAME
1163 # output (one per line) the unique leaves of NAME
1164 # a leaf is either
1165 # 1) a non-tgish dependency
1166 # 2) the base of a tgish dependency with no non-annihilated dependencies
1167 # duplicates are suppressed (by commit rev) and remotes are always ignored
1168 # if a leaf has an exact tag match that will be output
1169 # note that recurse_deps_exclude IS honored for this operation
1170 find_leaves()
1172 no_remotes=1
1173 with_top_level=1
1174 recurse_preorder=
1175 seen_leaf_refs=
1176 seen_leaf_revs=
1177 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1178 [ "$_isleaf" = "1" ] && [ "$_ismissing" = "0" ] || continue
1179 if [ "$_istgish" != "0" ]; then
1180 fulldep="refs/$topbases/$_dep"
1181 else
1182 fulldep="refs/heads/$_dep"
1184 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1185 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1186 if fullrev="$(ref_exists_rev "$fulldep")"; then
1187 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1188 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1189 # See if Git knows it by another name
1190 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1191 echo "refs/tags/$tagname"
1192 else
1193 echo "$fulldep"
1195 esac
1197 esac
1198 done <<-EOT
1199 $(recurse_deps_internal -l -o=1 -- "$1")
1201 with_top_level=
1204 # branch_needs_update
1205 # This is a helper function for determining whether given branch
1206 # is up-to-date wrt. its dependencies. It expects input as if it
1207 # is called as a recurse_deps() helper.
1208 # In case the branch does need update, it will echo it together
1209 # with the branch backtrace on the output (see needs_update()
1210 # description for details) and set $_ret to non-zero.
1211 branch_needs_update()
1213 if [ -n "$_dep_missing" ]; then
1214 echo "! $_dep $_depchain"
1215 return 0
1218 if [ -n "$_dep_is_tgish" ]; then
1219 [ -z "$_dep_annihilated" ] || return 0
1221 if [ -n "$_dep_has_remote" ]; then
1222 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" || {
1223 echo ":refs/remotes/$base_remote/$_dep $_dep $_depchain"
1224 _ret=1
1227 # We want to sync with our base first and should output this before
1228 # the remote branch, but the order does not actually matter to tg-update
1229 # as it just recurses regardless, but it does matter for tg-info (which
1230 # treats out-of-date bases as though they were already merged in) so
1231 # we output the remote before the base.
1232 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1233 echo ": $_dep $_depchain"
1234 _ret=1
1235 return
1239 if [ -n "$_name" ]; then
1240 case "$_dep" in :*) _fulldep="${_dep#:}";; *) _fulldep="refs/heads/$_dep";; esac
1241 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1242 # Some new commits in _dep
1243 echo "$_dep $_depchain"
1244 _ret=1
1249 # needs_update NAME
1250 # This function is recursive; it outputs reverse path from NAME
1251 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1252 # inner paths first. Innermost name can be :refs/remotes/<remote>/<name>
1253 # if the head is not in sync with the <remote> branch <name>, ':' if
1254 # the head is not in sync with the base (in this order of priority)
1255 # or '!' if dependency is missing. Note that the remote branch, base
1256 # order is reversed from the order they will actually be updated in
1257 # order to accomodate tg info which treats out-of-date items that are
1258 # only in the base as already being in the head for status purposes.
1259 # It will also return non-zero status if NAME needs update (seems backwards
1260 # but think of it as non-zero status if any non-missing output lines produced)
1261 # If needs_update() hits missing dependencies, it will append
1262 # them to space-separated $missing_deps list and skip them.
1263 needs_update()
1265 recurse_deps branch_needs_update "$1"
1268 # append second arg to first arg variable gluing with space if first already set
1269 vplus()
1271 eval "$1=\"\${$1:+\$$1 }\$2\""
1274 # true if whitespace separated first var name list contains second arg
1275 # use `vcontains 3 "value" "some list"` for a literal list
1276 vcontains()
1278 eval case "\" \${$1} \"" in '*" $2 "*) return 0; esac; return 1'
1281 # if the $1 var does not already contain $2 it's appended
1282 vsetadd()
1284 vcontains "$1" "$2" || vplus "$1" "$2"
1287 # reset needs_update_check results to empty
1288 needs_update_check_clear()
1290 unset_ needs_update_processed needs_update_behind needs_update_ahead needs_update_partial
1293 # needs_update_check NAME...
1295 # A faster version of needs_update that always succeeds
1296 # No output and unsuitable for actually performing updates themselves
1297 # If any of NAME... are NOT up-to-date AND they were not already processed
1298 # return status always will be zero however a simple check of
1299 # needs_update_behind after the call will answer the:
1300 # "are any out of date?": test -n "$needs_update_behind"
1301 # "is <x> out of date?": vcontains needs_update_behind "<x>"
1303 # Note that results are cumulative and "no_remotes" is honored as well as other
1304 # variables that modify recurse_deps_internal behavior. See the preceding
1305 # function to reset the results to empty when accumulation should start over.
1307 # Unlike needs_update, the branch names are themselves also checked to see if
1308 # they are out-of-date with respect to their bases or remote branches (not just
1309 # their remote bases). However, this can muddy some status results so this
1310 # can be disabled by setting needs_update_check_no_self to a non-empty value.
1312 # Unlike needs_update, here the remote base check is handled together with the
1313 # remote head check so if one is modified the other is too in the same way.
1315 # Dependencies are normally considered "behind" if they need an update from
1316 # their base or remote but this can be suppressed by setting the
1317 # needs_update_check_no_same to a non-empty value. This will NOT prevent
1318 # parents of those dependencies from still being considered behind in such a
1319 # case even though the dependency itself will not be. Note that setting
1320 # needs_update_check_no_same also implies needs_update_check_no_self.
1322 # The following whitespace-separated lists are updated with the results:
1324 # The "no_remotes" setting is obeyed but remote names themselves will never
1325 # appear in any of the lists
1327 # needs_update_processed
1328 # The branch names in here have been processed and will be skipped
1330 # needs_update_behind
1331 # Any branch named in here needs an update from one or more of its
1332 # direct or indirect dependencies (i.e. it's "out-of-date")
1334 # needs_update_ahead
1335 # Any branch named in here is NOT fully contained by at least one of
1336 # its dependents (i.e. it's a source of "out-of-date (aka dirty)"ness
1338 # needs_update_partial
1339 # Any branch names in here are either missing themselves or have one
1340 # or more detected missing dependencies (a completely missing remote
1341 # branch is never "detected")
1342 needs_update_check()
1344 # each head must be processed independently or else there will be
1345 # confusion about who's missing what and which branches actually are
1346 # out of date
1347 tmptgrdi="$tg_tmp_dir/tgrdi.$$"
1348 for nucname in "$@"; do
1349 ! vcontains needs_update_processed "$nucname" || continue
1350 # no need to fuss with recurse_deps, just use
1351 # recurse_deps_internal directly
1352 recurse_deps_internal -s -o=-1 "$nucname" >"$tmptgrdi"
1353 while read -r _rdi_m _rdi_t _rdi_l _rdi_v _rdi_node _rdi_parent _rdi_chain; do
1354 case "$_rdi_node" in ""|:*) continue; esac # empty or checked with remote
1355 vsetadd needs_update_processed "$_rdi_node"
1356 if [ "$_rdi_m" != "0" ]; then # missing
1357 vsetadd needs_update_partial "$_rdi_node"
1358 [ -z "$_rdi_parent" ] || vsetadd needs_update_partial "$_rdi_parent"
1359 continue
1361 [ "$_rdi_t$_rdi_l" != "12" ] || continue # always skip annihilated
1362 _rdi_dertee= # :)
1363 if [ -n "$_rdi_parent" ]; then # not a "self" line
1364 ! vcontains needs_update_partial "$_rdi_node" || vsetadd needs_update_partial "$_rdi_parent"
1365 ! vcontains needs_update_behind "$_rdi_node" || _rdi_dertee=2
1366 else
1367 [ -z "$needs_update_check_no_self$needs_update_check_no_same" ] || continue # skip self
1369 if [ -z "$_rdi_dertee" ]; then
1370 if [ "$_rdi_t" != "0" ]; then # tgish
1371 if branch_contains "refs/heads/$_rdi_node" "refs/$topbases/$_rdi_node"; then
1372 if [ "$_rdi_t" = "2" ]; then # will never be "2" when no_remotes is set
1373 branch_contains "refs/heads/$_rdi_node" "refs/remotes/$base_remote/$_rdi_node" &&
1374 branch_contains "refs/$topbases/$_rdi_node" "refs/remotes/$base_remote/${topbases#heads/}/$_rdi_node" ||
1375 _rdi_dertee=3
1377 else
1378 _rdi_dertee=3
1380 [ -z "$_rdi_dertee" ] || [ -n "$needs_update_check_no_same" ] || _rdi_dertee=1
1383 [ z"$_rdi_dertee" != z"1" ] || vsetadd needs_update_behind "$_rdi_node"
1384 [ -n "$_rdi_parent" ] || continue # self line
1385 if ! branch_contains "refs/$topbases/$_rdi_parent" "refs/heads/$_rdi_node"; then
1386 _rdi_dertee=1
1387 vsetadd needs_update_ahead "$_rdi_node"
1389 [ -z "$_rdi_dertee" ] || vsetadd needs_update_behind "$_rdi_parent"
1390 done <"$tmptgrdi"
1391 done
1394 # branch_empty NAME [-i | -w]
1395 branch_empty()
1397 if [ -z "$2" ]; then
1398 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1399 _result=
1400 _result_rev=
1401 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1402 [ -z "$_result" ] || [ "$_result_rev" != "$_rev" ] || return $_result
1403 _result=0
1404 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1405 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1406 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1407 return $_result
1408 else
1409 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1413 v_get_tdmopt_internal()
1415 [ -n "$1" ] && [ -n "$3" ] || return 0
1416 [ "$2" = "-i" ] || [ "$2" = "-w" ] || return 0
1417 ensure_work_tree
1418 _optval=
1419 if v_verify_topgit_branch _tghead "HEAD" -f; then
1420 if [ "$2" = "-w" ] && [ -f "$root_dir/$3" ] && [ -r "$root_dir/$3" ]; then
1421 _opthash=
1422 if _opthash="$(git hash-object -w -t blob --stdin <"$root_dir/$3")" && [ -n "$_opthash" ]; then
1423 _optval="$4\"$_tghead:$_opthash\""
1425 elif [ "$2" = "-i" ]; then
1426 if _opthash="$(git rev-parse --quiet --verify ":0:$3" --)" && [ -n "$_opthash" ]; then
1427 _optval="$4\"$_tghead:$_opthash\""
1431 eval "$1="'"$_optval"'
1434 # set var $1 to the correct -td= option for use in an eval for $2 -i or -w mode
1435 v_get_tdopt() { v_get_tdmopt_internal "$1" "$2" ".topdeps" "-td="; }
1437 # set var $1 to the correct -tm= option for use in an eval for $2 -i or -w mode
1438 v_get_tmopt() { v_get_tdmopt_internal "$1" "$2" ".topmsg" "-tm="; }
1440 # checkout_symref_full [-f] FULLREF [SEED]
1441 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1442 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1443 # MUST be a committish which if present will be used instead of current FULLREF
1444 # (and FULLREF will be updated to it as well in that case)
1445 # Any merge state is always cleared by this function
1446 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1447 # instead of -m) but it will clear out any unmerged entries
1448 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1449 checkout_symref_full()
1451 _mode=-m
1452 _head="HEAD"
1453 if [ "$1" = "-f" ]; then
1454 _mode="--reset"
1455 _head=
1456 shift
1458 _ishash=
1459 case "$1" in
1460 refs/?*)
1462 $octet20)
1463 _ishash=1
1464 [ -z "$2" ] || [ "$1" = "$2" ] ||
1465 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1466 set -- HEAD "$1"
1469 die "programmer error: invalid checkout_symref_full \"$1\""
1471 esac
1472 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1473 die "invalid committish: \"${2:-$1}\""
1474 # Clear out any MERGE_HEAD kruft
1475 rm -f "$git_dir/MERGE_HEAD" || :
1476 # We have to do all the hard work ourselves :/
1477 # This is like git checkout -b "$1" "$2"
1478 # (or just git checkout "$1"),
1479 # but never creates a detached HEAD (unless $1 is a hash)
1480 git read-tree -u $_mode $_head "$_seedrev" &&
1482 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1483 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1484 } && {
1485 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1489 # switch_to_base NAME [SEED]
1490 switch_to_base()
1492 checkout_symref_full "refs/$topbases/$1" "$2"
1495 # run editor with arguments
1496 # the editor setting will be cached in $tg_editor (which is eval'd)
1497 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1498 # just in case, noalt_setup will be in effect while the editor is running
1499 run_editor()
1501 tg_editor="$GIT_EDITOR"
1502 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1504 noalt_setup
1505 eval "$tg_editor" '"$@"'
1509 # Show the help messages.
1510 do_help()
1512 _www=
1513 if [ "$1" = "-w" ]; then
1514 _www=1
1515 shift
1517 if [ "$1" = "st" ]; then
1518 shift
1519 set -- "status" "$@"
1521 if [ -z "$1" ] ; then
1522 # This is currently invoked in all kinds of circumstances,
1523 # including when the user made a usage error. Should we end up
1524 # providing more than a short help message, then we should
1525 # differentiate.
1526 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1528 ## Build available commands list for help output
1530 cmds=
1531 sep=
1532 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1533 ! [ -r "$cmd" ] && continue
1534 # strip directory part and "tg-" prefix
1535 cmd="${cmd##*/}"
1536 cmd="${cmd#tg-}"
1537 [ "$cmd" != "migrate-bases" ] || continue
1538 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1539 cmds="$cmds$sep$cmd"
1540 sep="|"
1541 done
1543 echo "TopGit version $TG_VERSION - A different patch queue manager"
1544 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u]" \
1545 "[-c <name>=<val>] [--[no-]pager|-p] [-w [:]<tgtag>] ($cmds) ..."
1546 echo " Or: $tgname help [-w] [<command>]"
1547 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1548 elif [ -r "$TG_INST_CMDDIR"/tg-$1 ] || [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1549 if [ -n "$_www" ]; then
1550 nohtml=
1551 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1552 echo "${0##*/}: missing html help file:" \
1553 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1554 nohtml=1
1556 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1557 echo "${0##*/}: missing html help file:" \
1558 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1559 nohtml=1
1561 if [ -n "$nohtml" ]; then
1562 echo "${0##*/}: use" \
1563 "\"${0##*/} help $1\" instead" 1>&2
1564 exit 1
1566 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1567 exit
1569 output()
1571 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1572 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1573 echo
1574 elif [ "$1" = "help" ]; then
1575 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1576 echo
1577 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1578 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1579 echo
1581 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1582 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1585 page output "$1"
1586 else
1587 echo "${0##*/}: no help for $1" 1>&2
1588 do_help
1589 exit 1
1593 check_status()
1595 git_state=
1596 git_remove=
1597 tg_state=
1598 tg_remove=
1599 tg_topmerge=
1600 setup_git_dir_is_bare
1601 [ -z "$git_dir_is_bare" ] || return 0
1603 if [ -e "$git_dir/MERGE_HEAD" ]; then
1604 git_state="merge"
1605 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1606 git_state="am"
1607 git_remove="$git_dir/rebase-apply"
1608 elif [ -e "$git_dir/rebase-apply" ]; then
1609 git_state="rebase"
1610 git_remove="$git_dir/rebase-apply"
1611 elif [ -e "$git_dir/rebase-merge" ]; then
1612 git_state="rebase"
1613 git_remove="$git_dir/rebase-merge"
1614 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1615 git_state="cherry-pick"
1616 elif [ -e "$git_dir/BISECT_LOG" ]; then
1617 git_state="bisect"
1618 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1619 git_state="revert"
1621 git_remove="${git_remove#./}"
1623 if [ -e "$git_dir/tg-update" ]; then
1624 tg_state="update"
1625 tg_remove="$git_dir/tg-update"
1626 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1628 tg_remove="${tg_remove#./}"
1631 # Show status information
1632 do_status()
1634 do_status_result=0
1635 do_status_verbose=
1636 do_status_help=
1637 abbrev=refs
1638 pfx=
1639 while [ $# -gt 0 ] && case "$1" in
1640 --help|-h)
1641 do_status_help=1
1642 break;;
1643 -vv)
1644 # kludge in this common bundling option
1645 abbrev=
1646 do_status_verbose=1
1647 pfx="## "
1649 --verbose|-v)
1650 [ -z "$do_status_verbose" ] || abbrev=
1651 do_status_verbose=1
1652 pfx="## "
1654 --exit-code)
1655 do_status_result=2
1658 die "unknown status argument: $1"
1660 esac; do shift; done
1661 if [ -n "$do_status_help" ]; then
1662 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1663 return
1665 check_status
1666 symref="$(git symbolic-ref --quiet HEAD)" || :
1667 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1668 if [ -n "$symref" ]; then
1669 uprefpart=
1670 if [ -n "$headrv" ]; then
1671 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1672 if [ -n "$upref" ]; then
1673 uprefpart=" ... ${upref#$abbrev/remotes/}"
1674 mbase="$(git merge-base HEAD "$upref")" || :
1675 ahead="$(git rev-list --count HEAD ${mbase:+--not} $mbase)" || ahead=0
1676 behind="$(git rev-list --count "$upref" ${mbase:+--not} $mbase)" || behind=0
1677 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1678 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1679 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1680 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1681 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1684 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1685 else
1686 echol "${pfx}HEAD -> ${headrv:-?}"
1688 if [ -n "$tg_state" ]; then
1689 extra=
1690 if [ "$tg_state" = "update" ]; then
1691 IFS= read -r uname <"$git_dir/tg-update/name" || :
1692 [ -z "$uname" ] ||
1693 extra="; currently updating branch '$uname'"
1695 echol "${pfx}tg $tg_state in progress$extra"
1696 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1697 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1698 cat "$git_dir/tg-update/fullcmd"
1699 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1700 if [ $bcnt -gt 1 ]; then
1701 pcnt=0
1702 ! [ -s "$git_dir/tg-update/processed" ] ||
1703 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1704 echo "${pfx}$pcnt of $bcnt branches updated so far"
1707 if [ "$tg_state" = "update" ]; then
1708 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1709 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1710 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1711 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1714 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1715 if [ "$git_state" = "merge" ]; then
1716 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1717 if [ $ucnt -gt 0 ]; then
1718 echo "${pfx}"'fix conflicts and then "git commit" the result'
1719 else
1720 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1723 if [ -z "$git_state" ]; then
1724 setup_git_dir_is_bare
1725 [ -z "$git_dir_is_bare" ] || return 0
1726 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository???
1727 gspcnt=0
1728 [ -z "$gsp" ] ||
1729 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1730 untr=
1731 if [ "$gspcnt" -eq 0 ]; then
1732 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1733 echo "${pfx}working directory is clean$untr"
1734 [ -n "$tg_state" ] || do_status_result=0
1735 else
1736 echo "${pfx}working directory is DIRTY"
1737 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1742 ## Pager stuff
1744 # isatty FD
1745 isatty()
1747 test -t $1
1750 # pass "diff" to get pager.diff
1751 # if pager.$1 is a boolean false returns cat
1752 # if set to true or unset fails
1753 # otherwise succeeds and returns the value
1754 get_pager()
1756 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1757 [ "$_x" != "true" ] || return 1
1758 echo "cat"
1759 return 0
1761 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1762 echol "$_x"
1763 return 0
1765 return 1
1768 # setup_pager
1769 # Set TG_PAGER to a valid executable
1770 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1771 # See also the following "page" function for ease of use
1772 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1773 # Preference is (same as Git):
1774 # 1. GIT_PAGER
1775 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1776 # 3. core.pager (only if set)
1777 # 4. PAGER
1778 # 5. git var GIT_PAGER
1779 # 6. less
1780 setup_pager()
1782 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1784 emptypager=
1785 if [ -z "$TG_PAGER_IN_USE" ]; then
1786 # TG_PAGER = GIT_PAGER | PAGER | less
1787 # NOTE: GIT_PAGER='' is significant
1788 if [ -n "${GIT_PAGER+set}" ]; then
1789 TG_PAGER="$GIT_PAGER"
1790 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1791 TG_PAGER="$_dp"
1792 elif _cp="$(git config core.pager 2>/dev/null)"; then
1793 TG_PAGER="$_cp"
1794 elif [ -n "${PAGER+set}" ]; then
1795 TG_PAGER="$PAGER"
1796 else
1797 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1798 [ "$_gp" != ":" ] || _gp=
1799 TG_PAGER="${_gp:-less}"
1801 if [ -z "$TG_PAGER" ]; then
1802 emptypager=1
1803 TG_PAGER=cat
1805 else
1806 emptypager=1
1807 TG_PAGER=cat
1810 # Set pager default environment variables
1811 # see pager.c:setup_pager
1812 if [ -z "${LESS+set}" ]; then
1813 LESS="-FRX"
1814 export LESS
1816 if [ -z "${LV+set}" ]; then
1817 LV="-c"
1818 export LV
1821 # this is needed so e.g. $(git diff) will still colorize it's output if
1822 # requested in ~/.gitconfig with color.diff=auto
1823 GIT_PAGER_IN_USE=1
1824 export GIT_PAGER_IN_USE
1826 # this is needed so we don't get nested pagers
1827 TG_PAGER_IN_USE=1
1828 export TG_PAGER_IN_USE
1831 # page eval_arg [arg ...]
1833 # Calls setup_pager then evals the first argument passing it all the rest
1834 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1835 # by setup_pager (in which case the output is left as-is).
1837 # To handle arbitrary paging duties, collect lines to be paged into a
1838 # function and then call page with the function name or perhaps func_name "$@".
1840 # If no arguments at all are passed in do nothing (return with success).
1841 page()
1843 [ $# -gt 0 ] || return 0
1844 setup_pager
1845 _evalarg="$1"; shift
1846 if [ -n "$emptypager" ]; then
1847 eval "$_evalarg" '"$@"'
1848 else
1849 { eval "$_evalarg" '"$@"';} | eval "$TG_PAGER"
1853 # get_temp NAME [-d]
1854 # creates a new temporary file (or directory with -d) in the global
1855 # temporary directory $tg_tmp_dir with pattern prefix NAME
1856 get_temp()
1858 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1861 # automatically called by strftime
1862 # does nothing if already setup
1863 # may be called explicitly if the first call would otherwise be in a subshell
1864 # so that the setup is only done once before subshells start being spawned
1865 setup_strftime()
1867 [ -z "$strftime_is_setup" ] || return 0
1869 # date option to format raw epoch seconds values
1870 daterawopt=
1871 _testes='951807788'
1872 _testdt='2000-02-29 07:03:08 UTC'
1873 _testfm='%Y-%m-%d %H:%M:%S %Z'
1874 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1875 daterawopt='-d@'
1876 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1877 daterawopt='-r'
1879 strftime_is_setup=1
1882 # $1 => strftime format string to use
1883 # $2 => raw timestamp as seconds since epoch
1884 # $3 => optional time zone string (empty/absent for local time zone)
1885 strftime()
1887 setup_strftime
1888 if [ -n "$daterawopt" ]; then
1889 if [ -n "$3" ]; then
1890 TZ="$3" date "$daterawopt$2" "+$1"
1891 else
1892 date "$daterawopt$2" "+$1"
1894 else
1895 if [ -n "$3" ]; then
1896 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1897 else
1898 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1903 got_cdup_result=
1904 git_cdup_result=
1905 v_get_show_cdup()
1907 if [ -z "$got_cdup_result" ]; then
1908 git_cdup_result="$(git rev-parse --show-cdup)"
1909 got_cdup_result=1
1911 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1914 setup_git_dir_is_bare()
1916 if [ -z "$git_dir_is_bare_setup" ]; then
1917 git_dir_is_bare="$(git rev-parse --is-bare-repository)"
1918 [ z"$git_dir_is_bare" = z"true" ] || git_dir_is_bare=
1919 git_dir_is_bare_setup=1
1923 setup_git_dirs()
1925 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1926 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1927 git_dir="$(cd "$git_dir" && pwd)"
1929 if [ -z "$git_common_dir" ]; then
1930 if vcmp "$git_version" '>=' "2.5"; then
1931 # rev-parse --git-common-dir is broken and may give
1932 # an incorrect result unless the current directory is
1933 # already set to the top level directory
1934 v_get_show_cdup
1935 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1936 else
1937 git_common_dir="$git_dir"
1940 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1941 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1942 git_hooks_dir="$git_common_dir/hooks"
1943 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1944 case "$gchp" in
1945 /[!/]*)
1946 git_hooks_dir="$gchp"
1949 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1951 esac
1952 unset_ gchp
1956 basic_setup_remote()
1958 if [ -z "$base_remote" ]; then
1959 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
1960 base_remote="$TG_EXPLICIT_REMOTE"
1961 else
1962 base_remote="$(git config topgit.remote 2>/dev/null)" || :
1967 basic_setup()
1969 setup_git_dirs $1
1970 basic_setup_remote
1971 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1972 tgnosequester=
1973 [ "$tgsequester" != "false" ] || tgnosequester=1
1974 unset_ tgsequester
1976 # catch errors if topbases is used without being set
1977 unset_ tg_topbases_set
1978 topbases="programmer*:error"
1979 topbasesrx="programmer*:error}"
1980 oldbases="$topbases"
1983 tmpdir_setup()
1985 [ -z "$tg_tmp_dir" ] || return 0
1986 if [ -n "$TG_TMPDIR" ] && [ -d "$TG_TMPDIR" ] && [ -w "$TG_TMPDIR" ] &&
1987 { >"$TG_TMPDIR/.check"; } >/dev/null 2>&1; then
1988 tg_tmp_dir="$TG_TMPDIR"
1989 else
1990 tg_tmp_dir=
1991 TRAPEXIT_='${TG_DEBUG:+echo} rm -rf "$tg_tmp_dir" >&2'
1992 trap 'trapexit_ 129' HUP
1993 trap 'trapexit_ 130' INT
1994 trap 'trapexit_ 131' QUIT
1995 trap 'trapexit_ 134' ABRT
1996 trap 'trapexit_ 141' PIPE
1997 trap 'trapexit_ 143' TERM
1998 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1999 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2000 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2001 [ -z "$tg_tmp_dir" ] || tg_tmp_dir="$(cd "$tg_tmp_dir" && pwd -P)"
2003 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_tmp_dir/.check"; } >/dev/null 2>&1 ||
2004 die "could not create a writable temporary directory"
2006 # whenever tg_tmp_dir is != "" these must always be set
2007 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
2008 tg_ref_cache_br="$tg_ref_cache.br"
2009 tg_ref_cache_rbr="$tg_ref_cache.rbr"
2010 tg_ref_cache_ann="$tg_ref_cache.ann"
2011 tg_ref_cache_dep="$tg_ref_cache.dep"
2014 cachedir_setup()
2016 [ -z "$tg_cache_dir" ] || return 0
2017 user_id_no="$(id -u)" || :
2018 : "${user_id_no:=_99_}"
2019 tg_cache_dir="$git_common_dir/tg-cache"
2020 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2021 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
2022 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2023 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2024 if [ -z "$tg_cache_dir" ]; then
2025 tg_cache_dir="$tg_tmp_dir/tg-cache"
2026 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2027 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2029 [ -n "$tg_cache_dir" ] ||
2030 die "could not create a writable tg-cache directory (even a temporary one)"
2032 if [ -n "$2" ]; then
2033 # allow the wayback machine to share a separate cache
2034 [ -d "$tg_cache_dir/wayback" ] || mkdir "$tg_cache_dir/wayback" >/dev/null 2>&1 || :
2035 ! [ -d "$tg_cache_dir/wayback" ] || ! { >"$tg_cache_dir/wayback/.tgcache"; } >/dev/null 2>&1 ||
2036 tg_cache_dir="$tg_cache_dir/wayback"
2040 # set up alternate deb dirs
2041 altodb_setup()
2043 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
2044 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
2045 # so we avoid it if possible and require v2.11.1 to do it at all
2046 # otherwise just don't make an alternates temporary store in that case;
2047 # it's okay to not have one; everything will still work; the nicety of
2048 # making the temporary tree objects vanish when tg exits just won't
2049 # happen in that case but nothing will break also be sure to reuse
2050 # the parent's if we've been recursively invoked and it's for the
2051 # same repository we were invoked on
2053 tg_use_alt_odb=1
2054 _fullodbdir=
2055 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
2056 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] && _fullodbdir="$(cd "$_odbdir" && pwd -P)" ||
2057 die "could not find objects directory"
2058 if [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
2059 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
2060 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
2061 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
2062 tg_use_alt_odb=2
2065 _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
2066 if [ "$tg_use_alt_odb" = "1" ]; then
2067 # create an alternate objects database to keep the ephemeral objects in
2068 mkdir -p "$tg_tmp_dir/objects/info"
2069 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
2070 [ "$_fullodbdir" = "$TG_OBJECT_DIRECTORY" ] ||
2071 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
2073 case "$_fulltmpdir" in *[";:"]*|'"'*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
2074 if [ "$tg_use_alt_odb" = "1" ]; then
2075 case "$TG_OBJECT_DIRECTORY" in
2076 *[";:"]*|'"'*)
2077 # surround in "..." and backslash-escape internal '"' and '\\'
2078 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
2079 sed 's/\([""\\]\)/\\\1/g')\""
2082 _altodbdq="$TG_OBJECT_DIRECTORY"
2084 esac
2085 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2086 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2087 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2088 else
2089 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
2091 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
2092 if [ -n "$GIT_OBJECT_DIRECTORY" ]; then
2093 export GIT_OBJECT_DIRECTORY
2094 else
2095 unset_ GIT_OBJECT_DIRECTORY
2100 noalt_setup()
2102 if [ "${TG_PRESERVED_ALTERNATES+set}" = "set" ]; then
2103 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
2104 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2105 export GIT_ALTERNATE_OBJECT_DIRECTORIES
2106 else
2107 unset_ GIT_ALTERNATE_OBJECT_DIRECTORIES
2110 unset_ TG_TMPDIR TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES tg_use_alt_odb
2113 ## Initial setup
2114 initial_setup()
2116 # suppress the merge log editor feature since git 1.7.10
2118 GIT_MERGE_AUTOEDIT=no
2119 export GIT_MERGE_AUTOEDIT
2121 basic_setup $1
2122 iowopt=
2123 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
2124 gcfbopt=
2125 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
2126 auhopt=
2127 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
2128 v_get_show_cdup root_dir
2129 root_dir="${root_dir:-.}"
2130 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
2131 [ "$logrefupdates" = "true" ] || logrefupdates=
2133 # make sure root_dir doesn't end with a trailing slash.
2135 root_dir="${root_dir%/}"
2137 # create global temporary and cache directories, usually inside GIT_DIR
2139 tmpdir_setup
2140 unset_ TG_TMPDIR
2141 cachedir_setup
2143 # the wayback machine directory serves as its own "altodb"
2144 [ -n "$wayback" ] || altodb_setup
2147 activate_wayback_machine()
2149 [ -n "${1#:}" ] || [ -n "$2" ] || { wayback=; return 0; }
2150 setup_git_dirs
2151 tmpdir_setup
2152 altodb_setup
2153 tgwbr=
2154 tgwbr2=
2155 if [ -n "${1#:}" ]; then
2156 tgwbr="$(get_temp wbinfo)"
2157 tgwbr2="${tgwbr}2"
2158 tg revert --list --no-short "${1#:}" >"$tgwbr" && test -s "$tgwbr" || return 1
2159 # tg revert will likely leave a revert-tag-only cache which is not what we want
2160 remove_ref_cache
2162 cachedir_setup "" 1 # use a separate wayback cache dir
2163 # but don't step on the normal one if the separate one could not be set up
2164 case "$tg_cache_dir" in */wayback);;*) tg_cache_dir=; esac
2165 altodb="$TG_OBJECT_DIRECTORY"
2166 if [ -n "$3" ] && [ -n "$2" ]; then
2167 [ -d "$3" ] || { mkdir -p "$3" && [ -d "$3" ]; } ||
2168 die "could not create wayback directory: $3"
2169 tg_wayback_dir="$(cd "$3" && pwd -P)" || die "could not get wayback directory full path"
2170 [ -d "$tg_wayback_dir/.git" ] || { mkdir -p "$tg_wayback_dir/.git" && [ -d "$tg_wayback_dir/.git" ]; } ||
2171 die "could not initialize wayback directory: $3"
2172 is_empty_dir "$tg_wayback_dir" ".git" && is_empty_dir "$tg_wayback_dir/.git" "." ||
2173 die "wayback directory is not empty: $3"
2174 mkdir "$tg_wayback_dir/.git/objects"
2175 mkdir "$tg_wayback_dir/.git/objects/info"
2176 cat "$altodb/info/alternates" >"$tg_wayback_dir/.git/objects/info/alternates"
2177 else
2178 tg_wayback_dir="$tg_tmp_dir/wayback"
2179 mkdir "$tg_wayback_dir"
2180 mkdir "$tg_wayback_dir/.git"
2181 ln -s "$altodb" "$tg_wayback_dir/.git/objects"
2183 mkdir "$tg_wayback_dir/.git/refs"
2184 printf '0 Wayback Machine' >"$tg_wayback_dir/.git/gc.pid"
2185 qpesc="$(printf '%s\n' "$git_common_dir" | sed -e 's/\([\\""]\)/\\\1/g' -e '$!s/$/\\n/' | tr -d '\n')"
2186 laru="false"
2187 [ -z "$2" ] || laru="true"
2188 printf '%s' "\
2189 [include]
2190 path = \"$qpesc/config\"
2191 [core]
2192 bare = false
2193 logAllRefUpdates = $laru
2194 repositoryFormatVersion = 0
2195 [extensions]
2196 preciousObjects = true
2197 [gc]
2198 auto = 0
2199 autoDetach = false
2200 autoPackLimit = 0
2201 packRefs = false
2202 [remote \"wayback\"]
2203 url = \"$qpesc\"
2204 [push]
2205 default = nothing
2206 followTags = true
2207 [alias]
2208 wayback-updates = fetch -u --force --no-tags --dry-run wayback refs/*:refs/*
2209 " >"$tg_wayback_dir/.git/config"
2210 cat "$git_dir/HEAD" >"$tg_wayback_dir/.git/HEAD"
2211 case "$1" in ":"?*);;*)
2212 git show-ref >"$tg_wayback_dir/.git/packed-refs"
2213 git --git-dir="$tg_wayback_dir/.git" pack-refs --all
2214 esac
2215 noalt_setup
2216 TG_OBJECT_DIRECTORY="$altodb" && export TG_OBJECT_DIRECTORY
2217 if [ -n "${1#:}" ]; then
2218 <"$tgwbr" sed 's/^\([^ ][^ ]*\) \([^ ][^ ]*\)$/update \2 \1/' |
2219 git --git-dir="$tg_wayback_dir/.git" update-ref -m "wayback to $1" ${2:+--create-reflog} --stdin
2221 if test -n "$2"; then
2222 # extra setup for potential shell
2223 qpesc2="$(printf '%s\n' "$git_common_dir" | sed -e 's/\([\\""]\)/\\\\\1/g' -e '$!s/$/\\n/' | tr -d '\n')"
2224 printf '\twayback-repository = "!printf '\''%%s\\\\n'\'' \\"%s\\""\n' "$qpesc2" >>"$tg_wayback_dir/.git/config"
2225 qtesc="$(printf '%s\n' "${1:-:}" | sed 's/\([""]\)/\\\1/g')"
2226 printf '\twayback-tag = "!printf '\''%%s\\\\n'\'' \\"%s\\""\n' "$qtesc" >>"$tg_wayback_dir/.git/config"
2227 if [ -d "$git_common_dir/rr-cache" ]; then
2228 ln -s "$git_common_dir/rr-cache" "$tg_wayback_dir/.git/rr-cache"
2229 printf "[rerere]\n\tenabled = true\n" >>"$tg_wayback_dir/.git/config"
2231 if [ z"$2" != z"2" ]; then
2232 wbauth=
2233 wbprnt=
2234 if [ -n "${1#:}" ]; then
2235 [ -n "$tgwbr2" ] || tgwbr2="$(get_temp wbtag)"
2236 git --git-dir="$git_common_dir" cat-file tag "${1#:}" >"$tgwbr2" || return 1
2237 wbprnt="${lf}parent $(git --git-dir="$git_common_dir" rev-parse --verify --quiet "${1#:}"^0 -- 2>/dev/null)" || wbprnt=
2238 wbauth="$(<"$tgwbr2" awk '{if(!$0)exit;if($1=="tagger")print "author" substr($0,7)}')"
2240 wbcmtr="committer Wayback Machine <-> $(date "+%s %z")"
2241 [ -n "$wbauth" ] || wbauth="author${wbcmtr#committer}"
2242 wbtree="$(git --git-dir="$tg_wayback_dir/.git" mktree </dev/null)"
2243 wbcmt="$({
2244 printf '%s\n' "tree $wbtree$wbprnt" "$wbauth" "$wbcmtr" ""
2245 if [ -n "$tgwbr2" ]; then
2246 <"$tgwbr2" sed -e '1,/^$/d' -e '/^-----BEGIN/,$d' | git stripspace
2247 else
2248 echo "Wayback Machine"
2250 } | git --git-dir="$tg_wayback_dir/.git" hash-object -t commit -w --stdin)"
2251 test -n "$wbcmt" || return 1
2252 echo "$wbcmt" >"$tg_wayback_dir/.git/HEAD"
2255 cd "$tg_wayback_dir"
2256 unset git_dir git_common_dir
2259 set_topbases()
2261 # refer to "top-bases" in a refname with $topbases
2263 [ -z "$tg_topbases_set" ] || return 0
2265 topbases_implicit_default=1
2266 # See if topgit.top-bases is set to heads or refs
2267 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
2268 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
2269 if [ -n "$1" ]; then
2270 # never die on the hook script
2271 unset_ tgtb
2272 else
2273 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
2276 if [ -n "$tgtb" ]; then
2277 case "$tgtb" in
2278 heads)
2279 topbases="heads/{top-bases}"
2280 topbasesrx="heads/[{]top-bases[}]"
2281 oldbases="top-bases";;
2282 refs)
2283 topbases="top-bases"
2284 topbasesrx="top-bases"
2285 oldbases="heads/{top-bases}";;
2286 esac
2287 # MUST NOT be exported
2288 unset_ tgtb tg_topbases_set topbases_implicit_default
2289 tg_topbases_set=1
2290 return 0
2292 unset_ tgtb
2294 # check heads and top-bases and see what state the current
2295 # repository is in. remotes are ignored.
2297 rc=0 activebases=
2298 activebases="$(
2299 git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null |
2300 run_awk_ref_prefixes ${1:+-e} -n -- "refs/heads/{top-bases}" "refs/top-bases" "refs/heads")" ||
2301 rc=$?
2302 if [ "$rc" = "65" ]; then
2303 # Complain and die
2304 err "repository contains existing TopGit branches"
2305 err "but some use refs/top-bases/... for the base"
2306 err "and some use refs/heads/{top-bases}/... for the base"
2307 err "with the latter being the new, preferred location"
2308 err "set \"topgit.top-bases\" to either \"heads\" to use"
2309 err "the new heads/{top-bases} location or \"refs\" to use"
2310 err "the old top-bases location."
2311 err "(the tg migrate-bases command can also resolve this issue)"
2312 die "schizophrenic repository requires topgit.top-bases setting"
2314 [ -z "$activebases" ] || unset_ topbases_implicit_default
2315 if [ "$activebases" = "refs/heads/{top-bases}" ]; then
2316 topbases="heads/{top-bases}"
2317 topbasesrx="heads/[{]top-bases[}]"
2318 oldbases="top-bases"
2319 else
2320 # default is still top-bases for now
2321 topbases="top-bases"
2322 topbasesrx="top-bases"
2323 oldbases="heads/{top-bases}"
2325 # MUST NOT be exported
2326 unset_ rc activebases tg_topases_set
2327 tg_topbases_set=1
2328 return 0
2331 # $1 is remote name to check
2332 # $2 is optional variable name to set to result of check
2333 # $3 is optional command name to use in message (defaults to $cmd)
2334 # Fatal error if remote has schizophrenic top-bases
2335 # No error (and $2, if provided, will be set to empty) if remote has no top-bases at all
2336 check_remote_topbases()
2338 [ -n "$1" ] || die "programmer error: check_remote_topbases called with no remote argument"
2339 _crrc=0 _crremotebases=
2340 _crremotebases="$(
2341 git for-each-ref --format='%(refname)' "refs/remotes/$1" 2>/dev/null |
2342 run_awk_ref_prefixes -n -- "refs/remotes/$1/{top-bases}" "refs/remotes/$1/top-bases" "refs/remotes/$1")" ||
2343 _crrc=$?
2344 if [ "$_crrc" = "65" ]; then
2345 err "remote \"$1\" has top-bases in both locations:"
2346 err " refs/remotes/$1/{top-bases}/..."
2347 err " refs/remotes/$1/top-bases/..."
2348 err "set \"topgit.top-bases\" to \"heads\" for the first, preferred location"
2349 err "or set \"topgit.top-bases\" to \"refs\" for the second, old location"
2350 err "(the \"-c topgit.top-bases=<val>\" option can be used for this)"
2351 err "then re-run the tg ${3:-$cmd} command"
2352 err "(the tg migrate-bases command can also help with this problem)"
2353 die "schizophrenic remote \"$1\" requires topgit.top-bases setting"
2355 [ "$_crrc" != "66" ] || _crremotebases= # just to be sure
2356 [ -z "$2" ] || eval "$2="'"$_crremotebases"'
2357 unset _crrc _crremotebases
2358 return 0
2361 # init_reflog "ref"
2362 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
2363 # an empty log file to exist so that ref changes will be logged
2364 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
2365 # However, if "$1" is "refs/tgstash" then always make the reflog
2366 # The only ref not under refs/ that Git will write a reflog for is HEAD;
2367 # no matter what, it will NOT update a reflog for any other bare refs so
2368 # just quietly succeed when passed TG_STASH without doing anything.
2369 init_reflog()
2371 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
2372 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
2373 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
2374 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
2375 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
2378 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
2379 # a symbolic link. The directory part must exist, but the basename need not.
2380 v_get_abs_path()
2382 [ -n "$1" ] && [ -n "$2" ] || return 1
2383 set -- "$1" "$2" "${2%/}"
2384 case "$3" in
2385 */*) set -- "$1" "$2" "${3%/*}";;
2386 * ) set -- "$1" "$2" ".";;
2387 esac
2388 case "$2" in */)
2389 set -- "$1" "${2%/}" "$3" "/"
2390 esac
2391 [ -d "$3" ] || return 1
2392 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
2395 ## Startup
2397 : "${TG_INST_CMDDIR:=@cmddir@}"
2398 : "${TG_INST_SHAREDIR:=@sharedir@}"
2399 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
2401 [ -d "$TG_INST_CMDDIR" ] ||
2402 die "No command directory: '$TG_INST_CMDDIR'"
2404 ## Include awk scripts and their utility functions (separated for easier debugging)
2406 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
2407 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
2408 . "$TG_INST_CMDDIR/tg--awksome"
2410 if [ -n "$tg__include" ]; then
2412 # We were sourced from another script for our utility functions;
2413 # this is set by hooks. Skip the rest of the file. A simple return doesn't
2414 # work as expected in every shell. See http://bugs.debian.org/516188
2416 # ensure setup happens
2418 initial_setup 1
2419 set_topbases 1
2420 noalt_setup
2422 else
2424 set -e
2426 tgbin="$0"
2427 tgdir="${tgbin%/}"
2428 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
2429 tgdir="${tgdir%/*}/"
2430 tgname="${tgbin##*/}"
2431 [ "$0" != "$tgname" ] || tgdir=""
2433 # If tg contains a '/' but does not start with one then replace it with an absolute path
2435 case "$0" in /*) ;; */*)
2436 tgdir="$(cd "${0%/*}" && pwd -P)/"
2437 tgbin="$tgdir$tgname"
2438 esac
2440 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
2441 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2443 tgdisplaydir="$tgdir"
2444 tgdisplay="$tgbin"
2445 tgdisplayac="$tgdisplay"
2447 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2448 _tgabs="$_tgnameabs" &&
2449 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2450 [ "$_tgabs" = "$_tgnameabs" ]
2451 then
2452 tgdisplaydir=""
2453 tgdisplay="$tgname"
2454 tgdisplayac="$tgdisplay"
2456 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2457 unset_ _tgabs _tgnameabs
2459 tg() (
2460 TG_TMPDIR="$tg_tmp_dir" && export TG_TMPDIR &&
2461 exec "$tgbin" "$@"
2464 explicit_remote=
2465 explicit_dir=
2466 gitcdopt=
2467 noremote=
2468 forcepager=
2469 wayback=
2471 cmd=
2472 while :; do case "$1" in
2474 help|--help|-h)
2475 cmd=help
2476 shift
2477 break;;
2479 status|--status)
2480 cmd=status
2481 shift
2482 break;;
2484 --hooks-path)
2485 cmd=hooks-path
2486 shift
2487 break;;
2489 --exec-path)
2490 cmd=exec-path
2491 shift
2492 break;;
2494 --awk-path)
2495 cmd=awk-path
2496 shift
2497 break;;
2499 --top-bases)
2500 cmd=top-bases
2501 shift
2502 break;;
2504 --no-pager)
2505 forcepager=0
2506 shift;;
2508 --pager|-p)
2509 forcepager=1
2510 shift;;
2513 shift
2514 if [ -z "$1" ]; then
2515 echo "Option -r requires an argument." >&2
2516 do_help
2517 exit 1
2519 unset_ noremote
2520 base_remote="$1"
2521 explicit_remote="$base_remote"
2522 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2523 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2524 shift;;
2527 unset_ base_remote explicit_remote
2528 noremote=1
2529 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2530 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2531 shift;;
2534 shift
2535 if [ -z "$1" ]; then
2536 echo "Option -C requires an argument." >&2
2537 do_help
2538 exit 1
2540 cd "$1"
2541 unset_ GIT_DIR GIT_COMMON_DIR
2542 if [ -z "$explicit_dir" ]; then
2543 explicit_dir="$1"
2544 else
2545 explicit_dir="$PWD"
2547 gitcdopt=" -C \"$explicit_dir\""
2548 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2549 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2550 tgdisplayac="$tgdisplay"
2551 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2552 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2553 shift;;
2556 shift
2557 if [ -z "$1" ]; then
2558 echo "Option -c requires an argument." >&2
2559 do_help
2560 exit 1
2562 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2563 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2564 export GIT_CONFIG_PARAMETERS
2565 shift;;
2568 if [ -n "$wayback" ]; then
2569 echo "Option -w may be used at most once." >&2
2570 do_help
2571 exit 1
2573 shift
2574 if [ -z "$1" ]; then
2575 echo "Option -w requires an argument." >&2
2576 do_help
2577 exit 1
2579 wayback="$1"
2580 shift;;
2583 shift
2584 break;;
2587 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2588 do_help
2589 exit 1;;
2592 break;;
2594 esac; done
2595 if [ z"$forcepager" = z"0" ]; then
2596 GIT_PAGER_IN_USE=1 TG_PAGER_IN_USE=1 &&
2597 export GIT_PAGER_IN_USE TG_PAGER_IN_USE
2600 [ -n "$cmd" ] || [ $# -lt 1 ] || { cmd="$1"; shift; }
2602 ## Dispatch
2604 [ -n "$cmd" ] || { do_help; exit 1; }
2606 case "$cmd" in
2608 help)
2609 do_help "$@"
2610 exit 0;;
2612 status|st)
2613 unset_ base_remote
2614 basic_setup
2615 set_topbases
2616 do_status "$@"
2617 exit ${do_status_result:-0};;
2619 hooks-path)
2620 # Internal command
2621 echol "$TG_INST_HOOKSDIR";;
2623 exec-path)
2624 # Internal command
2625 echol "$TG_INST_CMDDIR";;
2627 awk-path)
2628 # Internal command
2629 echol "$TG_INST_CMDDIR/awk";;
2631 top-bases)
2632 # Maintenance command
2633 do_topbases_help=
2634 show_remote_topbases=
2635 case "$1" in
2636 --help|-h)
2637 do_topbases_help=0;;
2638 -r|--remote)
2639 if [ $# -eq 2 ] && [ -n "$2" ]; then
2640 # unadvertised, but make it work
2641 base_remote="$2"
2642 shift
2644 show_remote_topbases=1;;
2646 [ $# -eq 0 ] || do_topbases_help=1;;
2647 esac
2648 [ $# -le 1 ] || do_topbases_help=1
2649 if [ -n "$do_topbases_help" ]; then
2650 helpcmd='echo "Usage: ${tgname:-tg} [-r <remote>] --top-bases [-r]"'
2651 [ $do_topbases_help -eq 0 ] || helpcmd="$helpcmd >&2"
2652 eval "$helpcmd"
2653 exit $do_topbases_help
2655 git_dir=
2656 if git_dir="$(git rev-parse --git-dir 2>&1)"; then
2657 [ -z "$wayback" ] || activate_wayback_machine "$wayback"
2658 setup_git_dirs
2660 set_topbases
2661 if [ -n "$show_remote_topbases" ]; then
2662 basic_setup_remote
2663 [ -n "$base_remote" ] ||
2664 die "no remote location given. Either use -r <remote> option or set topgit.remote"
2665 rbases=
2666 [ -z "$topbases_implicit_default" ] ||
2667 check_remote_topbases "$base_remote" rbases "--top-bases"
2668 if [ -n "$rbases" ]; then
2669 echol "$rbases"
2670 else
2671 echol "refs/remotes/$base_remote/${topbases#heads/}"
2673 else
2674 echol "refs/$topbases"
2675 fi;;
2678 isutil=
2679 case "$cmd" in index-merge-one-file)
2680 isutil="-"
2681 esac
2682 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2683 looplevel="$TG_ALIAS_DEPTH"
2684 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2685 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2686 looplevel=0
2687 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2688 [ -n "$tgalias" ] || {
2689 echo "Unknown subcommand: $cmd" >&2
2690 do_help
2691 exit 1
2693 looplevel=$(( $looplevel + 1 ))
2694 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2695 TG_ALIAS_DEPTH="$looplevel"
2696 export TG_ALIAS_DEPTH
2697 if [ "!${tgalias#?}" = "$tgalias" ]; then
2698 [ -z "$wayback" ] ||
2699 die "-w is not allowed before an '!' alias command"
2700 unset_ GIT_PREFIX
2701 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2702 GIT_PREFIX="$pfx"
2703 export GIT_PREFIX
2705 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2706 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2707 else
2708 eval 'exec "$tgbin"' "${wayback:+-w \"\$wayback\"}" "$tgalias" '"$@"'
2710 die "alias execution failed for: $tgalias"
2712 unset_ TG_ALIAS_DEPTH
2714 showing_help=
2715 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2716 showing_help=1
2719 nomergesetup="$showing_help"
2720 case "$cmd" in base|contains|export|files|info|log|mail|next|patch|prev|rebase|revert|shell|summary|tag)
2721 # avoid merge setup where not necessary
2723 nomergesetup=1
2724 esac
2726 if [ -n "$wayback" ] && [ -z "$showing_help" ]; then
2727 [ -n "$nomergesetup" ] ||
2728 die "the wayback machine cannot be used with the \"$cmd\" subcommand"
2729 if [ "$cmd" = "shell" ]; then
2730 # this is ugly; `tg shell` should handle this but it's too
2731 # late there so we have to do it here
2732 wayback_dir=
2733 case "$1" in
2734 "--directory="?*)
2735 wayback_dir="${1#--directory=}" && shift;;
2736 "--directory=")
2737 die "--directory requires an argument";;
2738 "--directory")
2739 [ $# -ge 2 ] || die "--directory requires an argument"
2740 wayback_dir="$2" && shift 2;;
2741 esac
2742 activate_wayback_machine "$wayback" 1 "$wayback_dir"
2743 else
2744 _fullwb=
2745 # export might drop out into a shell for conflict resolution
2746 [ "$cmd" != "export" ] || _fullwb=2
2747 activate_wayback_machine "$wayback" "$_fullwb"
2748 fi ||
2749 die "failed to set the wayback machine to target \"$wayback\""
2752 [ -n "$showing_help" ] || initial_setup
2753 [ -z "$noremote" ] || unset_ base_remote
2755 if [ -z "$nomergesetup" ]; then
2756 # make sure merging the .top* files will always behave sanely
2758 setup_ours
2759 setup_hook "pre-commit"
2762 # everything but rebase needs topbases set
2763 carefully="$showing_help"
2764 [ "$cmd" != "migrate-bases" ] || carefully=1
2765 [ "$cmd" = "rebase" ] || set_topbases $carefully
2767 _use_ref_cache=
2768 tg_read_only=1
2769 _suppress_alt=
2770 case "$cmd$showing_help" in
2771 contains|info|summary|tag)
2772 _use_ref_cache=1;;
2773 "export")
2774 _use_ref_cache=1
2775 _suppress_alt=1;;
2776 annihilate|create|delete|depend|import|update)
2777 tg_read_only=
2778 _suppress_alt=1;;
2779 esac
2780 [ -z "$_suppress_alt" ] || noalt_setup
2781 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2783 fullcmd="${tgname:-tg} $cmd $*"
2784 if [ z"$forcepager" = z"1" ]; then
2785 page '. "$TG_INST_CMDDIR"/tg-$isutil$cmd' "$@"
2786 else
2787 . "$TG_INST_CMDDIR"/tg-$isutil$cmd
2788 fi;;
2789 esac