tg.sh: next version is 0.19.9
[topgit/pro.git] / tg.sh
blob565e2b5f371703fd382625528b6edb8959139627
1 #!/bin/sh
2 # TopGit - A different patch queue manager
3 # Copyright (C) 2008 Petr Baudis <pasky@suse.cz>
4 # Copyright (C) 2014-2017 Kyle J. McKay <mackyle@gmail.com>
5 # All rights reserved.
6 # GPLv2
8 TG_VERSION="0.19.9.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" -o "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" -a -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" -a "$_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" -a -s "$tg_ref_cache" ] || return 0
592 mkdir -p "$tg_tmp_dir/cached/refs"
593 awk '{x = $1; sub(/^refs\//, "", x); if (x != "") print x}' <"$tg_ref_cache" | tr '\n' '\0' | {
594 cd "$tg_tmp_dir/cached/refs" &&
595 xargs -0 mkdir -p
597 awk -v p="$tg_tmp_dir/cached/" '
598 NF == 2 &&
599 $1 ~ /^refs\/./ &&
600 $2 ~ /^[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]+$/ {
601 fn = p $1 "/.ref"
602 print "0 " $2 >fn
603 close(fn)
605 ' <"$tg_ref_cache"
606 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
609 # If the first argument is non-empty, stores "1" there if this call created the cache
610 v_create_ref_cache()
612 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
613 _remotespec=
614 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
615 [ -z "$1" ] || eval "$1=1"
616 git for-each-ref --format='%(refname) %(objectname)' \
617 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
618 create_ref_dirs
621 remove_ref_cache()
623 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
624 >"$tg_ref_cache"
625 >"$tg_ref_cache_br"
626 >"$tg_ref_cache_rbr"
627 >"$tg_ref_cache_ann"
628 >"$tg_ref_cache_dep"
631 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
632 rev_parse()
634 rev_parse_code_=1
635 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
636 rev_parse_code_=0
637 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache" ||
638 rev_parse_code_=$?
640 [ $rev_parse_code_ -ne 0 ] && [ -z "$tg_ref_cache_only" ] || return $rev_parse_code_
641 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
644 # ref_exists_rev REF
645 # Whether REF is a valid ref name
646 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
647 # or, if $base_remote is set, refs/remotes/$base_remote/
648 # Caches result if $tg_read_only and outputs HASH on success
649 ref_exists_rev()
651 case "$1" in
652 refs/*)
654 $octet20)
655 printf '%s' "$1"
656 return;;
658 die "ref_exists_rev requires fully-qualified ref name (given: $1)"
659 esac
660 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
661 _result=
662 _result_rev=
663 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
664 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
665 _result=0
666 _result_rev="$(rev_parse "$1")" || _result=$?
667 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
668 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
669 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
670 printf '%s' "$_result_rev"
671 return $_result
674 # Same as ref_exists_rev but output is abbreviated hash
675 # Optional second argument defaults to --short but may be any --short=.../--no-short option
676 ref_exists_rev_short()
678 case "$1" in
679 refs/*)
681 $octet20)
684 die "ref_exists_rev_short requires fully-qualified ref name"
685 esac
686 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
687 _result=
688 _result_rev=
689 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
690 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
691 _result=0
692 _result_rev="$(rev_parse "$1")" || _result=$?
693 if [ $_result -eq 0 ]; then
694 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev^0" --)"
695 _result=$?
697 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
698 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
699 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
700 printf '%s' "$_result_rev"
701 return $_result
704 # ref_exists REF
705 # Whether REF is a valid ref name
706 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
707 # or, if $base_remote is set, refs/remotes/$base_remote/
708 # Caches result
709 ref_exists()
711 ref_exists_rev "$1" >/dev/null
714 # rev_parse_tree REF
715 # Runs git rev-parse REF^{tree}
716 # Caches result if $tg_read_only
717 rev_parse_tree()
719 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
720 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
721 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
722 printf '%s\n' "$_result"
723 return 0
725 return 1
727 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
728 if [ -d "$tg_tmp_dir/cached/$1" ]; then
729 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
730 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
731 printf '%s\n' "$_result"
732 return 0
734 return 1
736 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
739 # has_remote BRANCH
740 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
741 has_remote()
743 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
746 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
747 # If -z "$1" still set return code but do not return result
748 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
749 # refs/heads/... then ... will be verified instead.
750 # if "$3" = "-f" (for fail) then return an error rather than dying.
751 v_verify_topgit_branch()
753 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
754 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
755 [ -n "$_verifyname" -o "$3" = "-f" ] || die "HEAD is not a symbolic ref"
756 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
757 [ "$3" != "-f" ] || return 1
758 die "HEAD is not a symbolic ref to the refs/heads namespace"
759 esac
760 set -- "$1" "$_verifyname" "$3"
762 case "$2" in
763 refs/"$topbases"/*)
764 _verifyname="${2#refs/$topbases/}"
766 refs/heads/*)
767 _verifyname="${2#refs/heads/}"
770 _verifyname="$2"
772 esac
773 if ! ref_exists "refs/heads/$_verifyname"; then
774 [ "$3" != "-f" ] || return 1
775 die "no such branch: $_verifyname"
777 if ! ref_exists "refs/$topbases/$_verifyname"; then
778 [ "$3" != "-f" ] || return 1
779 die "not a TopGit-controlled branch: $_verifyname"
781 [ -z "$1" ] || eval "$1="'"$_verifyname"'
784 # Return the verified TopGit branch name or die with an error.
785 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
786 # refs/heads/... then ... will be verified instead.
787 # if "$2" = "-f" (for fail) then return an error rather than dying.
788 verify_topgit_branch()
790 v_verify_topgit_branch _verifyname "$@" || return
791 printf '%s' "$_verifyname"
794 # Caches result
795 # $1 = branch name (i.e. "t/foo/bar")
796 # $2 = optional result of rev-parse "refs/heads/$1"
797 # $3 = optional result of rev-parse "refs/$topbases/$1"
798 branch_annihilated()
800 _branch_name="$1"
801 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
802 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
804 _result=
805 _result_rev=
806 _result_rev_base=
807 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/refs/heads/$_branch_name/.ann"; } 2>/dev/null || :
808 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
810 # use the merge base in case the base is ahead.
811 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
813 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
814 _result=$?
815 [ -d "$tg_cache_dir/refs/heads/$_branch_name" ] || mkdir -p "$tg_cache_dir/refs/heads/$_branch_name" 2>/dev/null
816 [ ! -d "$tg_cache_dir/refs/heads/$_branch_name" ] ||
817 echo $_result $_rev $_rev_base >"$tg_cache_dir/refs/heads/$_branch_name/.ann" 2>/dev/null || :
818 return $_result
821 non_annihilated_branches()
823 refscacheopt="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
824 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
825 refscacheopt="$refscacheopt"'-r="$tg_ref_cache" "refs/$topbases"'
827 eval run_awk_topgit_branches -n "$refscacheopt" '"refs/$topbases" "$@"'
830 # Make sure our tree is clean
831 # if optional "$1" given also verify that a checkout to "$1" would succeed
832 ensure_clean_tree()
834 check_status
835 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
836 git update-index --ignore-submodules --refresh ||
837 die "the working directory has uncommitted changes (see above) - first commit or reset them"
838 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
839 die "the index has uncommited changes"
840 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
841 die "git checkout \"$1\" would fail"
844 # Make sure .topdeps and .topmsg are "clean"
845 # They are considered "clean" if each is identical in worktree, index and HEAD
846 # With "-u" as the argument skip the HEAD check (-u => unborn)
847 # untracked .topdeps and/or .topmsg files are always considered "dirty" as well
848 # with -u them just existing constitutes "dirty"
849 ensure_clean_topfiles()
851 _dirtw=0
852 _dirti=0
853 _dirtu=0
854 _check="$(git diff-files --ignore-submodules --name-only -- :/.topdeps :/.topmsg)" &&
855 [ -z "$_check" ] || _dirtw=1
856 if [ "$1" != "-u" ]; then
857 _check="$(git diff-index --cached --ignore-submodules --name-only HEAD -- :/.topdeps :/.topmsg)" &&
858 [ -z "$_check" ] || _dirti=1
860 if [ "$_dirti$_dirtw" = "00" ]; then
861 v_get_show_cdup
862 if [ -e "${git_cdup_result}.topdeps" ] || [ -e "${git_cdup_result}.topmsg" ]; then
863 [ "$1" != "-u" ] &&
864 _check="$(git status --porcelain --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg)" &&
865 [ -z "$_check" ] || _dirtu=1
868 if [ "$_dirtu$_dirti$_dirtw" != "000" ]; then
869 git status --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg || :
870 case "$_dirtu$_dirti$_dirtw" in
871 001) die "the working directory has uncommitted changes (see above) - first commit or reset them";;
872 010) die "the index has uncommited changes (see above)";;
873 011) die "the working directory and index have uncommitted changes (see above) - first commit or reset them";;
874 100) die "the working directory has untracked files that would be overwritten (see above)";;
875 esac
879 # is_sha1 REF
880 # Whether REF is a SHA1 (compared to a symbolic name).
881 is_sha1()
883 case "$1" in $octet20) return 0;; esac
884 return 1
887 # navigate_deps <run_awk_topgit_navigate options and arguments>
888 # all options and arguments are passed through to run_awk_topgit_navigate
889 # except for a leading -td= option, if any, which is picked off for deps
890 # after arranging to feed it a suitable deps list
891 navigate_deps()
893 dogfer=
894 dorad=1
895 userc=
896 tmpdep=
897 ratd_opts="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
898 ratn_opts=
899 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
900 userc=1
901 tmprfs="$tg_ref_cache"
902 tmptgbr="$tg_ref_cache_br"
903 tmpann="$tg_ref_cache_ann"
904 tmpdep="$tg_ref_cache_dep"
905 [ -s "$tg_ref_cache" ] || dogfer=1
906 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
907 else
908 ratd_opts="${ratd_opts}-rmr"
909 ratn_opts="-rma -rmb"
910 tmprfs="$tg_tmp_dir/refs.$$"
911 tmpann="$tg_tmp_dir/ann.$$"
912 tmptgbr="$tg_tmp_dir/tgbr.$$"
913 dogfer=1
915 refpats="\"refs/heads\" \"refs/\$topbases\""
916 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
917 [ -z "$dogfer" ] ||
918 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
919 depscmd="run_awk_topgit_deps $ratd_opts"
920 case "$1" in -td=*)
921 userc=
922 depscmd="$depscmd $1"
923 shift
924 esac
925 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -s "refs/$topbases"'
926 if [ -n "$userc" ]; then
927 if [ -n "$dorad" ]; then
928 eval "$depscmd" >"$tmpdep"
930 depscmd='<"$tmpdep" '
931 else
932 depscmd="$depscmd |"
934 eval "$depscmd" run_awk_topgit_navigate '-a="$tmpann" -b="$tmptgbr"' "$ratn_opts" '"$@"'
937 # recurse_deps_internal NAME [BRANCHPATH...]
938 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
939 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
940 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
941 # (but missing and remotes are always "0")
942 # followed by a 0 for no excess visits or a positive number of excess visits
943 # then the branch name followed by its depedency chain (which might be empty)
944 # An output line might look like this:
945 # 0 1 1 0 t/foo/leaf t/foo/int t/stage
946 # If no_remotes is non-empty, exclude remotes
947 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
948 # If with_top_level is non-empty, include the top-level that's normally omitted
949 # any branch names in the space-separated recurse_deps_exclude variable
950 # are skipped (along with their dependencies)
951 recurse_deps_internal()
953 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
954 ratr_opts="${recurse_preorder:+-f} ${with_top_level:+-s}"
955 dogfer=
956 dorad=1
957 userc=
958 tmpdep=
959 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
960 userc=1
961 tmprfs="$tg_ref_cache"
962 tmptgbr="$tg_ref_cache_br"
963 tmpann="$tg_ref_cache_ann"
964 tmpdep="$tg_ref_cache_dep"
965 [ -s "$tg_ref_cache" ] || dogfer=1
966 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
967 else
968 ratr_opts="$ratr_opts -rmh -rma -rmb"
969 tmprfs="$tg_tmp_dir/refs.$$"
970 tmpann="$tg_tmp_dir/ann.$$"
971 tmptgbr="$tg_tmp_dir/tgbr.$$"
972 dogfer=1
974 refpats="\"refs/heads\" \"refs/\$topbases\""
975 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
976 tmptgrmtbr=
977 dorab=1
978 if [ -z "$no_remotes" ] && [ -n "$base_remote" ]; then
979 if [ -n "$userc" ]; then
980 tmptgrmtbr="$tg_ref_cache_rbr"
981 [ -n "$dogfer" ] || ! [ -s "$tmptgrmtbr" ] || dorab=
982 else
983 tmptgrmtbr="$tg_tmp_dir/tgrmtbr.$$"
984 ratr_opts="$ratr_opts -rmr"
986 ratr_opts="$ratr_opts -r=\"\$tmptgrmtbr\" -u=\":refs/remotes/\$base_remote/\${topbases#heads/}\""
988 [ -z "$dogfer" ] ||
989 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
990 if [ -n "$tmptgrmtbr" ] && [ -n "$dorab" ]; then
991 run_awk_topgit_branches -n -h="refs/remotes/$base_remote" -r="$tmprfs" \
992 "refs/remotes/$base_remote/${topbases#heads/}" >"$tmptgrmtbr"
994 depscmd="run_awk_topgit_deps -s${TG_DEBUG:+ -p=\"\$tg_ref_cache.pre\"}"
995 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" "refs/$topbases"'
996 if [ -n "$userc" ]; then
997 if [ -n "$dorad" ]; then
998 eval "$depscmd" >"$tmpdep"
1000 depscmd='<"$tmpdep" '
1001 else
1002 depscmd="$depscmd |"
1004 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
1005 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
1008 # do_eval CMD
1009 # helper for recurse_deps so that a return statement executed inside CMD
1010 # does not return from recurse_deps. This shouldn't be necessary, but it
1011 # seems that it actually is.
1012 do_eval()
1014 eval "$@"
1017 # becomes read-only for caching purposes
1018 # assigns new value to tg_read_only
1019 # become_cacheable/undo_become_cacheable calls may be nested
1020 become_cacheable()
1022 _old_tg_read_only="$tg_read_only"
1023 if [ -z "$tg_read_only" ]; then
1024 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1025 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1026 tg_read_only=1
1028 _my_ref_cache=
1029 v_create_ref_cache _my_ref_cache
1030 _my_ref_cache="${_my_ref_cache:+1}"
1031 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
1034 # restores tg_read_only and ref_cache to state before become_cacheable call
1035 # become_cacheable/undo_bocome_cacheable calls may be nested
1036 undo_become_cacheable()
1038 case "$tg_read_only" in
1039 "undo"[01]"-"*)
1040 _suffix="${tg_read_only#undo?-}"
1041 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
1042 tg_read_only="$_suffix"
1043 esac
1046 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
1047 become_non_cacheable()
1049 remove_ref_cache
1050 tg_read_only=
1051 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1052 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1055 # call this to make sure the current Git repository has an associated work tree
1056 # also make sure we are not in wayback mode
1057 ensure_work_tree()
1059 [ -z "$wayback" ] ||
1060 die "the wayback machine cannot be used with the specified options"
1061 setup_git_dir_is_bare
1062 [ -n "$git_dir_is_bare" ] || return 0
1063 die "This operation must be run in a work tree"
1066 # call this to make sure Git will not complain about a missing user/email
1067 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
1068 ensure_ident_available()
1070 [ -z "$TG_IDENT_CHECKED" ] || return 0
1071 git var GIT_AUTHOR_IDENT >/dev/null &&
1072 git var GIT_COMMITTER_IDENT >/dev/null || exit
1073 TG_IDENT_CHECKED=1
1074 export TG_IDENT_CHECKED
1075 return 0
1078 # recurse_deps [-o=<options string>] CMD NAME [BRANCHPATH...]
1079 # Recursively eval CMD on all dependencies of NAME.
1080 # Dependencies are visited in topological order.
1081 # If <options string> is given, it's eval'd into the recurse_deps_internal
1082 # call just before the "--" that's passed just before NAME
1083 # CMD can refer to the following variables:
1085 # _ret starts as 0; CMD can change; will be final return result
1086 # _dep bare branch name or ":refs/remotes/..." for a remote
1087 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
1088 # _depchain 0+ space-sep branch names (_name first) form a path to top
1089 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
1090 # _dep_is_leaf boolean "1" if leaf; "" if not
1091 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
1092 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
1093 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
1094 # _dep_xvisits non-negative integer number of excess visits (often 0)
1096 # CMD may use a "return" statement without issue; its return value is ignored,
1097 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
1098 # will stop immediately and the value with the leading "-" stripped off will
1099 # be the final result code
1101 # CMD can refer to $_name for queried branch name,
1102 # $_dep for dependency name,
1103 # $_depchain for space-seperated branch backtrace,
1104 # $_dep_missing boolean to check whether $_dep is present
1105 # and the $_dep_is_tgish and $_dep_annihilated booleans.
1106 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
1107 # It can modify $_ret to affect the return value
1108 # of the whole function.
1109 # If recurse_deps() hits missing dependencies, it will append
1110 # them to space-separated $missing_deps list and skip them
1111 # after calling CMD with _dep_missing set.
1112 # remote dependencies are processed if no_remotes is unset.
1113 # any branch names in the space-separated recurse_deps_exclude variable
1114 # are skipped (along with their dependencies)
1116 # If no_remotes is non-empty, exclude remotes
1117 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1118 # If with_top_level is non-empty, include the top-level that's normally omitted
1119 # any branch names in the space-separated recurse_deps_exclude variable
1120 # are skipped (along with their dependencies)
1121 recurse_deps()
1123 _opts=
1124 case "$1" in -o=*) _opts="${1#-o=}"; shift; esac
1125 _cmd="$1"; shift
1127 _depsfile="$(get_temp tg-depsfile)"
1128 eval recurse_deps_internal "$_opts" -- '"$@"' >"$_depsfile" || :
1130 _ret=0
1131 while read _ismissing _istgish _isleaf _dep_xvisits _dep _name _deppath; do
1132 _depchain="$_name${_deppath:+ $_deppath}"
1133 _dep_is_tgish=
1134 [ "$_istgish" = "0" ] || _dep_is_tgish=1
1135 _dep_has_remote=
1136 [ "$_istgish" != "2" ] || _dep_has_remote=1
1137 _dep_missing=
1138 if [ "$_ismissing" != "0" ]; then
1139 _dep_missing=1
1140 case " $missing_deps " in *" $_dep "*);;*)
1141 missing_deps="${missing_deps:+$missing_deps }$_dep"
1142 esac
1144 _dep_annihilated=
1145 _dep_is_leaf=
1146 if [ "$_isleaf" = "1" ]; then
1147 _dep_is_leaf=1
1148 elif [ "$_isleaf" = "2" ]; then
1149 _dep_annihilated=1
1151 do_eval "$_cmd" || :
1152 if [ "${_ret#-}" != "$_ret" ]; then
1153 _ret="${_ret#-}"
1154 break
1156 done <"$_depsfile"
1157 rm -f "$_depsfile"
1158 return ${_ret:-0}
1161 # find_leaves NAME
1162 # output (one per line) the unique leaves of NAME
1163 # a leaf is either
1164 # 1) a non-tgish dependency
1165 # 2) the base of a tgish dependency with no non-annihilated dependencies
1166 # duplicates are suppressed (by commit rev) and remotes are always ignored
1167 # if a leaf has an exact tag match that will be output
1168 # note that recurse_deps_exclude IS honored for this operation
1169 find_leaves()
1171 no_remotes=1
1172 with_top_level=1
1173 recurse_preorder=
1174 seen_leaf_refs=
1175 seen_leaf_revs=
1176 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1177 [ "$_isleaf" = "1" ] && [ "$_ismissing" = "0" ] || continue
1178 if [ "$_istgish" != "0" ]; then
1179 fulldep="refs/$topbases/$_dep"
1180 else
1181 fulldep="refs/heads/$_dep"
1183 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1184 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1185 if fullrev="$(ref_exists_rev "$fulldep")"; then
1186 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1187 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1188 # See if Git knows it by another name
1189 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1190 echo "refs/tags/$tagname"
1191 else
1192 echo "$fulldep"
1194 esac
1196 esac
1197 done <<-EOT
1198 $(recurse_deps_internal -l -o=1 -- "$1")
1200 with_top_level=
1203 # branch_needs_update
1204 # This is a helper function for determining whether given branch
1205 # is up-to-date wrt. its dependencies. It expects input as if it
1206 # is called as a recurse_deps() helper.
1207 # In case the branch does need update, it will echo it together
1208 # with the branch backtrace on the output (see needs_update()
1209 # description for details) and set $_ret to non-zero.
1210 branch_needs_update()
1212 if [ -n "$_dep_missing" ]; then
1213 echo "! $_dep $_depchain"
1214 return 0
1217 if [ -n "$_dep_is_tgish" ]; then
1218 [ -z "$_dep_annihilated" ] || return 0
1220 if [ -n "$_dep_has_remote" ]; then
1221 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" || {
1222 echo ":refs/remotes/$base_remote/$_dep $_dep $_depchain"
1223 _ret=1
1226 # We want to sync with our base first and should output this before
1227 # the remote branch, but the order does not actually matter to tg-update
1228 # as it just recurses regardless, but it does matter for tg-info (which
1229 # treats out-of-date bases as though they were already merged in) so
1230 # we output the remote before the base.
1231 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1232 echo ": $_dep $_depchain"
1233 _ret=1
1234 return
1238 if [ -n "$_name" ]; then
1239 case "$_dep" in :*) _fulldep="${_dep#:}";; *) _fulldep="refs/heads/$_dep";; esac
1240 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1241 # Some new commits in _dep
1242 echo "$_dep $_depchain"
1243 _ret=1
1248 # needs_update NAME
1249 # This function is recursive; it outputs reverse path from NAME
1250 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1251 # inner paths first. Innermost name can be :refs/remotes/<remote>/<name>
1252 # if the head is not in sync with the <remote> branch <name>, ':' if
1253 # the head is not in sync with the base (in this order of priority)
1254 # or '!' if dependency is missing. Note that the remote branch, base
1255 # order is reversed from the order they will actually be updated in
1256 # order to accomodate tg info which treats out-of-date items that are
1257 # only in the base as already being in the head for status purposes.
1258 # It will also return non-zero status if NAME needs update (seems backwards
1259 # but think of it as non-zero status if any non-missing output lines produced)
1260 # If needs_update() hits missing dependencies, it will append
1261 # them to space-separated $missing_deps list and skip them.
1262 needs_update()
1264 recurse_deps branch_needs_update "$1"
1267 # append second arg to first arg variable gluing with space if first already set
1268 vplus()
1270 eval "$1=\"\${$1:+\$$1 }\$2\""
1273 # true if whitespace separated first var name list contains second arg
1274 # use `vcontains 3 "value" "some list"` for a literal list
1275 vcontains()
1277 eval case "\" \${$1} \"" in '*" $2 "*) return 0; esac; return 1'
1280 # if the $1 var does not already contain $2 it's appended
1281 vsetadd()
1283 vcontains "$1" "$2" || vplus "$1" "$2"
1286 # reset needs_update_check results to empty
1287 needs_update_check_clear()
1289 unset_ needs_update_processed needs_update_behind needs_update_ahead needs_update_partial
1292 # needs_update_check NAME...
1294 # A faster version of needs_update that always succeeds
1295 # No output and unsuitable for actually performing updates themselves
1296 # If any of NAME... are NOT up-to-date AND they were not already processed
1297 # return status always will be zero however a simple check of
1298 # needs_update_behind after the call will answer the:
1299 # "are any out of date?": test -n "$needs_update_behind"
1300 # "is <x> out of date?": vcontains needs_update_behind "<x>"
1302 # Note that results are cumulative and "no_remotes" is honored as well as other
1303 # variables that modify recurse_deps_internal behavior. See the preceding
1304 # function to reset the results to empty when accumulation should start over.
1306 # Unlike needs_update, the branch names are themselves also checked to see if
1307 # they are out-of-date with respect to their bases or remote branches (not just
1308 # their remote bases). However, this can muddy some status results so this
1309 # can be disabled by setting needs_update_check_no_self to a non-empty value.
1311 # Unlike needs_update, here the remote base check is handled together with the
1312 # remote head check so if one is modified the other is too in the same way.
1314 # Dependencies are normally considered "behind" if they need an update from
1315 # their base or remote but this can be suppressed by setting the
1316 # needs_update_check_no_same to a non-empty value. This will NOT prevent
1317 # parents of those dependencies from still being considered behind in such a
1318 # case even though the dependency itself will not be. Note that setting
1319 # needs_update_check_no_same also implies needs_update_check_no_self.
1321 # The following whitespace-separated lists are updated with the results:
1323 # The "no_remotes" setting is obeyed but remote names themselves will never
1324 # appear in any of the lists
1326 # needs_update_processed
1327 # The branch names in here have been processed and will be skipped
1329 # needs_update_behind
1330 # Any branch named in here needs an update from one or more of its
1331 # direct or indirect dependencies (i.e. it's "out-of-date")
1333 # needs_update_ahead
1334 # Any branch named in here is NOT fully contained by at least one of
1335 # its dependents (i.e. it's a source of "out-of-date (aka dirty)"ness
1337 # needs_update_partial
1338 # Any branch names in here are either missing themselves or have one
1339 # or more detected missing dependencies (a completely missing remote
1340 # branch is never "detected")
1341 needs_update_check()
1343 # each head must be processed independently or else there will be
1344 # confusion about who's missing what and which branches actually are
1345 # out of date
1346 tmptgrdi="$tg_tmp_dir/tgrdi.$$"
1347 for nucname in "$@"; do
1348 ! vcontains needs_update_processed "$nucname" || continue
1349 # no need to fuss with recurse_deps, just use
1350 # recurse_deps_internal directly
1351 recurse_deps_internal -s -o=-1 "$nucname" >"$tmptgrdi"
1352 while read -r _rdi_m _rdi_t _rdi_l _rdi_v _rdi_node _rdi_parent _rdi_chain; do
1353 case "$_rdi_node" in ""|:*) continue; esac # empty or checked with remote
1354 vsetadd needs_update_processed "$_rdi_node"
1355 if [ "$_rdi_m" != "0" ]; then # missing
1356 vsetadd needs_update_partial "$_rdi_node"
1357 [ -z "$_rdi_parent" ] || vsetadd needs_update_partial "$_rdi_parent"
1358 continue
1360 [ "$_rdi_t$_rdi_l" != "12" ] || continue # always skip annihilated
1361 _rdi_dertee= # :)
1362 if [ -n "$_rdi_parent" ]; then # not a "self" line
1363 ! vcontains needs_update_partial "$_rdi_node" || vsetadd needs_update_partial "$_rdi_parent"
1364 ! vcontains needs_update_behind "$_rdi_node" || _rdi_dertee=2
1365 else
1366 [ -z "$needs_update_check_no_self$needs_update_check_no_same" ] || continue # skip self
1368 if [ -z "$_rdi_dertee" ]; then
1369 if [ "$_rdi_t" != "0" ]; then # tgish
1370 if branch_contains "refs/heads/$_rdi_node" "refs/$topbases/$_rdi_node"; then
1371 if [ "$_rdi_t" = "2" ]; then # will never be "2" when no_remotes is set
1372 branch_contains "refs/heads/$_rdi_node" "refs/remotes/$base_remote/$_rdi_node" &&
1373 branch_contains "refs/$topbases/$_rdi_node" "refs/remotes/$base_remote/${topbases#heads/}/$_rdi_node" ||
1374 _rdi_dertee=3
1376 else
1377 _rdi_dertee=3
1379 [ -z "$_rdi_dertee" ] || [ -n "$needs_update_check_no_same" ] || _rdi_dertee=1
1382 [ z"$_rdi_dertee" != z"1" ] || vsetadd needs_update_behind "$_rdi_node"
1383 [ -n "$_rdi_parent" ] || continue # self line
1384 if ! branch_contains "refs/$topbases/$_rdi_parent" "refs/heads/$_rdi_node"; then
1385 _rdi_dertee=1
1386 vsetadd needs_update_ahead "$_rdi_node"
1388 [ -z "$_rdi_dertee" ] || vsetadd needs_update_behind "$_rdi_parent"
1389 done <"$tmptgrdi"
1390 done
1393 # branch_empty NAME [-i | -w]
1394 branch_empty()
1396 if [ -z "$2" ]; then
1397 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1398 _result=
1399 _result_rev=
1400 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1401 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
1402 _result=0
1403 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1404 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1405 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1406 return $_result
1407 else
1408 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1412 v_get_tdmopt_internal()
1414 [ -n "$1" ] && [ -n "$3" ] || return 0
1415 [ "$2" = "-i" ] || [ "$2" = "-w" ] || return 0
1416 ensure_work_tree
1417 _optval=
1418 if v_verify_topgit_branch _tghead "HEAD" -f; then
1419 if [ "$2" = "-w" ] && [ -f "$root_dir/$3" ] && [ -r "$root_dir/$3" ]; then
1420 _opthash=
1421 if _opthash="$(git hash-object -w -t blob --stdin <"$root_dir/$3")" && [ -n "$_opthash" ]; then
1422 _optval="$4\"$_tghead:$_opthash\""
1424 elif [ "$2" = "-i" ]; then
1425 if _opthash="$(git rev-parse --quiet --verify ":0:$3" --)" && [ -n "$_opthash" ]; then
1426 _optval="$4\"$_tghead:$_opthash\""
1430 eval "$1="'"$_optval"'
1433 # set var $1 to the correct -td= option for use in an eval for $2 -i or -w mode
1434 v_get_tdopt() { v_get_tdmopt_internal "$1" "$2" ".topdeps" "-td="; }
1436 # set var $1 to the correct -tm= option for use in an eval for $2 -i or -w mode
1437 v_get_tmopt() { v_get_tdmopt_internal "$1" "$2" ".topmsg" "-tm="; }
1439 # checkout_symref_full [-f] FULLREF [SEED]
1440 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1441 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1442 # MUST be a committish which if present will be used instead of current FULLREF
1443 # (and FULLREF will be updated to it as well in that case)
1444 # Any merge state is always cleared by this function
1445 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1446 # instead of -m) but it will clear out any unmerged entries
1447 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1448 checkout_symref_full()
1450 _mode=-m
1451 _head="HEAD"
1452 if [ "$1" = "-f" ]; then
1453 _mode="--reset"
1454 _head=
1455 shift
1457 _ishash=
1458 case "$1" in
1459 refs/?*)
1461 $octet20)
1462 _ishash=1
1463 [ -z "$2" ] || [ "$1" = "$2" ] ||
1464 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1465 set -- HEAD "$1"
1468 die "programmer error: invalid checkout_symref_full \"$1\""
1470 esac
1471 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1472 die "invalid committish: \"${2:-$1}\""
1473 # Clear out any MERGE_HEAD kruft
1474 rm -f "$git_dir/MERGE_HEAD" || :
1475 # We have to do all the hard work ourselves :/
1476 # This is like git checkout -b "$1" "$2"
1477 # (or just git checkout "$1"),
1478 # but never creates a detached HEAD (unless $1 is a hash)
1479 git read-tree -u $_mode $_head "$_seedrev" &&
1481 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1482 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1483 } && {
1484 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1488 # switch_to_base NAME [SEED]
1489 switch_to_base()
1491 checkout_symref_full "refs/$topbases/$1" "$2"
1494 # run editor with arguments
1495 # the editor setting will be cached in $tg_editor (which is eval'd)
1496 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1497 # just in case, noalt_setup will be in effect while the editor is running
1498 run_editor()
1500 tg_editor="$GIT_EDITOR"
1501 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1503 noalt_setup
1504 eval "$tg_editor" '"$@"'
1508 # Show the help messages.
1509 do_help()
1511 _www=
1512 if [ "$1" = "-w" ]; then
1513 _www=1
1514 shift
1516 if [ -z "$1" ] ; then
1517 # This is currently invoked in all kinds of circumstances,
1518 # including when the user made a usage error. Should we end up
1519 # providing more than a short help message, then we should
1520 # differentiate.
1521 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1523 ## Build available commands list for help output
1525 cmds=
1526 sep=
1527 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1528 ! [ -r "$cmd" ] && continue
1529 # strip directory part and "tg-" prefix
1530 cmd="${cmd##*/}"
1531 cmd="${cmd#tg-}"
1532 [ "$cmd" != "migrate-bases" ] || continue
1533 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1534 cmds="$cmds$sep$cmd"
1535 sep="|"
1536 done
1538 echo "TopGit version $TG_VERSION - A different patch queue manager"
1539 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u]" \
1540 "[-c <name>=<val>] [--[no-]pager|-p] [-w [:]<tgtag>] ($cmds) ..."
1541 echo " Or: $tgname help [-w] [<command>]"
1542 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1543 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1544 if [ -n "$_www" ]; then
1545 nohtml=
1546 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1547 echo "${0##*/}: missing html help file:" \
1548 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1549 nohtml=1
1551 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1552 echo "${0##*/}: missing html help file:" \
1553 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1554 nohtml=1
1556 if [ -n "$nohtml" ]; then
1557 echo "${0##*/}: use" \
1558 "\"${0##*/} help $1\" instead" 1>&2
1559 exit 1
1561 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1562 exit
1564 output()
1566 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1567 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1568 echo
1569 elif [ "$1" = "help" ]; then
1570 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1571 echo
1572 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1573 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1574 echo
1576 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1577 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1580 page output "$1"
1581 else
1582 echo "${0##*/}: no help for $1" 1>&2
1583 do_help
1584 exit 1
1588 check_status()
1590 git_state=
1591 git_remove=
1592 tg_state=
1593 tg_remove=
1594 tg_topmerge=
1595 setup_git_dir_is_bare
1596 [ -z "$git_dir_is_bare" ] || return 0
1598 if [ -e "$git_dir/MERGE_HEAD" ]; then
1599 git_state="merge"
1600 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1601 git_state="am"
1602 git_remove="$git_dir/rebase-apply"
1603 elif [ -e "$git_dir/rebase-apply" ]; then
1604 git_state="rebase"
1605 git_remove="$git_dir/rebase-apply"
1606 elif [ -e "$git_dir/rebase-merge" ]; then
1607 git_state="rebase"
1608 git_remove="$git_dir/rebase-merge"
1609 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1610 git_state="cherry-pick"
1611 elif [ -e "$git_dir/BISECT_LOG" ]; then
1612 git_state="bisect"
1613 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1614 git_state="revert"
1616 git_remove="${git_remove#./}"
1618 if [ -e "$git_dir/tg-update" ]; then
1619 tg_state="update"
1620 tg_remove="$git_dir/tg-update"
1621 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1623 tg_remove="${tg_remove#./}"
1626 # Show status information
1627 do_status()
1629 do_status_result=0
1630 do_status_verbose=
1631 do_status_help=
1632 abbrev=refs
1633 pfx=
1634 while [ $# -gt 0 ] && case "$1" in
1635 --help|-h)
1636 do_status_help=1
1637 break;;
1638 -vv)
1639 # kludge in this common bundling option
1640 abbrev=
1641 do_status_verbose=1
1642 pfx="## "
1644 --verbose|-v)
1645 [ -z "$do_status_verbose" ] || abbrev=
1646 do_status_verbose=1
1647 pfx="## "
1649 --exit-code)
1650 do_status_result=2
1653 die "unknown status argument: $1"
1655 esac; do shift; done
1656 if [ -n "$do_status_help" ]; then
1657 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1658 return
1660 check_status
1661 symref="$(git symbolic-ref --quiet HEAD)" || :
1662 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1663 if [ -n "$symref" ]; then
1664 uprefpart=
1665 if [ -n "$headrv" ]; then
1666 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1667 if [ -n "$upref" ]; then
1668 uprefpart=" ... ${upref#$abbrev/remotes/}"
1669 mbase="$(git merge-base HEAD "$upref")" || :
1670 ahead="$(git rev-list --count HEAD ${mbase:+--not $mbase})" || ahead=0
1671 behind="$(git rev-list --count "$upref" ${mbase:+--not $mbase})" || behind=0
1672 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1673 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1674 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1675 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1676 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1679 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1680 else
1681 echol "${pfx}HEAD -> ${headrv:-?}"
1683 if [ -n "$tg_state" ]; then
1684 extra=
1685 if [ "$tg_state" = "update" ]; then
1686 IFS= read -r uname <"$git_dir/tg-update/name" || :
1687 [ -z "$uname" ] ||
1688 extra="; currently updating branch '$uname'"
1690 echol "${pfx}tg $tg_state in progress$extra"
1691 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1692 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1693 cat "$git_dir/tg-update/fullcmd"
1694 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1695 if [ $bcnt -gt 1 ]; then
1696 pcnt=0
1697 ! [ -s "$git_dir/tg-update/processed" ] ||
1698 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1699 echo "${pfx}$pcnt of $bcnt branches updated so far"
1702 if [ "$tg_state" = "update" ]; then
1703 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1704 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1705 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1706 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1709 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1710 if [ "$git_state" = "merge" ]; then
1711 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1712 if [ $ucnt -gt 0 ]; then
1713 echo "${pfx}"'fix conflicts and then "git commit" the result'
1714 else
1715 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1718 if [ -z "$git_state" ]; then
1719 setup_git_dir_is_bare
1720 [ -z "$git_dir_is_bare" ] || return 0
1721 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository???
1722 gspcnt=0
1723 [ -z "$gsp" ] ||
1724 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1725 untr=
1726 if [ "$gspcnt" -eq 0 ]; then
1727 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1728 echo "${pfx}working directory is clean$untr"
1729 [ -n "$tg_state" ] || do_status_result=0
1730 else
1731 echo "${pfx}working directory is DIRTY"
1732 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1737 ## Pager stuff
1739 # isatty FD
1740 isatty()
1742 test -t $1
1745 # pass "diff" to get pager.diff
1746 # if pager.$1 is a boolean false returns cat
1747 # if set to true or unset fails
1748 # otherwise succeeds and returns the value
1749 get_pager()
1751 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1752 [ "$_x" != "true" ] || return 1
1753 echo "cat"
1754 return 0
1756 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1757 echol "$_x"
1758 return 0
1760 return 1
1763 # setup_pager
1764 # Set TG_PAGER to a valid executable
1765 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1766 # See also the following "page" function for ease of use
1767 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1768 # Preference is (same as Git):
1769 # 1. GIT_PAGER
1770 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1771 # 3. core.pager (only if set)
1772 # 4. PAGER
1773 # 5. git var GIT_PAGER
1774 # 6. less
1775 setup_pager()
1777 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1779 emptypager=
1780 if [ -z "$TG_PAGER_IN_USE" ]; then
1781 # TG_PAGER = GIT_PAGER | PAGER | less
1782 # NOTE: GIT_PAGER='' is significant
1783 if [ -n "${GIT_PAGER+set}" ]; then
1784 TG_PAGER="$GIT_PAGER"
1785 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1786 TG_PAGER="$_dp"
1787 elif _cp="$(git config core.pager 2>/dev/null)"; then
1788 TG_PAGER="$_cp"
1789 elif [ -n "${PAGER+set}" ]; then
1790 TG_PAGER="$PAGER"
1791 else
1792 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1793 [ "$_gp" != ":" ] || _gp=
1794 TG_PAGER="${_gp:-less}"
1796 if [ -z "$TG_PAGER" ]; then
1797 emptypager=1
1798 TG_PAGER=cat
1800 else
1801 emptypager=1
1802 TG_PAGER=cat
1805 # Set pager default environment variables
1806 # see pager.c:setup_pager
1807 if [ -z "${LESS+set}" ]; then
1808 LESS="-FRX"
1809 export LESS
1811 if [ -z "${LV+set}" ]; then
1812 LV="-c"
1813 export LV
1816 # this is needed so e.g. $(git diff) will still colorize it's output if
1817 # requested in ~/.gitconfig with color.diff=auto
1818 GIT_PAGER_IN_USE=1
1819 export GIT_PAGER_IN_USE
1821 # this is needed so we don't get nested pagers
1822 TG_PAGER_IN_USE=1
1823 export TG_PAGER_IN_USE
1826 # page eval_arg [arg ...]
1828 # Calls setup_pager then evals the first argument passing it all the rest
1829 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1830 # by setup_pager (in which case the output is left as-is).
1832 # To handle arbitrary paging duties, collect lines to be paged into a
1833 # function and then call page with the function name or perhaps func_name "$@".
1835 # If no arguments at all are passed in do nothing (return with success).
1836 page()
1838 [ $# -gt 0 ] || return 0
1839 setup_pager
1840 _evalarg="$1"; shift
1841 if [ -n "$emptypager" ]; then
1842 eval "$_evalarg" '"$@"'
1843 else
1844 { eval "$_evalarg" '"$@"';} | eval "$TG_PAGER"
1848 # get_temp NAME [-d]
1849 # creates a new temporary file (or directory with -d) in the global
1850 # temporary directory $tg_tmp_dir with pattern prefix NAME
1851 get_temp()
1853 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1856 # automatically called by strftime
1857 # does nothing if already setup
1858 # may be called explicitly if the first call would otherwise be in a subshell
1859 # so that the setup is only done once before subshells start being spawned
1860 setup_strftime()
1862 [ -z "$strftime_is_setup" ] || return 0
1864 # date option to format raw epoch seconds values
1865 daterawopt=
1866 _testes='951807788'
1867 _testdt='2000-02-29 07:03:08 UTC'
1868 _testfm='%Y-%m-%d %H:%M:%S %Z'
1869 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1870 daterawopt='-d@'
1871 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1872 daterawopt='-r'
1874 strftime_is_setup=1
1877 # $1 => strftime format string to use
1878 # $2 => raw timestamp as seconds since epoch
1879 # $3 => optional time zone string (empty/absent for local time zone)
1880 strftime()
1882 setup_strftime
1883 if [ -n "$daterawopt" ]; then
1884 if [ -n "$3" ]; then
1885 TZ="$3" date "$daterawopt$2" "+$1"
1886 else
1887 date "$daterawopt$2" "+$1"
1889 else
1890 if [ -n "$3" ]; then
1891 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1892 else
1893 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1898 got_cdup_result=
1899 git_cdup_result=
1900 v_get_show_cdup()
1902 if [ -z "$got_cdup_result" ]; then
1903 git_cdup_result="$(git rev-parse --show-cdup)"
1904 got_cdup_result=1
1906 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1909 setup_git_dir_is_bare()
1911 if [ -z "$git_dir_is_bare_setup" ]; then
1912 git_dir_is_bare="$(git rev-parse --is-bare-repository)"
1913 [ z"$git_dir_is_bare" = z"true" ] || git_dir_is_bare=
1914 git_dir_is_bare_setup=1
1918 setup_git_dirs()
1920 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1921 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1922 git_dir="$(cd "$git_dir" && pwd)"
1924 if [ -z "$git_common_dir" ]; then
1925 if vcmp "$git_version" '>=' "2.5"; then
1926 # rev-parse --git-common-dir is broken and may give
1927 # an incorrect result unless the current directory is
1928 # already set to the top level directory
1929 v_get_show_cdup
1930 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1931 else
1932 git_common_dir="$git_dir"
1935 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1936 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1937 git_hooks_dir="$git_common_dir/hooks"
1938 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1939 case "$gchp" in
1940 /[!/]*)
1941 git_hooks_dir="$gchp"
1944 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1946 esac
1947 unset_ gchp
1951 basic_setup_remote()
1953 if [ -z "$base_remote" ]; then
1954 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
1955 base_remote="$TG_EXPLICIT_REMOTE"
1956 else
1957 base_remote="$(git config topgit.remote 2>/dev/null)" || :
1962 basic_setup()
1964 setup_git_dirs $1
1965 basic_setup_remote
1966 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1967 tgnosequester=
1968 [ "$tgsequester" != "false" ] || tgnosequester=1
1969 unset_ tgsequester
1971 # catch errors if topbases is used without being set
1972 unset_ tg_topbases_set
1973 topbases="programmer*:error"
1974 topbasesrx="programmer*:error}"
1975 oldbases="$topbases"
1978 tmpdir_setup()
1980 [ -z "$tg_tmp_dir" ] || return 0
1981 if [ -n "$TG_TMPDIR" ] && [ -d "$TG_TMPDIR" ] && [ -w "$TG_TMPDIR" ] &&
1982 { >"$TG_TMPDIR/.check"; } >/dev/null 2>&1; then
1983 tg_tmp_dir="$TG_TMPDIR"
1984 else
1985 tg_tmp_dir=
1986 TRAPEXIT_='${TG_DEBUG:+echo} rm -rf "$tg_tmp_dir" >&2'
1987 trap 'trapexit_ 129' HUP
1988 trap 'trapexit_ 130' INT
1989 trap 'trapexit_ 131' QUIT
1990 trap 'trapexit_ 134' ABRT
1991 trap 'trapexit_ 141' PIPE
1992 trap 'trapexit_ 143' TERM
1993 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1994 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1995 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1996 [ -z "$tg_tmp_dir" ] || tg_tmp_dir="$(cd "$tg_tmp_dir" && pwd -P)"
1998 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_tmp_dir/.check"; } >/dev/null 2>&1 ||
1999 die "could not create a writable temporary directory"
2001 # whenever tg_tmp_dir is != "" these must always be set
2002 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
2003 tg_ref_cache_br="$tg_ref_cache.br"
2004 tg_ref_cache_rbr="$tg_ref_cache.rbr"
2005 tg_ref_cache_ann="$tg_ref_cache.ann"
2006 tg_ref_cache_dep="$tg_ref_cache.dep"
2009 cachedir_setup()
2011 [ -z "$tg_cache_dir" ] || return 0
2012 user_id_no="$(id -u)" || :
2013 : "${user_id_no:=_99_}"
2014 tg_cache_dir="$git_common_dir/tg-cache"
2015 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2016 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
2017 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2018 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2019 if [ -z "$tg_cache_dir" ]; then
2020 tg_cache_dir="$tg_tmp_dir/tg-cache"
2021 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2022 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2024 [ -n "$tg_cache_dir" ] ||
2025 die "could not create a writable tg-cache directory (even a temporary one)"
2027 if [ -n "$2" ]; then
2028 # allow the wayback machine to share a separate cache
2029 [ -d "$tg_cache_dir/wayback" ] || mkdir "$tg_cache_dir/wayback" >/dev/null 2>&1 || :
2030 ! [ -d "$tg_cache_dir/wayback" ] || ! { >"$tg_cache_dir/wayback/.tgcache"; } >/dev/null 2>&1 ||
2031 tg_cache_dir="$tg_cache_dir/wayback"
2035 # set up alternate deb dirs
2036 altodb_setup()
2038 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
2039 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
2040 # so we avoid it if possible and require v2.11.1 to do it at all
2041 # otherwise just don't make an alternates temporary store in that case;
2042 # it's okay to not have one; everything will still work; the nicety of
2043 # making the temporary tree objects vanish when tg exits just won't
2044 # happen in that case but nothing will break also be sure to reuse
2045 # the parent's if we've been recursively invoked and it's for the
2046 # same repository we were invoked on
2048 tg_use_alt_odb=1
2049 _fullodbdir=
2050 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
2051 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] && _fullodbdir="$(cd "$_odbdir" && pwd -P)" ||
2052 die "could not find objects directory"
2053 if [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
2054 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
2055 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
2056 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
2057 tg_use_alt_odb=2
2060 _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
2061 if [ "$tg_use_alt_odb" = "1" ]; then
2062 # create an alternate objects database to keep the ephemeral objects in
2063 mkdir -p "$tg_tmp_dir/objects/info"
2064 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
2065 [ "$_fullodbdir" = "$TG_OBJECT_DIRECTORY" ] ||
2066 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
2068 case "$_fulltmpdir" in *[";:"]*|'"'*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
2069 if [ "$tg_use_alt_odb" = "1" ]; then
2070 case "$TG_OBJECT_DIRECTORY" in
2071 *[";:"]*|'"'*)
2072 # surround in "..." and backslash-escape internal '"' and '\\'
2073 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
2074 sed 's/\([""\\]\)/\\\1/g')\""
2077 _altodbdq="$TG_OBJECT_DIRECTORY"
2079 esac
2080 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2081 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2082 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2083 else
2084 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
2086 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
2087 if [ -n "$GIT_OBJECT_DIRECTORY" ]; then
2088 export GIT_OBJECT_DIRECTORY
2089 else
2090 unset_ GIT_OBJECT_DIRECTORY
2095 noalt_setup()
2097 if [ "${TG_PRESERVED_ALTERNATES+set}" = "set" ]; then
2098 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
2099 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2100 export GIT_ALTERNATE_OBJECT_DIRECTORIES
2101 else
2102 unset_ GIT_ALTERNATE_OBJECT_DIRECTORIES
2105 unset_ TG_TMPDIR TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES tg_use_alt_odb
2108 ## Initial setup
2109 initial_setup()
2111 # suppress the merge log editor feature since git 1.7.10
2113 GIT_MERGE_AUTOEDIT=no
2114 export GIT_MERGE_AUTOEDIT
2116 basic_setup $1
2117 iowopt=
2118 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
2119 gcfbopt=
2120 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
2121 auhopt=
2122 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
2123 v_get_show_cdup root_dir
2124 root_dir="${root_dir:-.}"
2125 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
2126 [ "$logrefupdates" = "true" ] || logrefupdates=
2128 # make sure root_dir doesn't end with a trailing slash.
2130 root_dir="${root_dir%/}"
2132 # create global temporary and cache directories, usually inside GIT_DIR
2134 tmpdir_setup
2135 unset_ TG_TMPDIR
2136 cachedir_setup
2138 # the wayback machine directory serves as its own "altodb"
2139 [ -n "$wayback" ] || altodb_setup
2142 activate_wayback_machine()
2144 [ -n "${1#:}" ] || [ -n "$2" ] || { wayback=; return 0; }
2145 setup_git_dirs
2146 tmpdir_setup
2147 altodb_setup
2148 tgwbr=
2149 tgwbr2=
2150 if [ -n "${1#:}" ]; then
2151 tgwbr="$(get_temp wbinfo)"
2152 tgwbr2="${tgwbr}2"
2153 tg revert --list --no-short "${1#:}" >"$tgwbr" && test -s "$tgwbr" || return 1
2154 # tg revert will likely leave a revert-tag-only cache which is not what we want
2155 remove_ref_cache
2157 cachedir_setup "" 1 # use a separate wayback cache dir
2158 # but don't step on the normal one if the separate one could not be set up
2159 case "$tg_cache_dir" in */wayback);;*) tg_cache_dir=; esac
2160 altodb="$TG_OBJECT_DIRECTORY"
2161 if [ -n "$3" ] && [ -n "$2" ]; then
2162 [ -d "$3" ] || { mkdir -p "$3" && [ -d "$3" ]; } ||
2163 die "could not create wayback directory: $3"
2164 tg_wayback_dir="$(cd "$3" && pwd -P)" || die "could not get wayback directory full path"
2165 [ -d "$tg_wayback_dir/.git" ] || { mkdir -p "$tg_wayback_dir/.git" && [ -d "$tg_wayback_dir/.git" ]; } ||
2166 die "could not initialize wayback directory: $3"
2167 is_empty_dir "$tg_wayback_dir" ".git" && is_empty_dir "$tg_wayback_dir/.git" "." ||
2168 die "wayback directory is not empty: $3"
2169 mkdir "$tg_wayback_dir/.git/objects"
2170 mkdir "$tg_wayback_dir/.git/objects/info"
2171 cat "$altodb/info/alternates" >"$tg_wayback_dir/.git/objects/info/alternates"
2172 else
2173 tg_wayback_dir="$tg_tmp_dir/wayback"
2174 mkdir "$tg_wayback_dir"
2175 mkdir "$tg_wayback_dir/.git"
2176 ln -s "$altodb" "$tg_wayback_dir/.git/objects"
2178 mkdir "$tg_wayback_dir/.git/refs"
2179 printf '0 Wayback Machine' >"$tg_wayback_dir/.git/gc.pid"
2180 qpesc="$(printf '%s\n' "$git_common_dir" | sed -e 's/\([\\""]\)/\\\1/g' -e '$!s/$/\\n/' | tr -d '\n')"
2181 laru="false"
2182 [ -z "$2" ] || laru="true"
2183 printf '%s' "\
2184 [include]
2185 path = \"$qpesc/config\"
2186 [core]
2187 bare = false
2188 logAllRefUpdates = $laru
2189 repositoryFormatVersion = 0
2190 [extensions]
2191 preciousObjects = true
2192 [gc]
2193 auto = 0
2194 autoDetach = false
2195 autoPackLimit = 0
2196 packRefs = false
2197 [remote \"wayback\"]
2198 url = \"$qpesc\"
2199 [push]
2200 default = nothing
2201 followTags = true
2202 [alias]
2203 wayback-updates = fetch --force --no-tags --dry-run wayback refs/*:refs/*
2204 " >"$tg_wayback_dir/.git/config"
2205 cat "$git_dir/HEAD" >"$tg_wayback_dir/.git/HEAD"
2206 case "$1" in ":"?*);;*)
2207 git show-ref >"$tg_wayback_dir/.git/packed-refs"
2208 git --git-dir="$tg_wayback_dir/.git" pack-refs --all
2209 esac
2210 noalt_setup
2211 TG_OBJECT_DIRECTORY="$altodb" && export TG_OBJECT_DIRECTORY
2212 if [ -n "${1#:}" ]; then
2213 <"$tgwbr" sed 's/^\([^ ][^ ]*\) \([^ ][^ ]*\)$/update \2 \1/' |
2214 git --git-dir="$tg_wayback_dir/.git" update-ref -m "wayback to $1" ${2:+--create-reflog} --stdin
2216 if test -n "$2"; then
2217 # extra setup for potential shell
2218 qpesc2="$(printf '%s\n' "$git_common_dir" | sed -e 's/\([\\""]\)/\\\\\1/g' -e '$!s/$/\\n/' | tr -d '\n')"
2219 printf '\twayback-repository = "!printf '\''%%s\\\\n'\'' \\"%s\\""\n' "$qpesc2" >>"$tg_wayback_dir/.git/config"
2220 qtesc="$(printf '%s\n' "${1:-:}" | sed 's/\([""]\)/\\\1/g')"
2221 printf '\twayback-tag = "!printf '\''%%s\\\\n'\'' \\"%s\\""\n' "$qtesc" >>"$tg_wayback_dir/.git/config"
2222 if [ -d "$git_common_dir/rr-cache" ]; then
2223 ln -s "$git_common_dir/rr-cache" "$tg_wayback_dir/.git/rr-cache"
2224 printf "[rerere]\n\tenabled = true\n" >>"$tg_wayback_dir/.git/config"
2226 if [ z"$2" != z"2" ]; then
2227 wbauth=
2228 wbprnt=
2229 if [ -n "${1#:}" ]; then
2230 [ -n "$tgwbr2" ] || tgwbr2="$(get_temp wbtag)"
2231 git --git-dir="$git_common_dir" cat-file tag "${1#:}" >"$tgwbr2" || return 1
2232 wbprnt="${lf}parent $(git --git-dir="$git_common_dir" rev-parse --verify --quiet "${1#:}"^0 -- 2>/dev/null)" || wbprnt=
2233 wbauth="$(<"$tgwbr2" awk '{if(!$0)exit;if($1=="tagger")print "author" substr($0,7)}')"
2235 wbcmtr="committer Wayback Machine <-> $(date "+%s %z")"
2236 [ -n "$wbauth" ] || wbauth="author${wbcmtr#committer}"
2237 wbtree="$(git --git-dir="$tg_wayback_dir/.git" mktree </dev/null)"
2238 wbcmt="$({
2239 printf '%s\n' "tree $wbtree$wbprnt" "$wbauth" "$wbcmtr" ""
2240 if [ -n "$tgwbr2" ]; then
2241 <"$tgwbr2" sed -e '1,/^$/d' -e '/^-----BEGIN/,$d' | git stripspace
2242 else
2243 echo "Wayback Machine"
2245 } | git --git-dir="$tg_wayback_dir/.git" hash-object -t commit -w --stdin)"
2246 test -n "$wbcmt" || return 1
2247 echo "$wbcmt" >"$tg_wayback_dir/.git/HEAD"
2250 cd "$tg_wayback_dir"
2251 unset git_dir git_common_dir
2254 set_topbases()
2256 # refer to "top-bases" in a refname with $topbases
2258 [ -z "$tg_topbases_set" ] || return 0
2260 topbases_implicit_default=1
2261 # See if topgit.top-bases is set to heads or refs
2262 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
2263 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
2264 if [ -n "$1" ]; then
2265 # never die on the hook script
2266 unset_ tgtb
2267 else
2268 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
2271 if [ -n "$tgtb" ]; then
2272 case "$tgtb" in
2273 heads)
2274 topbases="heads/{top-bases}"
2275 topbasesrx="heads/[{]top-bases[}]"
2276 oldbases="top-bases";;
2277 refs)
2278 topbases="top-bases"
2279 topbasesrx="top-bases"
2280 oldbases="heads/{top-bases}";;
2281 esac
2282 # MUST NOT be exported
2283 unset_ tgtb tg_topbases_set topbases_implicit_default
2284 tg_topbases_set=1
2285 return 0
2287 unset_ tgtb
2289 # check heads and top-bases and see what state the current
2290 # repository is in. remotes are ignored.
2292 rc=0 activebases=
2293 activebases="$(
2294 git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null |
2295 run_awk_ref_prefixes ${1:+-e} -n -- "refs/heads/{top-bases}" "refs/top-bases" "refs/heads")" ||
2296 rc=$?
2297 if [ "$rc" = "65" ]; then
2298 # Complain and die
2299 err "repository contains existing TopGit branches"
2300 err "but some use refs/top-bases/... for the base"
2301 err "and some use refs/heads/{top-bases}/... for the base"
2302 err "with the latter being the new, preferred location"
2303 err "set \"topgit.top-bases\" to either \"heads\" to use"
2304 err "the new heads/{top-bases} location or \"refs\" to use"
2305 err "the old top-bases location."
2306 err "(the tg migrate-bases command can also resolve this issue)"
2307 die "schizophrenic repository requires topgit.top-bases setting"
2309 [ -z "$activebases" ] || unset_ topbases_implicit_default
2310 if [ "$activebases" = "refs/heads/{top-bases}" ]; then
2311 topbases="heads/{top-bases}"
2312 topbasesrx="heads/[{]top-bases[}]"
2313 oldbases="top-bases"
2314 else
2315 # default is still top-bases for now
2316 topbases="top-bases"
2317 topbasesrx="top-bases"
2318 oldbases="heads/{top-bases}"
2320 # MUST NOT be exported
2321 unset_ rc activebases tg_topases_set
2322 tg_topbases_set=1
2323 return 0
2326 # $1 is remote name to check
2327 # $2 is optional variable name to set to result of check
2328 # $3 is optional command name to use in message (defaults to $cmd)
2329 # Fatal error if remote has schizophrenic top-bases
2330 # No error (and $2, if provided, will be set to empty) if remote has no top-bases at all
2331 check_remote_topbases()
2333 [ -n "$1" ] || die "programmer error: check_remote_topbases called with no remote argument"
2334 _crrc=0 _crremotebases=
2335 _crremotebases="$(
2336 git for-each-ref --format='%(refname)' "refs/remotes/$1" 2>/dev/null |
2337 run_awk_ref_prefixes -n -- "refs/remotes/$1/{top-bases}" "refs/remotes/$1/top-bases" "refs/remotes/$1")" ||
2338 _crrc=$?
2339 if [ "$_crrc" = "65" ]; then
2340 err "remote \"$1\" has top-bases in both locations:"
2341 err " refs/remotes/$1/{top-bases}/..."
2342 err " refs/remotes/$1/top-bases/..."
2343 err "set \"topgit.top-bases\" to \"heads\" for the first, preferred location"
2344 err "or set \"topgit.top-bases\" to \"refs\" for the second, old location"
2345 err "(the \"-c topgit.top-bases=<val>\" option can be used for this)"
2346 err "then re-run the tg ${3:-$cmd} command"
2347 err "(the tg migrate-bases command can also help with this problem)"
2348 die "schizophrenic remote \"$1\" requires topgit.top-bases setting"
2350 [ "$_crrc" != "66" ] || _crremotebases= # just to be sure
2351 [ -z "$2" ] || eval "$2="'"$_crremotebases"'
2352 unset _crrc _crremotebases
2353 return 0
2356 # init_reflog "ref"
2357 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
2358 # an empty log file to exist so that ref changes will be logged
2359 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
2360 # However, if "$1" is "refs/tgstash" then always make the reflog
2361 # The only ref not under refs/ that Git will write a reflog for is HEAD;
2362 # no matter what, it will NOT update a reflog for any other bare refs so
2363 # just quietly succeed when passed TG_STASH without doing anything.
2364 init_reflog()
2366 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
2367 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
2368 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
2369 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
2370 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
2373 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
2374 # a symbolic link. The directory part must exist, but the basename need not.
2375 v_get_abs_path()
2377 [ -n "$1" ] && [ -n "$2" ] || return 1
2378 set -- "$1" "$2" "${2%/}"
2379 case "$3" in
2380 */*) set -- "$1" "$2" "${3%/*}";;
2381 * ) set -- "$1" "$2" ".";;
2382 esac
2383 case "$2" in */)
2384 set -- "$1" "${2%/}" "$3" "/"
2385 esac
2386 [ -d "$3" ] || return 1
2387 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
2390 ## Startup
2392 : "${TG_INST_CMDDIR:=@cmddir@}"
2393 : "${TG_INST_SHAREDIR:=@sharedir@}"
2394 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
2396 [ -d "$TG_INST_CMDDIR" ] ||
2397 die "No command directory: '$TG_INST_CMDDIR'"
2399 ## Include awk scripts and their utility functions (separated for easier debugging)
2401 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
2402 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
2403 . "$TG_INST_CMDDIR/tg--awksome"
2405 if [ -n "$tg__include" ]; then
2407 # We were sourced from another script for our utility functions;
2408 # this is set by hooks. Skip the rest of the file. A simple return doesn't
2409 # work as expected in every shell. See http://bugs.debian.org/516188
2411 # ensure setup happens
2413 initial_setup 1
2414 set_topbases 1
2415 noalt_setup
2417 else
2419 set -e
2421 tgbin="$0"
2422 tgdir="${tgbin%/}"
2423 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
2424 tgdir="${tgdir%/*}/"
2425 tgname="${tgbin##*/}"
2426 [ "$0" != "$tgname" ] || tgdir=""
2428 # If tg contains a '/' but does not start with one then replace it with an absolute path
2430 case "$0" in /*) ;; */*)
2431 tgdir="$(cd "${0%/*}" && pwd -P)/"
2432 tgbin="$tgdir$tgname"
2433 esac
2435 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
2436 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2438 tgdisplaydir="$tgdir"
2439 tgdisplay="$tgbin"
2440 tgdisplayac="$tgdisplay"
2442 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2443 _tgabs="$_tgnameabs" &&
2444 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2445 [ "$_tgabs" = "$_tgnameabs" ]
2446 then
2447 tgdisplaydir=""
2448 tgdisplay="$tgname"
2449 tgdisplayac="$tgdisplay"
2451 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2452 unset_ _tgabs _tgnameabs
2454 tg() (
2455 TG_TMPDIR="$tg_tmp_dir" && export TG_TMPDIR &&
2456 exec "$tgbin" "$@"
2459 explicit_remote=
2460 explicit_dir=
2461 gitcdopt=
2462 noremote=
2463 forcepager=
2464 wayback=
2466 cmd=
2467 while :; do case "$1" in
2469 help|--help|-h)
2470 cmd=help
2471 shift
2472 break;;
2474 status|--status)
2475 cmd=status
2476 shift
2477 break;;
2479 --hooks-path)
2480 cmd=hooks-path
2481 shift
2482 break;;
2484 --exec-path)
2485 cmd=exec-path
2486 shift
2487 break;;
2489 --awk-path)
2490 cmd=awk-path
2491 shift
2492 break;;
2494 --top-bases)
2495 cmd=top-bases
2496 shift
2497 break;;
2499 --no-pager)
2500 forcepager=0
2501 shift;;
2503 --pager|-p)
2504 forcepager=1
2505 shift;;
2508 shift
2509 if [ -z "$1" ]; then
2510 echo "Option -r requires an argument." >&2
2511 do_help
2512 exit 1
2514 unset_ noremote
2515 base_remote="$1"
2516 explicit_remote="$base_remote"
2517 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2518 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2519 shift;;
2522 unset_ base_remote explicit_remote
2523 noremote=1
2524 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2525 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2526 shift;;
2529 shift
2530 if [ -z "$1" ]; then
2531 echo "Option -C requires an argument." >&2
2532 do_help
2533 exit 1
2535 cd "$1"
2536 unset_ GIT_DIR GIT_COMMON_DIR
2537 if [ -z "$explicit_dir" ]; then
2538 explicit_dir="$1"
2539 else
2540 explicit_dir="$PWD"
2542 gitcdopt=" -C \"$explicit_dir\""
2543 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2544 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2545 tgdisplayac="$tgdisplay"
2546 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2547 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2548 shift;;
2551 shift
2552 if [ -z "$1" ]; then
2553 echo "Option -c requires an argument." >&2
2554 do_help
2555 exit 1
2557 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2558 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2559 export GIT_CONFIG_PARAMETERS
2560 shift;;
2563 if [ -n "$wayback" ]; then
2564 echo "Option -w may be used at most once." >&2
2565 do_help
2566 exit 1
2568 shift
2569 if [ -z "$1" ]; then
2570 echo "Option -w requires an argument." >&2
2571 do_help
2572 exit 1
2574 wayback="$1"
2575 shift;;
2578 shift
2579 break;;
2582 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2583 do_help
2584 exit 1;;
2587 break;;
2589 esac; done
2590 if [ z"$forcepager" = z"0" ]; then
2591 GIT_PAGER_IN_USE=1 TG_PAGER_IN_USE=1 &&
2592 export GIT_PAGER_IN_USE TG_PAGER_IN_USE
2595 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
2597 ## Dispatch
2599 [ -n "$cmd" ] || { do_help; exit 1; }
2601 case "$cmd" in
2603 help)
2604 do_help "$@"
2605 exit 0;;
2607 status|st)
2608 unset_ base_remote
2609 basic_setup
2610 set_topbases
2611 do_status "$@"
2612 exit ${do_status_result:-0};;
2614 hooks-path)
2615 # Internal command
2616 echol "$TG_INST_HOOKSDIR";;
2618 exec-path)
2619 # Internal command
2620 echol "$TG_INST_CMDDIR";;
2622 awk-path)
2623 # Internal command
2624 echol "$TG_INST_CMDDIR/awk";;
2626 top-bases)
2627 # Maintenance command
2628 do_topbases_help=
2629 show_remote_topbases=
2630 case "$1" in
2631 --help|-h)
2632 do_topbases_help=0;;
2633 -r|--remote)
2634 if [ $# -eq 2 ] && [ -n "$2" ]; then
2635 # unadvertised, but make it work
2636 base_remote="$2"
2637 shift
2639 show_remote_topbases=1;;
2641 [ $# -eq 0 ] || do_topbases_help=1;;
2642 esac
2643 [ $# -le 1 ] || do_topbases_help=1
2644 if [ -n "$do_topbases_help" ]; then
2645 helpcmd='echo "Usage: ${tgname:-tg} [-r <remote>] --top-bases [-r]"'
2646 [ $do_topbases_help -eq 0 ] || helpcmd="$helpcmd >&2"
2647 eval "$helpcmd"
2648 exit $do_topbases_help
2650 git_dir=
2651 if git_dir="$(git rev-parse --git-dir 2>&1)"; then
2652 [ -z "$wayback" ] || activate_wayback_machine "$wayback"
2653 setup_git_dirs
2655 set_topbases
2656 if [ -n "$show_remote_topbases" ]; then
2657 basic_setup_remote
2658 [ -n "$base_remote" ] ||
2659 die "no remote location given. Either use -r <remote> option or set topgit.remote"
2660 rbases=
2661 [ -z "$topbases_implicit_default" ] ||
2662 check_remote_topbases "$base_remote" rbases "--top-bases"
2663 if [ -n "$rbases" ]; then
2664 echol "$rbases"
2665 else
2666 echol "refs/remotes/$base_remote/${topbases#heads/}"
2668 else
2669 echol "refs/$topbases"
2670 fi;;
2673 isutil=
2674 case "$cmd" in index-merge-one-file)
2675 isutil="-"
2676 esac
2677 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2678 looplevel="$TG_ALIAS_DEPTH"
2679 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2680 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2681 looplevel=0
2682 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2683 [ -n "$tgalias" ] || {
2684 echo "Unknown subcommand: $cmd" >&2
2685 do_help
2686 exit 1
2688 looplevel=$(( $looplevel + 1 ))
2689 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2690 TG_ALIAS_DEPTH="$looplevel"
2691 export TG_ALIAS_DEPTH
2692 if [ "!${tgalias#?}" = "$tgalias" ]; then
2693 [ -z "$wayback" ] ||
2694 die "-w is not allowed before an '!' alias command"
2695 unset_ GIT_PREFIX
2696 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2697 GIT_PREFIX="$pfx"
2698 export GIT_PREFIX
2700 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2701 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2702 else
2703 eval 'exec "$tgbin"' "${wayback:+-w \"\$wayback\"}" "$tgalias" '"$@"'
2705 die "alias execution failed for: $tgalias"
2707 unset_ TG_ALIAS_DEPTH
2709 showing_help=
2710 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2711 showing_help=1
2714 nomergesetup="$showing_help"
2715 case "$cmd" in base|contains|export|files|info|log|mail|next|patch|prev|rebase|revert|shell|summary|tag)
2716 # avoid merge setup where not necessary
2718 nomergesetup=1
2719 esac
2721 if [ -n "$wayback" ] && [ -z "$showing_help" ]; then
2722 [ -n "$nomergesetup" ] ||
2723 die "the wayback machine cannot be used with the \"$cmd\" subcommand"
2724 if [ "$cmd" = "shell" ]; then
2725 # this is ugly; `tg shell` should handle this but it's too
2726 # late there so we have to do it here
2727 wayback_dir=
2728 case "$1" in
2729 "--directory="?*)
2730 wayback_dir="${1#--directory=}" && shift;;
2731 "--directory=")
2732 die "--directory requires an argument";;
2733 "--directory")
2734 [ $# -ge 2 ] || die "--directory requires an argument"
2735 wayback_dir="$2" && shift 2;;
2736 esac
2737 activate_wayback_machine "$wayback" 1 "$wayback_dir"
2738 else
2739 _fullwb=
2740 # export might drop out into a shell for conflict resolution
2741 [ "$cmd" != "export" ] || _fullwb=2
2742 activate_wayback_machine "$wayback" "$_fullwb"
2743 fi ||
2744 die "failed to set the wayback machine to target \"$wayback\""
2747 [ -n "$showing_help" ] || initial_setup
2748 [ -z "$noremote" ] || unset_ base_remote
2750 if [ -z "$nomergesetup" ]; then
2751 # make sure merging the .top* files will always behave sanely
2753 setup_ours
2754 setup_hook "pre-commit"
2757 # everything but rebase needs topbases set
2758 carefully="$showing_help"
2759 [ "$cmd" != "migrate-bases" ] || carefully=1
2760 [ "$cmd" = "rebase" ] || set_topbases $carefully
2762 _use_ref_cache=
2763 tg_read_only=1
2764 _suppress_alt=
2765 case "$cmd$showing_help" in
2766 contains|info|summary|tag)
2767 _use_ref_cache=1;;
2768 "export")
2769 _use_ref_cache=1
2770 _suppress_alt=1;;
2771 annihilate|create|delete|depend|import|update)
2772 tg_read_only=
2773 _suppress_alt=1;;
2774 esac
2775 [ -z "$_suppress_alt" ] || noalt_setup
2776 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2778 fullcmd="${tgname:-tg} $cmd $*"
2779 if [ z"$forcepager" = z"1" ]; then
2780 page '. "$TG_INST_CMDDIR"/tg-$isutil$cmd' "$@"
2781 else
2782 . "$TG_INST_CMDDIR"/tg-$isutil$cmd
2783 fi;;
2784 esac