tg: improve handling of configured core.hooksPath
[topgit/pro.git] / tg.sh
blobae2de225449b7455f95fc4b91543b67af67d12c8
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 cmp() { exec_lc_all_c cmp cmp "$@"; }
77 cut() { exec_lc_all_c cut cut "$@"; }
78 find() { exec_lc_all_c find find "$@"; }
79 grep() { exec_lc_all_c grep grep "$@"; }
80 join() { exec_lc_all_c join join "$@"; }
81 paste() { exec_lc_all_c paste paste "$@"; }
82 sed() { exec_lc_all_c sed sed "$@"; }
83 sort() { exec_lc_all_c sort sort "$@"; }
84 tr() { exec_lc_all_c tr tr "$@"; }
85 wc() { exec_lc_all_c wc wc "$@"; }
86 xargs() { exec_lc_all_c xargs xargs "$@"; }
88 # Output arguments without any possible interpretation
89 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
90 echol()
92 printf '%s\n' "$*"
95 info()
97 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
100 warn()
102 info "warning: $*" >&2
105 err()
107 info "error: $*" >&2
110 fatal()
112 info "fatal: $*" >&2
115 die()
117 fatal "$@"
118 exit 1
121 # shift off first arg then return "$*" properly quoted in single-quotes
122 # if $1 was '' output goes to stdout otherwise it's assigned to $1
123 # the final \n, if any, is omitted from the result but any others are included
124 v_quotearg()
126 _quotearg_v="$1"
127 shift
128 set -- "$_quotearg_v" \
129 "sed \"s/'/'\\\\\\''/g;1s/^/'/;\\\$s/\\\$/'/;s/'''/'/g;1s/^''\\(.\\)/\\1/\"" "$*"
130 unset_ _quotearg_v
131 if [ -z "$3" ]; then
132 if [ -z "$1" ]; then
133 echo "''"
134 else
135 eval "$1=\"''\""
137 else
138 if [ -z "$1" ]; then
139 printf "%s$4" "$3" | eval "$2"
140 else
141 eval "$1="'"$(printf "%s$4" "$3" | eval "$2")"'
146 # same as v_quotearg except there's no extra $1 so output always goes to stdout
147 quotearg()
149 v_quotearg '' "$@"
152 vcmp()
154 # Compare $1 to $3 each of which must match ^[^0-9]*\d*(\.\d*)*.*$
155 # where only the "\d*" parts in the regex participate in the comparison
156 # Since EVERY string matches that regex this function is easy to use
157 # An empty string ('') for $1 or $3 or any "\d*" part is treated as 0
158 # $2 is a compare op '<', '<=', '=', '==', '!=', '>=', '>'
159 # Return code is 0 for true, 1 for false (or unknown compare op)
160 # There is NO difference in behavior between '=' and '=='
161 # Note that "vcmp 1.8 == 1.8.0.0.0.0" correctly returns 0
162 set -- "$1" "$2" "$3" "${1%%[0-9]*}" "${3%%[0-9]*}"
163 set -- "${1#"$4"}" "$2" "${3#"$5"}"
164 set -- "${1%%[!0-9.]*}" "$2" "${3%%[!0-9.]*}"
165 while
166 vcmp_a_="${1%%.*}"
167 vcmp_b_="${3%%.*}"
168 [ "z$vcmp_a_" != "z" ] || [ "z$vcmp_b_" != "z" ]
170 if [ "${vcmp_a_:-0}" -lt "${vcmp_b_:-0}" ]; then
171 unset_ vcmp_a_ vcmp_b_
172 case "$2" in "<"|"<="|"!=") return 0; esac
173 return 1
174 elif [ "${vcmp_a_:-0}" -gt "${vcmp_b_:-0}" ]; then
175 unset_ vcmp_a_ vcmp_b_
176 case "$2" in ">"|">="|"!=") return 0; esac
177 return 1;
179 vcmp_a_="${1#$vcmp_a_}"
180 vcmp_b_="${3#$vcmp_b_}"
181 set -- "${vcmp_a_#.}" "$2" "${vcmp_b_#.}"
182 done
183 unset_ vcmp_a_ vcmp_b_
184 case "$2" in "="|"=="|"<="|">=") return 0; esac
185 return 1
188 # true if "$1" is an existing dir and is empty except for
189 # any additional files given as extra arguments. If "$2"
190 # is the single character "." then all ".*" files will be
191 # ignored for the test (plus any further args, if any)
192 is_empty_dir() {
193 test -n "$1" && test -d "$1" || return 1
194 iedd_="$1"
195 shift
196 ieddnok_='\.?$'
197 if [ z"$1" = z"." ]; then
198 ieddnok_=
199 shift
200 while ! case "$1" in "."*) ! :; esac; do shift; done
202 if [ $# -eq 0 ]; then
203 ! \ls -a1 "$iedd_" | grep -q -E -v '^\.'"$ieddnok_"
204 else
205 # we only handle ".git" right now for efficiency
206 [ z"$*" = z".git" ] || {
207 fatal "[BUG] is_empty_dir not implemented for arguments: $*"
208 exit 70
210 ! \ls -a1 "$iedd_" | grep -q -E -v -i -e '^\.\.?$' -e '^\.git$'
214 precheck() {
215 if ! git_version="$(git version)"; then
216 die "'git version' failed"
218 case "$git_version" in [Gg]"it version "*);;*)
219 die "'git version' output does not start with 'git version '"
220 esac
222 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
223 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
226 case "$1" in version|--version|-V)
227 echo "TopGit version $TG_VERSION"
228 exit 0
229 esac
231 [ $# -eq 1 ] && [ "$1" = "--make-empty-blob" ] || precheck
232 [ $# -ne 1 ] || [ "$1" != "precheck" ] || exit 0
234 cat_depsmsg_internal()
236 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
237 if [ -s "$tg_cache_dir/refs/heads/$1/.$2" ]; then
238 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
239 _line=
240 while IFS= read -r _line || [ -n "$_line" ]; do
241 printf '%s\n' "$_line"
242 done
243 return 0
244 fi <"$tg_cache_dir/refs/heads/$1/.$2"
246 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null || :
247 if [ -d "$tg_cache_dir/refs/heads/$1" ]; then
248 printf '%s\n' "$_rev" >"$tg_cache_dir/refs/heads/$1/.$2"
249 _line=
250 git cat-file blob "$_rev:.$2" 2>/dev/null |
251 while IFS= read -r _line || [ -n "$_line" ]; do
252 printf '%s\n' "$_line" >&3
253 printf '%s\n' "$_line"
254 done 3>>"$tg_cache_dir/refs/heads/$1/.$2"
255 else
256 git cat-file blob "$_rev:.$2" 2>/dev/null
260 # cat_deps BRANCHNAME
261 # Caches result
262 cat_deps()
264 cat_depsmsg_internal "$1" topdeps
267 # cat_msg BRANCHNAME
268 # Caches result
269 cat_msg()
271 cat_depsmsg_internal "$1" topmsg
274 # cat_file TOPIC:PATH [FROM]
275 # cat the file PATH from branch TOPIC when FROM is empty.
276 # FROM can be -i or -w, than the file will be from the index or worktree,
277 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
278 cat_file()
280 path="$1"
281 case "$2" in
283 cat "$root_dir/${path#*:}"
286 # ':file' means cat from index
287 git cat-file blob ":${path#*:}" 2>/dev/null
290 case "$path" in
291 refs/heads/*:.topdeps)
292 _temp="${path%:.topdeps}"
293 cat_deps "${_temp#refs/heads/}"
295 refs/heads/*:.topmsg)
296 _temp="${path%:.topmsg}"
297 cat_msg "${_temp#refs/heads/}"
300 git cat-file blob "$path" 2>/dev/null
302 esac
305 die "Wrong argument to cat_file: '$2'"
307 esac
310 # if use_alt_temp_odb and tg_use_alt_odb are true try to write the object(s)
311 # into the temporary alt odb area instead of the usual location
312 git_temp_alt_odb_cmd()
314 if [ -n "$use_alt_temp_odb" ] && [ -n "$tg_use_alt_odb" ] &&
315 [ -n "$TG_OBJECT_DIRECTORY" ] &&
316 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
318 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
319 GIT_OBJECT_DIRECTORY="$TG_OBJECT_DIRECTORY"
320 unset_ TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES
321 export GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
322 git "$@"
324 else
325 git "$@"
329 git_write_tree() { git_temp_alt_odb_cmd write-tree "$@"; }
330 git_mktree() { git_temp_alt_odb_cmd mktree "$@"; }
332 make_mtblob() {
333 use_alt_temp_odb=1
334 tg_use_alt_odb=1
335 git_temp_alt_odb_cmd hash-object -t blob -w --stdin </dev/null >/dev/null 2>&1
337 # short-circuit this for speed
338 [ $# -eq 1 ] && [ "$1" = "--make-empty-blob" ] && { make_mtblob || :; exit 0; }
340 # get tree for the committed topic
341 get_tree_()
343 echo "refs/heads/$1"
346 # get tree for the base
347 get_tree_b()
349 echo "refs/$topbases/$1"
352 # get tree for the index
353 get_tree_i()
355 git_write_tree
358 # get tree for the worktree
359 get_tree_w()
361 i_tree=$(git_write_tree)
363 # the file for --index-output needs to sit next to the
364 # current index file
365 cd "$root_dir"
366 : ${GIT_INDEX_FILE:="$git_dir/index"}
367 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
368 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
369 GIT_INDEX_FILE="$TMP_INDEX" &&
370 export GIT_INDEX_FILE &&
371 git diff --name-only -z HEAD |
372 git update-index -z --add --remove --stdin &&
373 git_write_tree &&
374 rm -f "$TMP_INDEX"
378 # get tree for arbitrary ref
379 get_tree_r()
381 echo "$1"
384 # strip_ref "$(git symbolic-ref HEAD)"
385 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
386 strip_ref()
388 case "$1" in
389 refs/"$topbases"/*)
390 echol "${1#refs/$topbases/}"
392 refs/heads/*)
393 echol "${1#refs/heads/}"
396 echol "$1"
397 esac
400 # pretty_tree [-t] NAME [-b | -i | -w | -r]
401 # Output tree ID of a cleaned-up tree without tg's artifacts.
402 # NAME will be ignored for -i and -w, but needs to be present
403 # With -r NAME must be a full ref name to a treeish (it's used as-is)
404 # If -t is used the tree is written into the alternate temporary objects area
405 pretty_tree()
407 use_alt_temp_odb=
408 [ "$1" != "-t" ] || { shift; use_alt_temp_odb=1; }
409 name="$1"
410 source="${2#?}"
411 git ls-tree --full-tree "$(get_tree_$source "$name")" |
412 sed -ne '/ \.top.*$/!p' |
413 git_mktree
416 # return an empty-tree root commit -- date is either passed in or current
417 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
418 # An invalid secs causes the current date to be used, an invalid zone offset
419 # causes +0000 to be used
420 make_empty_commit()
422 # the empty tree is guaranteed to always be there even in a repo with
423 # zero objects, but for completeness we force it to exist as a real object
424 SECS=
425 read -r SECS ZONE JUNK <<-EOT || :
428 case "$SECS" in *[!0-9]*) SECS=; esac
429 if [ -z "$SECS" ]; then
430 MTDATE="$(date '+%s %z')"
431 else
432 case "$ZONE" in
433 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
435 [01][0-9][0-5][0-9])
436 ZONE="+$ZONE"
439 ZONE="+0000"
440 esac
441 MTDATE="$SECS $ZONE"
443 EMPTYID="- <-> $MTDATE"
444 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
445 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
446 git hash-object -t commit -w --stdin
449 # standard input is a diff
450 # standard output is the "+" lines with leading "+ " removed
451 # beware that old lines followed by the dreaded '\ No newline at end of file'
452 # will appear to be new lines if lines are added after them
453 # the git diff --ignore-space-at-eol option can be used to prevent this
454 diff_added_lines()
456 awk '
457 BEGIN { in_hunk = 0; }
458 /^@@ / { in_hunk = 1; }
459 /^\+/ { if (in_hunk == 1) printf("%s\n", substr($0, 2)); }
460 !/^\\ No newline at end of file/ &&
461 /^[^@ +-]/ { in_hunk = 0; }
465 # $1 is name of new branch to create locally if all of these are true:
466 # a) exists as a remote TopGit branch for "$base_remote"
467 # b) the branch "name" does not have any invalid characters in it
468 # c) neither of the two branch refs (branch or base) exist locally
469 # returns success only if a new local branch was created (and dumps message)
470 auto_create_local_remote()
472 case "$1" in ""|*[" $tab$lf~^:\\*?["]*|.*|*/.*|*.|*./|/*|*/|*//*) return 1; esac
473 [ -n "$base_remote" ] &&
474 git update-ref --stdin <<-EOT >/dev/null 2>&1 &&
475 verify refs/remotes/$base_remote/${topbases#heads/}/$1 refs/remotes/$base_remote/${topbases#heads/}/$1
476 verify refs/remotes/$base_remote/$1 refs/remotes/$base_remote/$1
477 create refs/$topbases/$1 refs/remotes/$base_remote/${topbases#heads/}/$1^0
478 create refs/heads/$1 refs/remotes/$base_remote/$1^0
480 { init_reflog "refs/$topbases/$1" || :; } &&
481 info "topic branch '$1' automatically set up from remote '$base_remote'"
484 # setup_hook NAME
485 setup_hook()
487 setup_git_dir_is_bare
488 [ -z "$git_dir_is_bare" ] || return 0
489 tgname="${0##*/}"
490 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
491 if [ -f "$git_hooks_dir/$1" ] && grep -Fq "$hook_call" "$git_hooks_dir/$1"; then
492 # Another job well done!
493 return
495 # Prepare incantation
496 hook_chain=
497 if [ -s "$git_hooks_dir/$1" ] && [ -x "$git_hooks_dir/$1" ]; then
498 hook_call="$hook_call"' || exit $?'
499 if [ -L "$git_hooks_dir/$1" ] || ! sed -n 1p <"$git_hooks_dir/$1" | grep -Fqx "#!@SHELL_PATH@"; then
500 chain_num=
501 while [ -e "$git_hooks_dir/$1-chain$chain_num" ]; do
502 chain_num=$(( $chain_num + 1 ))
503 done
504 mv -f "$git_hooks_dir/$1" "$git_hooks_dir/$1-chain$chain_num"
505 hook_chain=1
507 else
508 hook_call="exec $hook_call"
509 [ -d "$git_hooks_dir" ] || mkdir -p "$git_hooks_dir" || :
511 # Don't call hook if tg is not installed
512 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
513 # Insert call into the hook
515 echol "#!@SHELL_PATH@"
516 echol "$hook_call"
517 if [ -n "$hook_chain" ]; then
518 echol "exec \"\$0-chain$chain_num\" \"\$@\""
519 else
520 [ ! -s "$git_hooks_dir/$1" ] || cat "$git_hooks_dir/$1"
522 } >"$git_hooks_dir/$1+"
523 chmod a+x "$git_hooks_dir/$1+"
524 mv "$git_hooks_dir/$1+" "$git_hooks_dir/$1"
527 # setup_ours (no arguments)
528 setup_ours()
530 setup_git_dir_is_bare
531 [ -z "$git_dir_is_bare" ] || return 0
532 if [ ! -s "$git_common_dir/info/attributes" ] || ! grep -q topmsg "$git_common_dir/info/attributes"; then
533 [ -d "$git_common_dir/info" ] || mkdir "$git_common_dir/info"
535 echo ".topmsg merge=ours"
536 echo ".topdeps merge=ours"
537 } >>"$git_common_dir/info/attributes"
539 if ! git config merge.ours.driver >/dev/null; then
540 git config merge.ours.name '"always keep ours" merge driver'
541 git config merge.ours.driver 'touch %A'
545 # measure_branch NAME [BASE] [EXTRAHEAD...]
546 measure_branch()
548 _bname="$1"; _base="$2"
549 shift; shift
550 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
551 # The caller should've verified $name is valid
552 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
553 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
554 if [ $_commits -ne 1 ]; then
555 _suffix="commits"
556 else
557 _suffix="commit"
559 echo "$_commits/$_nmcommits $_suffix"
562 # true if $1 is contained by (or the same as) $2
563 # this is never slower than merge-base --is-ancestor and is often slightly faster
564 contained_by()
566 [ "$(git rev-list --count --max-count=1 "$1" --not "$2" --)" = "0" ]
569 # branch_contains B1 B2
570 # Whether B1 is a superset of B2.
571 branch_contains()
573 _revb1="$(ref_exists_rev "$1")" || return 0
574 _revb2="$(ref_exists_rev "$2")" || return 0
575 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
576 if read _result _rev_matchb1 _rev_matchb2 &&
577 [ "$_revb1" = "$_rev_matchb1" ] && [ "$_revb2" = "$_rev_matchb2" ]; then
578 return $_result
579 fi <"$tg_cache_dir/$1/.bc/$2/.d"
581 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
582 _result=0
583 contained_by "$_revb2" "$_revb1" || _result=1
584 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
585 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
587 return $_result
590 create_ref_dirs()
592 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" ] && [ -s "$tg_ref_cache" ] || return 0
593 mkdir -p "$tg_tmp_dir/cached/refs"
594 awk '{x=$1; sub(/^refs\//,"",x); if (x != "") {gsub(/[^A-Za-z0-9\/_.+-]/,"\\\\&",x); print x;}}' <"$tg_ref_cache" |
596 cd "$tg_tmp_dir/cached/refs" &&
597 xargs mkdir -p
599 awk -v p="$tg_tmp_dir/cached/" '
600 NF == 2 &&
601 $1 ~ /^refs\/./ &&
602 $2 ~ /^[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]+$/ {
603 fn = p $1 "/.ref"
604 print "0 " $2 >fn
605 close(fn)
607 ' <"$tg_ref_cache"
608 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
611 # If the first argument is non-empty, stores "1" there if this call created the cache
612 v_create_ref_cache()
614 [ -n "$tg_ref_cache" ] && ! [ -s "$tg_ref_cache" ] || return 0
615 _remotespec=
616 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
617 [ -z "$1" ] || eval "$1=1"
618 git for-each-ref --format='%(refname) %(objectname)' \
619 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
620 create_ref_dirs
623 remove_ref_cache()
625 [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ] || return 0
626 >"$tg_ref_cache"
627 >"$tg_ref_cache_br"
628 >"$tg_ref_cache_rbr"
629 >"$tg_ref_cache_ann"
630 >"$tg_ref_cache_dep"
633 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
634 rev_parse()
636 rev_parse_code_=1
637 if [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
638 rev_parse_code_=0
639 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache" ||
640 rev_parse_code_=$?
642 [ $rev_parse_code_ -ne 0 ] && [ -z "$tg_ref_cache_only" ] || return $rev_parse_code_
643 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
646 # ref_exists_rev REF
647 # Whether REF is a valid ref name
648 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
649 # or, if $base_remote is set, refs/remotes/$base_remote/
650 # Caches result if $tg_read_only and outputs HASH on success
651 ref_exists_rev()
653 case "$1" in
654 refs/*)
656 $octet20)
657 printf '%s' "$1"
658 return;;
660 die "ref_exists_rev requires fully-qualified ref name (given: $1)"
661 esac
662 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
663 _result=
664 _result_rev=
665 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
666 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
667 _result=0
668 _result_rev="$(rev_parse "$1")" || _result=$?
669 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
670 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
671 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
672 printf '%s' "$_result_rev"
673 return $_result
676 # Same as ref_exists_rev but output is abbreviated hash
677 # Optional second argument defaults to --short but may be any --short=.../--no-short option
678 ref_exists_rev_short()
680 case "$1" in
681 refs/*)
683 $octet20)
686 die "ref_exists_rev_short requires fully-qualified ref name"
687 esac
688 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
689 _result=
690 _result_rev=
691 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
692 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
693 _result=0
694 _result_rev="$(rev_parse "$1")" || _result=$?
695 if [ $_result -eq 0 ]; then
696 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev^0" --)"
697 _result=$?
699 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
700 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
701 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
702 printf '%s' "$_result_rev"
703 return $_result
706 # ref_exists REF
707 # Whether REF is a valid ref name
708 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
709 # or, if $base_remote is set, refs/remotes/$base_remote/
710 # Caches result
711 ref_exists()
713 ref_exists_rev "$1" >/dev/null
716 # rev_parse_tree REF
717 # Runs git rev-parse REF^{tree}
718 # Caches result if $tg_read_only
719 rev_parse_tree()
721 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
722 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
723 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
724 printf '%s\n' "$_result"
725 return 0
727 return 1
729 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
730 if [ -d "$tg_tmp_dir/cached/$1" ]; then
731 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
732 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
733 printf '%s\n' "$_result"
734 return 0
736 return 1
738 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
741 # has_remote BRANCH
742 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
743 has_remote()
745 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
748 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
749 # If -z "$1" still set return code but do not return result
750 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
751 # refs/heads/... then ... will be verified instead.
752 # if "$3" = "-f" (for fail) then return an error rather than dying.
753 v_verify_topgit_branch()
755 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
756 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
757 [ -n "$_verifyname" ] || [ "$3" = "-f" ] || die "HEAD is not a symbolic ref"
758 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
759 [ "$3" != "-f" ] || return 1
760 die "HEAD is not a symbolic ref to the refs/heads namespace"
761 esac
762 set -- "$1" "$_verifyname" "$3"
764 case "$2" in
765 refs/"$topbases"/*)
766 _verifyname="${2#refs/$topbases/}"
768 refs/heads/*)
769 _verifyname="${2#refs/heads/}"
772 _verifyname="$2"
774 esac
775 if ! ref_exists "refs/heads/$_verifyname"; then
776 [ "$3" != "-f" ] || return 1
777 die "no such branch: $_verifyname"
779 if ! ref_exists "refs/$topbases/$_verifyname"; then
780 [ "$3" != "-f" ] || return 1
781 die "not a TopGit-controlled branch: $_verifyname"
783 [ -z "$1" ] || eval "$1="'"$_verifyname"'
786 # Return the verified TopGit branch name or die with an error.
787 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
788 # refs/heads/... then ... will be verified instead.
789 # if "$2" = "-f" (for fail) then return an error rather than dying.
790 verify_topgit_branch()
792 v_verify_topgit_branch _verifyname "$@" || return
793 printf '%s' "$_verifyname"
796 # Caches result
797 # $1 = branch name (i.e. "t/foo/bar")
798 # $2 = optional result of rev-parse "refs/heads/$1"
799 # $3 = optional result of rev-parse "refs/$topbases/$1"
800 branch_annihilated()
802 _branch_name="$1"
803 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
804 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
806 _result=
807 _result_rev=
808 _result_rev_base=
809 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/refs/heads/$_branch_name/.ann"; } 2>/dev/null || :
810 [ -z "$_result" ] || [ "$_result_rev" != "$_rev" ] || [ "$_result_rev_base" != "$_rev_base" ] || return $_result
812 # use the merge base in case the base is ahead.
813 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
815 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
816 _result=$?
817 [ -d "$tg_cache_dir/refs/heads/$_branch_name" ] || mkdir -p "$tg_cache_dir/refs/heads/$_branch_name" 2>/dev/null
818 [ ! -d "$tg_cache_dir/refs/heads/$_branch_name" ] ||
819 echo $_result $_rev $_rev_base >"$tg_cache_dir/refs/heads/$_branch_name/.ann" 2>/dev/null || :
820 return $_result
823 non_annihilated_branches()
825 refscacheopt="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
826 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
827 refscacheopt="$refscacheopt"'-r="$tg_ref_cache" "refs/$topbases"'
829 eval run_awk_topgit_branches -n "$refscacheopt" '"refs/$topbases" "$@"'
832 # Make sure our tree is clean
833 # if optional "$1" given also verify that a checkout to "$1" would succeed
834 ensure_clean_tree()
836 check_status
837 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
838 git update-index --ignore-submodules --refresh ||
839 die "the working directory has uncommitted changes (see above) - first commit or reset them"
840 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
841 die "the index has uncommited changes"
842 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
843 die "git checkout \"$1\" would fail"
846 # Make sure .topdeps and .topmsg are "clean"
847 # They are considered "clean" if each is identical in worktree, index and HEAD
848 # With "-u" as the argument skip the HEAD check (-u => unborn)
849 # untracked .topdeps and/or .topmsg files are always considered "dirty" as well
850 # with -u them just existing constitutes "dirty"
851 ensure_clean_topfiles()
853 _dirtw=0
854 _dirti=0
855 _dirtu=0
856 _check="$(git diff-files --ignore-submodules --name-only -- :/.topdeps :/.topmsg)" &&
857 [ -z "$_check" ] || _dirtw=1
858 if [ "$1" != "-u" ]; then
859 _check="$(git diff-index --cached --ignore-submodules --name-only HEAD -- :/.topdeps :/.topmsg)" &&
860 [ -z "$_check" ] || _dirti=1
862 if [ "$_dirti$_dirtw" = "00" ]; then
863 v_get_show_cdup
864 if [ -e "${git_cdup_result}.topdeps" ] || [ -e "${git_cdup_result}.topmsg" ]; then
865 [ "$1" != "-u" ] &&
866 _check="$(git status --porcelain --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg)" &&
867 [ -z "$_check" ] || _dirtu=1
870 if [ "$_dirtu$_dirti$_dirtw" != "000" ]; then
871 git status --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg || :
872 case "$_dirtu$_dirti$_dirtw" in
873 001) die "the working directory has uncommitted changes (see above) - first commit or reset them";;
874 010) die "the index has uncommited changes (see above)";;
875 011) die "the working directory and index have uncommitted changes (see above) - first commit or reset them";;
876 100) die "the working directory has untracked files that would be overwritten (see above)";;
877 esac
881 # is_sha1 REF
882 # Whether REF is a SHA1 (compared to a symbolic name).
883 is_sha1()
885 case "$1" in $octet20) return 0;; esac
886 return 1
889 # navigate_deps <run_awk_topgit_navigate options and arguments>
890 # all options and arguments are passed through to run_awk_topgit_navigate
891 # except for a leading -td= option, if any, which is picked off for deps
892 # after arranging to feed it a suitable deps list
893 navigate_deps()
895 dogfer=
896 dorad=1
897 userc=
898 tmpdep=
899 ratd_opts="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
900 ratn_opts=
901 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
902 userc=1
903 tmprfs="$tg_ref_cache"
904 tmptgbr="$tg_ref_cache_br"
905 tmpann="$tg_ref_cache_ann"
906 tmpdep="$tg_ref_cache_dep"
907 [ -s "$tg_ref_cache" ] || dogfer=1
908 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
909 else
910 ratd_opts="${ratd_opts}-rmr"
911 ratn_opts="-rma -rmb"
912 tmprfs="$tg_tmp_dir/refs.$$"
913 tmpann="$tg_tmp_dir/ann.$$"
914 tmptgbr="$tg_tmp_dir/tgbr.$$"
915 dogfer=1
917 refpats="\"refs/heads\" \"refs/\$topbases\""
918 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
919 [ -z "$dogfer" ] ||
920 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
921 depscmd="run_awk_topgit_deps $ratd_opts"
922 case "$1" in -td=*)
923 userc=
924 depscmd="$depscmd $1"
925 shift
926 esac
927 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -s "refs/$topbases"'
928 if [ -n "$userc" ]; then
929 if [ -n "$dorad" ]; then
930 eval "$depscmd" >"$tmpdep"
932 depscmd='<"$tmpdep" '
933 else
934 depscmd="$depscmd |"
936 eval "$depscmd" run_awk_topgit_navigate '-a="$tmpann" -b="$tmptgbr"' "$ratn_opts" '"$@"'
939 # recurse_deps_internal NAME [BRANCHPATH...]
940 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
941 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
942 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
943 # (but missing and remotes are always "0")
944 # followed by a 0 for no excess visits or a positive number of excess visits
945 # then the branch name followed by its depedency chain (which might be empty)
946 # An output line might look like this:
947 # 0 1 1 0 t/foo/leaf t/foo/int t/stage
948 # If no_remotes is non-empty, exclude remotes
949 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
950 # If with_top_level is non-empty, include the top-level that's normally omitted
951 # any branch names in the space-separated recurse_deps_exclude variable
952 # are skipped (along with their dependencies)
953 recurse_deps_internal()
955 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
956 ratr_opts="${recurse_preorder:+-f} ${with_top_level:+-s}"
957 dogfer=
958 dorad=1
959 userc=
960 tmpdep=
961 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
962 userc=1
963 tmprfs="$tg_ref_cache"
964 tmptgbr="$tg_ref_cache_br"
965 tmpann="$tg_ref_cache_ann"
966 tmpdep="$tg_ref_cache_dep"
967 [ -s "$tg_ref_cache" ] || dogfer=1
968 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
969 else
970 ratr_opts="$ratr_opts -rmh -rma -rmb"
971 tmprfs="$tg_tmp_dir/refs.$$"
972 tmpann="$tg_tmp_dir/ann.$$"
973 tmptgbr="$tg_tmp_dir/tgbr.$$"
974 dogfer=1
976 refpats="\"refs/heads\" \"refs/\$topbases\""
977 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
978 tmptgrmtbr=
979 dorab=1
980 if [ -z "$no_remotes" ] && [ -n "$base_remote" ]; then
981 if [ -n "$userc" ]; then
982 tmptgrmtbr="$tg_ref_cache_rbr"
983 [ -n "$dogfer" ] || ! [ -s "$tmptgrmtbr" ] || dorab=
984 else
985 tmptgrmtbr="$tg_tmp_dir/tgrmtbr.$$"
986 ratr_opts="$ratr_opts -rmr"
988 ratr_opts="$ratr_opts -r=\"\$tmptgrmtbr\" -u=\":refs/remotes/\$base_remote/\${topbases#heads/}\""
990 [ -z "$dogfer" ] ||
991 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
992 if [ -n "$tmptgrmtbr" ] && [ -n "$dorab" ]; then
993 run_awk_topgit_branches -n -h="refs/remotes/$base_remote" -r="$tmprfs" \
994 "refs/remotes/$base_remote/${topbases#heads/}" >"$tmptgrmtbr"
996 depscmd="run_awk_topgit_deps -s${TG_DEBUG:+ -p=\"\$tg_ref_cache.pre\"}"
997 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" "refs/$topbases"'
998 if [ -n "$userc" ]; then
999 if [ -n "$dorad" ]; then
1000 eval "$depscmd" >"$tmpdep"
1002 depscmd='<"$tmpdep" '
1003 else
1004 depscmd="$depscmd |"
1006 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
1007 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
1010 # do_eval CMD
1011 # helper for recurse_deps so that a return statement executed inside CMD
1012 # does not return from recurse_deps. This shouldn't be necessary, but it
1013 # seems that it actually is.
1014 do_eval()
1016 eval "$@"
1019 # becomes read-only for caching purposes
1020 # assigns new value to tg_read_only
1021 # become_cacheable/undo_become_cacheable calls may be nested
1022 become_cacheable()
1024 _old_tg_read_only="$tg_read_only"
1025 if [ -z "$tg_read_only" ]; then
1026 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1027 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1028 tg_read_only=1
1030 _my_ref_cache=
1031 v_create_ref_cache _my_ref_cache
1032 _my_ref_cache="${_my_ref_cache:+1}"
1033 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
1036 # restores tg_read_only and ref_cache to state before become_cacheable call
1037 # become_cacheable/undo_bocome_cacheable calls may be nested
1038 undo_become_cacheable()
1040 case "$tg_read_only" in
1041 "undo"[01]"-"*)
1042 _suffix="${tg_read_only#undo?-}"
1043 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
1044 tg_read_only="$_suffix"
1045 esac
1048 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
1049 become_non_cacheable()
1051 remove_ref_cache
1052 tg_read_only=
1053 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1054 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1057 # call this to make sure the current Git repository has an associated work tree
1058 # also make sure we are not in wayback mode
1059 ensure_work_tree()
1061 [ -z "$wayback" ] ||
1062 die "the wayback machine cannot be used with the specified options"
1063 setup_git_dir_is_bare
1064 [ -n "$git_dir_is_bare" ] || return 0
1065 die "This operation must be run in a work tree"
1068 # call this to make sure Git will not complain about a missing user/email
1069 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
1070 ensure_ident_available()
1072 [ -z "$TG_IDENT_CHECKED" ] || return 0
1073 git var GIT_AUTHOR_IDENT >/dev/null &&
1074 git var GIT_COMMITTER_IDENT >/dev/null || exit
1075 TG_IDENT_CHECKED=1
1076 export TG_IDENT_CHECKED
1077 return 0
1080 # recurse_deps [-o=<options string>] CMD NAME [BRANCHPATH...]
1081 # Recursively eval CMD on all dependencies of NAME.
1082 # Dependencies are visited in topological order.
1083 # If <options string> is given, it's eval'd into the recurse_deps_internal
1084 # call just before the "--" that's passed just before NAME
1085 # CMD can refer to the following variables:
1087 # _ret starts as 0; CMD can change; will be final return result
1088 # _dep bare branch name or ":refs/remotes/..." for a remote
1089 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
1090 # _depchain 0+ space-sep branch names (_name first) form a path to top
1091 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
1092 # _dep_is_leaf boolean "1" if leaf; "" if not
1093 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
1094 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
1095 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
1096 # _dep_xvisits non-negative integer number of excess visits (often 0)
1098 # CMD may use a "return" statement without issue; its return value is ignored,
1099 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
1100 # will stop immediately and the value with the leading "-" stripped off will
1101 # be the final result code
1103 # CMD can refer to $_name for queried branch name,
1104 # $_dep for dependency name,
1105 # $_depchain for space-seperated branch backtrace,
1106 # $_dep_missing boolean to check whether $_dep is present
1107 # and the $_dep_is_tgish and $_dep_annihilated booleans.
1108 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
1109 # It can modify $_ret to affect the return value
1110 # of the whole function.
1111 # If recurse_deps() hits missing dependencies, it will append
1112 # them to space-separated $missing_deps list and skip them
1113 # after calling CMD with _dep_missing set.
1114 # remote dependencies are processed if no_remotes is unset.
1115 # any branch names in the space-separated recurse_deps_exclude variable
1116 # are skipped (along with their dependencies)
1118 # If no_remotes is non-empty, exclude remotes
1119 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1120 # If with_top_level is non-empty, include the top-level that's normally omitted
1121 # any branch names in the space-separated recurse_deps_exclude variable
1122 # are skipped (along with their dependencies)
1123 recurse_deps()
1125 _opts=
1126 case "$1" in -o=*) _opts="${1#-o=}"; shift; esac
1127 _cmd="$1"; shift
1129 _depsfile="$(get_temp tg-depsfile)"
1130 eval recurse_deps_internal "$_opts" -- '"$@"' >"$_depsfile" || :
1132 _ret=0
1133 while read _ismissing _istgish _isleaf _dep_xvisits _dep _name _deppath; do
1134 _depchain="$_name${_deppath:+ $_deppath}"
1135 _dep_is_tgish=
1136 [ "$_istgish" = "0" ] || _dep_is_tgish=1
1137 _dep_has_remote=
1138 [ "$_istgish" != "2" ] || _dep_has_remote=1
1139 _dep_missing=
1140 if [ "$_ismissing" != "0" ]; then
1141 _dep_missing=1
1142 case " $missing_deps " in *" $_dep "*);;*)
1143 missing_deps="${missing_deps:+$missing_deps }$_dep"
1144 esac
1146 _dep_annihilated=
1147 _dep_is_leaf=
1148 if [ "$_isleaf" = "1" ]; then
1149 _dep_is_leaf=1
1150 elif [ "$_isleaf" = "2" ]; then
1151 _dep_annihilated=1
1153 do_eval "$_cmd" || :
1154 if [ "${_ret#-}" != "$_ret" ]; then
1155 _ret="${_ret#-}"
1156 break
1158 done <"$_depsfile"
1159 rm -f "$_depsfile"
1160 return ${_ret:-0}
1163 # find_leaves NAME
1164 # output (one per line) the unique leaves of NAME
1165 # a leaf is either
1166 # 1) a non-tgish dependency
1167 # 2) the base of a tgish dependency with no non-annihilated dependencies
1168 # duplicates are suppressed (by commit rev) and remotes are always ignored
1169 # if a leaf has an exact tag match that will be output
1170 # note that recurse_deps_exclude IS honored for this operation
1171 find_leaves()
1173 no_remotes=1
1174 with_top_level=1
1175 recurse_preorder=
1176 seen_leaf_refs=
1177 seen_leaf_revs=
1178 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1179 [ "$_isleaf" = "1" ] && [ "$_ismissing" = "0" ] || continue
1180 if [ "$_istgish" != "0" ]; then
1181 fulldep="refs/$topbases/$_dep"
1182 else
1183 fulldep="refs/heads/$_dep"
1185 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1186 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1187 if fullrev="$(ref_exists_rev "$fulldep")"; then
1188 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1189 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1190 # See if Git knows it by another name
1191 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1192 echo "refs/tags/$tagname"
1193 else
1194 echo "$fulldep"
1196 esac
1198 esac
1199 done <<-EOT
1200 $(recurse_deps_internal -l -o=1 -- "$1")
1202 with_top_level=
1205 # branch_needs_update
1206 # This is a helper function for determining whether given branch
1207 # is up-to-date wrt. its dependencies. It expects input as if it
1208 # is called as a recurse_deps() helper.
1209 # In case the branch does need update, it will echo it together
1210 # with the branch backtrace on the output (see needs_update()
1211 # description for details) and set $_ret to non-zero.
1212 branch_needs_update()
1214 if [ -n "$_dep_missing" ]; then
1215 echo "! $_dep $_depchain"
1216 return 0
1219 if [ -n "$_dep_is_tgish" ]; then
1220 [ -z "$_dep_annihilated" ] || return 0
1222 if [ -n "$_dep_has_remote" ]; then
1223 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" || {
1224 echo ":refs/remotes/$base_remote/$_dep $_dep $_depchain"
1225 _ret=1
1228 # We want to sync with our base first and should output this before
1229 # the remote branch, but the order does not actually matter to tg-update
1230 # as it just recurses regardless, but it does matter for tg-info (which
1231 # treats out-of-date bases as though they were already merged in) so
1232 # we output the remote before the base.
1233 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1234 echo ": $_dep $_depchain"
1235 _ret=1
1236 return
1240 if [ -n "$_name" ]; then
1241 case "$_dep" in :*) _fulldep="${_dep#:}";; *) _fulldep="refs/heads/$_dep";; esac
1242 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1243 # Some new commits in _dep
1244 echo "$_dep $_depchain"
1245 _ret=1
1250 # needs_update NAME
1251 # This function is recursive; it outputs reverse path from NAME
1252 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1253 # inner paths first. Innermost name can be :refs/remotes/<remote>/<name>
1254 # if the head is not in sync with the <remote> branch <name>, ':' if
1255 # the head is not in sync with the base (in this order of priority)
1256 # or '!' if dependency is missing. Note that the remote branch, base
1257 # order is reversed from the order they will actually be updated in
1258 # order to accomodate tg info which treats out-of-date items that are
1259 # only in the base as already being in the head for status purposes.
1260 # It will also return non-zero status if NAME needs update (seems backwards
1261 # but think of it as non-zero status if any non-missing output lines produced)
1262 # If needs_update() hits missing dependencies, it will append
1263 # them to space-separated $missing_deps list and skip them.
1264 needs_update()
1266 recurse_deps branch_needs_update "$1"
1269 # append second arg to first arg variable gluing with space if first already set
1270 vplus()
1272 eval "$1=\"\${$1:+\$$1 }\$2\""
1275 # true if whitespace separated first var name list contains second arg
1276 # use `vcontains 3 "value" "some list"` for a literal list
1277 vcontains()
1279 eval case "\" \${$1} \"" in '*" $2 "*) return 0; esac; return 1'
1282 # if the $1 var does not already contain $2 it's appended
1283 vsetadd()
1285 vcontains "$1" "$2" || vplus "$1" "$2"
1288 # reset needs_update_check results to empty
1289 needs_update_check_clear()
1291 unset_ needs_update_processed needs_update_behind needs_update_ahead needs_update_partial
1294 # needs_update_check NAME...
1296 # A faster version of needs_update that always succeeds
1297 # No output and unsuitable for actually performing updates themselves
1298 # If any of NAME... are NOT up-to-date AND they were not already processed
1299 # return status always will be zero however a simple check of
1300 # needs_update_behind after the call will answer the:
1301 # "are any out of date?": test -n "$needs_update_behind"
1302 # "is <x> out of date?": vcontains needs_update_behind "<x>"
1304 # Note that results are cumulative and "no_remotes" is honored as well as other
1305 # variables that modify recurse_deps_internal behavior. See the preceding
1306 # function to reset the results to empty when accumulation should start over.
1308 # Unlike needs_update, the branch names are themselves also checked to see if
1309 # they are out-of-date with respect to their bases or remote branches (not just
1310 # their remote bases). However, this can muddy some status results so this
1311 # can be disabled by setting needs_update_check_no_self to a non-empty value.
1313 # Unlike needs_update, here the remote base check is handled together with the
1314 # remote head check so if one is modified the other is too in the same way.
1316 # Dependencies are normally considered "behind" if they need an update from
1317 # their base or remote but this can be suppressed by setting the
1318 # needs_update_check_no_same to a non-empty value. This will NOT prevent
1319 # parents of those dependencies from still being considered behind in such a
1320 # case even though the dependency itself will not be. Note that setting
1321 # needs_update_check_no_same also implies needs_update_check_no_self.
1323 # The following whitespace-separated lists are updated with the results:
1325 # The "no_remotes" setting is obeyed but remote names themselves will never
1326 # appear in any of the lists
1328 # needs_update_processed
1329 # The branch names in here have been processed and will be skipped
1331 # needs_update_behind
1332 # Any branch named in here needs an update from one or more of its
1333 # direct or indirect dependencies (i.e. it's "out-of-date")
1335 # needs_update_ahead
1336 # Any branch named in here is NOT fully contained by at least one of
1337 # its dependents (i.e. it's a source of "out-of-date (aka dirty)"ness
1339 # needs_update_partial
1340 # Any branch names in here are either missing themselves or have one
1341 # or more detected missing dependencies (a completely missing remote
1342 # branch is never "detected")
1343 needs_update_check()
1345 # each head must be processed independently or else there will be
1346 # confusion about who's missing what and which branches actually are
1347 # out of date
1348 tmptgrdi="$tg_tmp_dir/tgrdi.$$"
1349 for nucname in "$@"; do
1350 ! vcontains needs_update_processed "$nucname" || continue
1351 # no need to fuss with recurse_deps, just use
1352 # recurse_deps_internal directly
1353 recurse_deps_internal -s -o=-1 "$nucname" >"$tmptgrdi"
1354 while read -r _rdi_m _rdi_t _rdi_l _rdi_v _rdi_node _rdi_parent _rdi_chain; do
1355 case "$_rdi_node" in ""|:*) continue; esac # empty or checked with remote
1356 vsetadd needs_update_processed "$_rdi_node"
1357 if [ "$_rdi_m" != "0" ]; then # missing
1358 vsetadd needs_update_partial "$_rdi_node"
1359 [ -z "$_rdi_parent" ] || vsetadd needs_update_partial "$_rdi_parent"
1360 continue
1362 [ "$_rdi_t$_rdi_l" != "12" ] || continue # always skip annihilated
1363 _rdi_dertee= # :)
1364 if [ -n "$_rdi_parent" ]; then # not a "self" line
1365 ! vcontains needs_update_partial "$_rdi_node" || vsetadd needs_update_partial "$_rdi_parent"
1366 ! vcontains needs_update_behind "$_rdi_node" || _rdi_dertee=2
1367 else
1368 [ -z "$needs_update_check_no_self$needs_update_check_no_same" ] || continue # skip self
1370 if [ -z "$_rdi_dertee" ]; then
1371 if [ "$_rdi_t" != "0" ]; then # tgish
1372 if branch_contains "refs/heads/$_rdi_node" "refs/$topbases/$_rdi_node"; then
1373 if [ "$_rdi_t" = "2" ]; then # will never be "2" when no_remotes is set
1374 branch_contains "refs/heads/$_rdi_node" "refs/remotes/$base_remote/$_rdi_node" &&
1375 branch_contains "refs/$topbases/$_rdi_node" "refs/remotes/$base_remote/${topbases#heads/}/$_rdi_node" ||
1376 _rdi_dertee=3
1378 else
1379 _rdi_dertee=3
1381 [ -z "$_rdi_dertee" ] || [ -n "$needs_update_check_no_same" ] || _rdi_dertee=1
1384 [ z"$_rdi_dertee" != z"1" ] || vsetadd needs_update_behind "$_rdi_node"
1385 [ -n "$_rdi_parent" ] || continue # self line
1386 if ! branch_contains "refs/$topbases/$_rdi_parent" "refs/heads/$_rdi_node"; then
1387 _rdi_dertee=1
1388 vsetadd needs_update_ahead "$_rdi_node"
1390 [ -z "$_rdi_dertee" ] || vsetadd needs_update_behind "$_rdi_parent"
1391 done <"$tmptgrdi"
1392 done
1395 # branch_empty NAME [-i | -w]
1396 branch_empty()
1398 if [ -z "$2" ]; then
1399 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1400 _result=
1401 _result_rev=
1402 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1403 [ -z "$_result" ] || [ "$_result_rev" != "$_rev" ] || return $_result
1404 _result=0
1405 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1406 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1407 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1408 return $_result
1409 else
1410 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1414 v_get_tdmopt_internal()
1416 [ -n "$1" ] && [ -n "$3" ] || return 0
1417 [ "$2" = "-i" ] || [ "$2" = "-w" ] || return 0
1418 ensure_work_tree
1419 _optval=
1420 if v_verify_topgit_branch _tghead "HEAD" -f; then
1421 if [ "$2" = "-w" ] && [ -f "$root_dir/$3" ] && [ -r "$root_dir/$3" ]; then
1422 _opthash=
1423 if _opthash="$(git hash-object -w -t blob --stdin <"$root_dir/$3")" && [ -n "$_opthash" ]; then
1424 _optval="$4\"$_tghead:$_opthash\""
1426 elif [ "$2" = "-i" ]; then
1427 if _opthash="$(git rev-parse --quiet --verify ":0:$3" --)" && [ -n "$_opthash" ]; then
1428 _optval="$4\"$_tghead:$_opthash\""
1432 eval "$1="'"$_optval"'
1435 # set var $1 to the correct -td= option for use in an eval for $2 -i or -w mode
1436 v_get_tdopt() { v_get_tdmopt_internal "$1" "$2" ".topdeps" "-td="; }
1438 # set var $1 to the correct -tm= option for use in an eval for $2 -i or -w mode
1439 v_get_tmopt() { v_get_tdmopt_internal "$1" "$2" ".topmsg" "-tm="; }
1441 # checkout_symref_full [-f] FULLREF [SEED]
1442 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1443 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1444 # MUST be a committish which if present will be used instead of current FULLREF
1445 # (and FULLREF will be updated to it as well in that case)
1446 # Any merge state is always cleared by this function
1447 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1448 # instead of -m) but it will clear out any unmerged entries
1449 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1450 checkout_symref_full()
1452 _mode=-m
1453 _head="HEAD"
1454 if [ "$1" = "-f" ]; then
1455 _mode="--reset"
1456 _head=
1457 shift
1459 _ishash=
1460 case "$1" in
1461 refs/?*)
1463 $octet20)
1464 _ishash=1
1465 [ -z "$2" ] || [ "$1" = "$2" ] ||
1466 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1467 set -- HEAD "$1"
1470 die "programmer error: invalid checkout_symref_full \"$1\""
1472 esac
1473 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1474 die "invalid committish: \"${2:-$1}\""
1475 # Clear out any MERGE_HEAD kruft
1476 rm -f "$git_dir/MERGE_HEAD" || :
1477 # We have to do all the hard work ourselves :/
1478 # This is like git checkout -b "$1" "$2"
1479 # (or just git checkout "$1"),
1480 # but never creates a detached HEAD (unless $1 is a hash)
1481 git read-tree -u $_mode $_head "$_seedrev" &&
1483 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1484 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1485 } && {
1486 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1490 # switch_to_base NAME [SEED]
1491 switch_to_base()
1493 checkout_symref_full "refs/$topbases/$1" "$2"
1496 # run editor with arguments
1497 # the editor setting will be cached in $tg_editor (which is eval'd)
1498 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1499 # just in case, noalt_setup will be in effect while the editor is running
1500 run_editor()
1502 tg_editor="$GIT_EDITOR"
1503 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1505 noalt_setup
1506 eval "$tg_editor" '"$@"'
1510 # Show the help messages.
1511 do_help()
1513 _www=
1514 if [ "$1" = "-w" ]; then
1515 _www=1
1516 shift
1518 if [ "$1" = "st" ]; then
1519 shift
1520 set -- "status" "$@"
1522 if [ -z "$1" ] ; then
1523 # This is currently invoked in all kinds of circumstances,
1524 # including when the user made a usage error. Should we end up
1525 # providing more than a short help message, then we should
1526 # differentiate.
1527 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1529 ## Build available commands list for help output
1531 cmds=
1532 sep=
1533 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1534 ! [ -r "$cmd" ] && continue
1535 # strip directory part and "tg-" prefix
1536 cmd="${cmd##*/}"
1537 cmd="${cmd#tg-}"
1538 [ "$cmd" != "migrate-bases" ] || continue
1539 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1540 cmds="$cmds$sep$cmd"
1541 sep="|"
1542 done
1544 echo "TopGit version $TG_VERSION - A different patch queue manager"
1545 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u]" \
1546 "[-c <name>=<val>] [--[no-]pager|-p] [-w [:]<tgtag>] ($cmds) ..."
1547 echo " Or: $tgname help [-w] [<command>]"
1548 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1549 elif [ -r "$TG_INST_CMDDIR"/tg-$1 ] || [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1550 if [ -n "$_www" ]; then
1551 nohtml=
1552 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1553 echo "${0##*/}: missing html help file:" \
1554 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1555 nohtml=1
1557 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1558 echo "${0##*/}: missing html help file:" \
1559 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1560 nohtml=1
1562 if [ -n "$nohtml" ]; then
1563 echo "${0##*/}: use" \
1564 "\"${0##*/} help $1\" instead" 1>&2
1565 exit 1
1567 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1568 exit
1570 output()
1572 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1573 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1574 echo
1575 elif [ "$1" = "help" ]; then
1576 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1577 echo
1578 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1579 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1580 echo
1582 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1583 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1586 page output "$1"
1587 else
1588 echo "${0##*/}: no help for $1" 1>&2
1589 do_help
1590 exit 1
1594 check_status()
1596 git_state=
1597 git_remove=
1598 tg_state=
1599 tg_remove=
1600 tg_topmerge=
1601 setup_git_dir_is_bare
1602 [ -z "$git_dir_is_bare" ] || return 0
1604 if [ -e "$git_dir/MERGE_HEAD" ]; then
1605 git_state="merge"
1606 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1607 git_state="am"
1608 git_remove="$git_dir/rebase-apply"
1609 elif [ -e "$git_dir/rebase-apply" ]; then
1610 git_state="rebase"
1611 git_remove="$git_dir/rebase-apply"
1612 elif [ -e "$git_dir/rebase-merge" ]; then
1613 git_state="rebase"
1614 git_remove="$git_dir/rebase-merge"
1615 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1616 git_state="cherry-pick"
1617 elif [ -e "$git_dir/BISECT_LOG" ]; then
1618 git_state="bisect"
1619 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1620 git_state="revert"
1622 git_remove="${git_remove#./}"
1624 if [ -e "$git_dir/tg-update" ]; then
1625 tg_state="update"
1626 tg_remove="$git_dir/tg-update"
1627 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1629 tg_remove="${tg_remove#./}"
1632 # Show status information
1633 do_status()
1635 do_status_result=0
1636 do_status_verbose=
1637 do_status_help=
1638 abbrev=refs
1639 pfx=
1640 while [ $# -gt 0 ] && case "$1" in
1641 --help|-h)
1642 do_status_help=1
1643 break;;
1644 -vv)
1645 # kludge in this common bundling option
1646 abbrev=
1647 do_status_verbose=1
1648 pfx="## "
1650 --verbose|-v)
1651 [ -z "$do_status_verbose" ] || abbrev=
1652 do_status_verbose=1
1653 pfx="## "
1655 --exit-code)
1656 do_status_result=2
1659 die "unknown status argument: $1"
1661 esac; do shift; done
1662 if [ -n "$do_status_help" ]; then
1663 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1664 return
1666 check_status
1667 symref="$(git symbolic-ref --quiet HEAD)" || :
1668 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1669 if [ -n "$symref" ]; then
1670 uprefpart=
1671 if [ -n "$headrv" ]; then
1672 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1673 if [ -n "$upref" ]; then
1674 uprefpart=" ... ${upref#$abbrev/remotes/}"
1675 mbase="$(git merge-base HEAD "$upref")" || :
1676 ahead="$(git rev-list --count HEAD ${mbase:+--not} $mbase)" || ahead=0
1677 behind="$(git rev-list --count "$upref" ${mbase:+--not} $mbase)" || behind=0
1678 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1679 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1680 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1681 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1682 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1685 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1686 else
1687 echol "${pfx}HEAD -> ${headrv:-?}"
1689 if [ -n "$tg_state" ]; then
1690 extra=
1691 if [ "$tg_state" = "update" ]; then
1692 IFS= read -r uname <"$git_dir/tg-update/name" || :
1693 [ -z "$uname" ] ||
1694 extra="; currently updating branch '$uname'"
1696 echol "${pfx}tg $tg_state in progress$extra"
1697 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1698 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1699 cat "$git_dir/tg-update/fullcmd"
1700 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1701 if [ $bcnt -gt 1 ]; then
1702 pcnt=0
1703 ! [ -s "$git_dir/tg-update/processed" ] ||
1704 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1705 echo "${pfx}$pcnt of $bcnt branches updated so far"
1708 if [ "$tg_state" = "update" ]; then
1709 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1710 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1711 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1712 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1715 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1716 if [ "$git_state" = "merge" ]; then
1717 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1718 if [ $ucnt -gt 0 ]; then
1719 echo "${pfx}"'fix conflicts and then "git commit" the result'
1720 else
1721 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1724 if [ -z "$git_state" ]; then
1725 setup_git_dir_is_bare
1726 [ -z "$git_dir_is_bare" ] || return 0
1727 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository???
1728 gspcnt=0
1729 [ -z "$gsp" ] ||
1730 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1731 untr=
1732 if [ "$gspcnt" -eq 0 ]; then
1733 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1734 echo "${pfx}working directory is clean$untr"
1735 [ -n "$tg_state" ] || do_status_result=0
1736 else
1737 echo "${pfx}working directory is DIRTY"
1738 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1743 ## Pager stuff
1745 # isatty FD
1746 isatty()
1748 test -t $1
1751 # pass "diff" to get pager.diff
1752 # if pager.$1 is a boolean false returns cat
1753 # if set to true or unset fails
1754 # otherwise succeeds and returns the value
1755 get_pager()
1757 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1758 [ "$_x" != "true" ] || return 1
1759 echo "cat"
1760 return 0
1762 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1763 echol "$_x"
1764 return 0
1766 return 1
1769 # setup_pager
1770 # Set TG_PAGER to a valid executable
1771 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1772 # See also the following "page" function for ease of use
1773 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1774 # Preference is (same as Git):
1775 # 1. GIT_PAGER
1776 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1777 # 3. core.pager (only if set)
1778 # 4. PAGER
1779 # 5. git var GIT_PAGER
1780 # 6. less
1781 setup_pager()
1783 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1785 emptypager=
1786 if [ -z "$TG_PAGER_IN_USE" ]; then
1787 # TG_PAGER = GIT_PAGER | PAGER | less
1788 # NOTE: GIT_PAGER='' is significant
1789 if [ -n "${GIT_PAGER+set}" ]; then
1790 TG_PAGER="$GIT_PAGER"
1791 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1792 TG_PAGER="$_dp"
1793 elif _cp="$(git config core.pager 2>/dev/null)"; then
1794 TG_PAGER="$_cp"
1795 elif [ -n "${PAGER+set}" ]; then
1796 TG_PAGER="$PAGER"
1797 else
1798 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1799 [ "$_gp" != ":" ] || _gp=
1800 TG_PAGER="${_gp:-less}"
1802 if [ -z "$TG_PAGER" ]; then
1803 emptypager=1
1804 TG_PAGER=cat
1806 else
1807 emptypager=1
1808 TG_PAGER=cat
1811 # Set pager default environment variables
1812 # see pager.c:setup_pager
1813 if [ -z "${LESS+set}" ]; then
1814 LESS="-FRX"
1815 export LESS
1817 if [ -z "${LV+set}" ]; then
1818 LV="-c"
1819 export LV
1822 # this is needed so e.g. $(git diff) will still colorize it's output if
1823 # requested in ~/.gitconfig with color.diff=auto
1824 GIT_PAGER_IN_USE=1
1825 export GIT_PAGER_IN_USE
1827 # this is needed so we don't get nested pagers
1828 TG_PAGER_IN_USE=1
1829 export TG_PAGER_IN_USE
1832 # page eval_arg [arg ...]
1834 # Calls setup_pager then evals the first argument passing it all the rest
1835 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1836 # by setup_pager (in which case the output is left as-is).
1838 # To handle arbitrary paging duties, collect lines to be paged into a
1839 # function and then call page with the function name or perhaps func_name "$@".
1841 # If no arguments at all are passed in do nothing (return with success).
1842 page()
1844 [ $# -gt 0 ] || return 0
1845 setup_pager
1846 _evalarg="$1"; shift
1847 if [ -n "$emptypager" ]; then
1848 eval "$_evalarg" '"$@"'
1849 else
1850 { eval "$_evalarg" '"$@"';} | eval "$TG_PAGER"
1854 # get_temp NAME [-d]
1855 # creates a new temporary file (or directory with -d) in the global
1856 # temporary directory $tg_tmp_dir with pattern prefix NAME
1857 get_temp()
1859 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1862 # automatically called by strftime
1863 # does nothing if already setup
1864 # may be called explicitly if the first call would otherwise be in a subshell
1865 # so that the setup is only done once before subshells start being spawned
1866 setup_strftime()
1868 [ -z "$strftime_is_setup" ] || return 0
1870 # date option to format raw epoch seconds values
1871 daterawopt=
1872 _testes='951807788'
1873 _testdt='2000-02-29 07:03:08 UTC'
1874 _testfm='%Y-%m-%d %H:%M:%S %Z'
1875 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1876 daterawopt='-d@'
1877 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1878 daterawopt='-r'
1880 strftime_is_setup=1
1883 # $1 => strftime format string to use
1884 # $2 => raw timestamp as seconds since epoch
1885 # $3 => optional time zone string (empty/absent for local time zone)
1886 strftime()
1888 setup_strftime
1889 if [ -n "$daterawopt" ]; then
1890 if [ -n "$3" ]; then
1891 TZ="$3" date "$daterawopt$2" "+$1"
1892 else
1893 date "$daterawopt$2" "+$1"
1895 else
1896 if [ -n "$3" ]; then
1897 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1898 else
1899 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1904 got_cdup_result=
1905 git_cdup_result=
1906 v_get_show_cdup()
1908 if [ -z "$got_cdup_result" ]; then
1909 git_cdup_result="$(git rev-parse --show-cdup)"
1910 got_cdup_result=1
1912 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1915 setup_git_dir_is_bare()
1917 if [ -z "$git_dir_is_bare_setup" ]; then
1918 git_dir_is_bare="$(git rev-parse --is-bare-repository)"
1919 [ z"$git_dir_is_bare" = z"true" ] || git_dir_is_bare=
1920 git_dir_is_bare_setup=1
1924 git_hooks_pat_list="\
1925 [a]pplypatch-ms[g] [p]re-applypatc[h] [p]ost-applypatc[h] [p]re-commi[t] \
1926 [p]repare-commit-ms[g] [c]ommit-ms[g] [p]ost-commi[t] [p]re-rebas[e] \
1927 [p]ost-checkou[t] [p]ost-merg[e] [p]re-pus[h] [p]re-receiv[e] [u]pdat[e] \
1928 [p]ost-receiv[e] [p]ost-updat[e] [p]ush-to-checkou[t] [p]re-auto-g[c] \
1929 [p]ost-rewrit[e]"
1931 # git_hooks_dir must already be set to the value of core.hooksPath which
1932 # exists and is an absolute path. The first and only argument is the
1933 # "pwd -P" of the $git_hooks_dir directory. If the core.hooksPath setting
1934 # appears to be "friendly" attempt to alter it to be an absolute path to
1935 # "$git_common_dir/hooks" instead. A "friendly" core.hooksPath setting
1936 # points to a directory for which "$git_common_dir/hooks" already has
1937 # entries which are symbolic links to the same core.hooksPath items.
1938 # There's no POSIX readlink utility, but there is a 'cmp -s' utility so we
1939 # use that instead to check. Also the "friendly" core.hooksPath must be
1940 # something that's recognizable as belonging to a "friendly".
1941 maybe_adjust_friendly_hooks_path()
1943 case "$1" in */_global/hooks);;*) return 0; esac
1944 [ -n "$1" ] && [ -d "$1" ] && [ -d "$git_common_dir/hooks" ] || return 0
1945 [ -w "$git_common_dir" ] || return 0
1946 ! [ -e "$git_common_dir/config" ] || {
1947 [ -f "$git_common_dir/config" ] && [ -w "$git_common_dir/config" ]
1948 } || return 0
1949 oktoswitch=1
1950 for ghook in $(cd "$1" && eval "echo $git_hooks_pat_list"); do
1951 case "$ghook" in "["*) continue; esac
1952 [ -x "$1/$ghook" ] &&
1953 [ -f "$1/$ghook" ] || continue
1954 [ -x "$git_common_dir/hooks/$ghook" ] &&
1955 [ -f "$git_common_dir/hooks/$ghook" ] &&
1956 cmp -s "$1/$ghook" "$git_common_dir/hooks/$ghook" || {
1957 oktoswitch=
1958 break
1960 done
1961 if [ -n "$oktoswitch" ]; then
1962 # a known "friendly" was detected and the hooks match;
1963 # go ahead and silently switch the path
1964 ! git config core.hooksPath "$git_common_dir/hooks" >/dev/null 2>&1 ||
1965 git_hooks_dir="$git_common_dir/hooks"
1967 unset_ oktoswitch
1968 return 0
1971 setup_git_dirs()
1973 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1974 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1975 git_dir="$(cd "$git_dir" && pwd)"
1977 if [ -z "$git_common_dir" ]; then
1978 if vcmp "$git_version" '>=' "2.5"; then
1979 # rev-parse --git-common-dir is broken and may give
1980 # an incorrect result unless the current directory is
1981 # already set to the top level directory
1982 v_get_show_cdup
1983 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1984 else
1985 git_common_dir="$git_dir"
1988 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1989 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1990 git_hooks_dir="$git_common_dir/hooks"
1991 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1992 case "$gchp" in
1993 /[!/]*)
1994 if [ -d "$gchp" ]; then
1995 # if core.hooksPath is just another name for
1996 # $git_common_dir/hooks, keep referring to it
1997 # by $git_common_dir/hooks
1998 abscdh="$(cd "$git_common_dir" && pwd -P)/hooks"
1999 abshpd="$(cd "$gchp" && pwd -P)"
2000 if [ "$abshpd" != "$abscdh" ]; then
2001 git_hooks_dir="$gchp"
2002 maybe_adjust_friendly_hooks_path "$abshpd"
2004 unset_ abscdh abshpd
2005 else
2006 [ -n "$1" ] || warn "ignoring non-existent core.hooksPath: $gchp"
2010 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
2012 esac
2013 unset_ gchp
2017 basic_setup_remote()
2019 if [ -z "$base_remote" ]; then
2020 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
2021 base_remote="$TG_EXPLICIT_REMOTE"
2022 else
2023 base_remote="$(git config topgit.remote 2>/dev/null)" || :
2028 basic_setup()
2030 setup_git_dirs $1
2031 basic_setup_remote
2032 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
2033 tgnosequester=
2034 [ "$tgsequester" != "false" ] || tgnosequester=1
2035 unset_ tgsequester
2037 # catch errors if topbases is used without being set
2038 unset_ tg_topbases_set
2039 topbases="programmer*:error"
2040 topbasesrx="programmer*:error}"
2041 oldbases="$topbases"
2044 tmpdir_setup()
2046 [ -z "$tg_tmp_dir" ] || return 0
2047 if [ -n "$TG_TMPDIR" ] && [ -d "$TG_TMPDIR" ] && [ -w "$TG_TMPDIR" ] &&
2048 { >"$TG_TMPDIR/.check"; } >/dev/null 2>&1; then
2049 tg_tmp_dir="$TG_TMPDIR"
2050 else
2051 tg_tmp_dir=
2052 TRAPEXIT_='${TG_DEBUG:+echo} rm -rf "$tg_tmp_dir" >&2'
2053 trap 'trapexit_ 129' HUP
2054 trap 'trapexit_ 130' INT
2055 trap 'trapexit_ 131' QUIT
2056 trap 'trapexit_ 134' ABRT
2057 trap 'trapexit_ 141' PIPE
2058 trap 'trapexit_ 143' TERM
2059 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2060 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2061 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2062 [ -z "$tg_tmp_dir" ] || tg_tmp_dir="$(cd "$tg_tmp_dir" && pwd -P)"
2064 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_tmp_dir/.check"; } >/dev/null 2>&1 ||
2065 die "could not create a writable temporary directory"
2067 # whenever tg_tmp_dir is != "" these must always be set
2068 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
2069 tg_ref_cache_br="$tg_ref_cache.br"
2070 tg_ref_cache_rbr="$tg_ref_cache.rbr"
2071 tg_ref_cache_ann="$tg_ref_cache.ann"
2072 tg_ref_cache_dep="$tg_ref_cache.dep"
2075 cachedir_setup()
2077 [ -z "$tg_cache_dir" ] || return 0
2078 user_id_no="$(id -u)" || :
2079 : "${user_id_no:=_99_}"
2080 tg_cache_dir="$git_common_dir/tg-cache"
2081 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2082 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
2083 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2084 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2085 if [ -z "$tg_cache_dir" ]; then
2086 tg_cache_dir="$tg_tmp_dir/tg-cache"
2087 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2088 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2090 [ -n "$tg_cache_dir" ] ||
2091 die "could not create a writable tg-cache directory (even a temporary one)"
2093 if [ -n "$2" ]; then
2094 # allow the wayback machine to share a separate cache
2095 [ -d "$tg_cache_dir/wayback" ] || mkdir "$tg_cache_dir/wayback" >/dev/null 2>&1 || :
2096 ! [ -d "$tg_cache_dir/wayback" ] || ! { >"$tg_cache_dir/wayback/.tgcache"; } >/dev/null 2>&1 ||
2097 tg_cache_dir="$tg_cache_dir/wayback"
2101 # set up alternate deb dirs
2102 altodb_setup()
2104 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
2105 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
2106 # so we avoid it if possible and require v2.11.1 to do it at all
2107 # otherwise just don't make an alternates temporary store in that case;
2108 # it's okay to not have one; everything will still work; the nicety of
2109 # making the temporary tree objects vanish when tg exits just won't
2110 # happen in that case but nothing will break also be sure to reuse
2111 # the parent's if we've been recursively invoked and it's for the
2112 # same repository we were invoked on
2114 tg_use_alt_odb=1
2115 _fullodbdir=
2116 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
2117 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] && _fullodbdir="$(cd "$_odbdir" && pwd -P)" ||
2118 die "could not find objects directory"
2119 if [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
2120 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
2121 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
2122 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
2123 tg_use_alt_odb=2
2126 _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
2127 if [ "$tg_use_alt_odb" = "1" ]; then
2128 # create an alternate objects database to keep the ephemeral objects in
2129 mkdir -p "$tg_tmp_dir/objects/info"
2130 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
2131 [ "$_fullodbdir" = "$TG_OBJECT_DIRECTORY" ] ||
2132 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
2134 case "$_fulltmpdir" in *[";:"]*|'"'*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
2135 if [ "$tg_use_alt_odb" = "1" ]; then
2136 case "$TG_OBJECT_DIRECTORY" in
2137 *[";:"]*|'"'*)
2138 # surround in "..." and backslash-escape internal '"' and '\\'
2139 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
2140 sed 's/\([""\\]\)/\\\1/g')\""
2143 _altodbdq="$TG_OBJECT_DIRECTORY"
2145 esac
2146 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2147 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2148 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2149 else
2150 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
2152 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
2153 if [ -n "$GIT_OBJECT_DIRECTORY" ]; then
2154 export GIT_OBJECT_DIRECTORY
2155 else
2156 unset_ GIT_OBJECT_DIRECTORY
2161 noalt_setup()
2163 if [ "${TG_PRESERVED_ALTERNATES+set}" = "set" ]; then
2164 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
2165 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2166 export GIT_ALTERNATE_OBJECT_DIRECTORIES
2167 else
2168 unset_ GIT_ALTERNATE_OBJECT_DIRECTORIES
2171 unset_ TG_TMPDIR TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES tg_use_alt_odb
2174 ## Initial setup
2175 initial_setup()
2177 # suppress the merge log editor feature since git 1.7.10
2179 GIT_MERGE_AUTOEDIT=no
2180 export GIT_MERGE_AUTOEDIT
2182 basic_setup $1
2183 iowopt=
2184 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
2185 gcfbopt=
2186 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
2187 auhopt=
2188 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
2189 v_get_show_cdup root_dir
2190 root_dir="${root_dir:-.}"
2191 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
2192 [ "$logrefupdates" = "true" ] || logrefupdates=
2194 # make sure root_dir doesn't end with a trailing slash.
2196 root_dir="${root_dir%/}"
2198 # create global temporary and cache directories, usually inside GIT_DIR
2200 tmpdir_setup
2201 unset_ TG_TMPDIR
2202 cachedir_setup
2204 # the wayback machine directory serves as its own "altodb"
2205 [ -n "$wayback" ] || altodb_setup
2208 activate_wayback_machine()
2210 [ -n "${1#:}" ] || [ -n "$2" ] || { wayback=; return 0; }
2211 setup_git_dirs
2212 tmpdir_setup
2213 altodb_setup
2214 tgwbr=
2215 tgwbr2=
2216 if [ -n "${1#:}" ]; then
2217 tgwbr="$(get_temp wbinfo)"
2218 tgwbr2="${tgwbr}2"
2219 tg revert --list --no-short "${1#:}" >"$tgwbr" && test -s "$tgwbr" || return 1
2220 # tg revert will likely leave a revert-tag-only cache which is not what we want
2221 remove_ref_cache
2223 cachedir_setup "" 1 # use a separate wayback cache dir
2224 # but don't step on the normal one if the separate one could not be set up
2225 case "$tg_cache_dir" in */wayback);;*) tg_cache_dir=; esac
2226 altodb="$TG_OBJECT_DIRECTORY"
2227 if [ -n "$3" ] && [ -n "$2" ]; then
2228 [ -d "$3" ] || { mkdir -p "$3" && [ -d "$3" ]; } ||
2229 die "could not create wayback directory: $3"
2230 tg_wayback_dir="$(cd "$3" && pwd -P)" || die "could not get wayback directory full path"
2231 [ -d "$tg_wayback_dir/.git" ] || { mkdir -p "$tg_wayback_dir/.git" && [ -d "$tg_wayback_dir/.git" ]; } ||
2232 die "could not initialize wayback directory: $3"
2233 is_empty_dir "$tg_wayback_dir" ".git" && is_empty_dir "$tg_wayback_dir/.git" "." ||
2234 die "wayback directory is not empty: $3"
2235 mkdir "$tg_wayback_dir/.git/objects"
2236 mkdir "$tg_wayback_dir/.git/objects/info"
2237 cat "$altodb/info/alternates" >"$tg_wayback_dir/.git/objects/info/alternates"
2238 else
2239 tg_wayback_dir="$tg_tmp_dir/wayback"
2240 mkdir "$tg_wayback_dir"
2241 mkdir "$tg_wayback_dir/.git"
2242 ln -s "$altodb" "$tg_wayback_dir/.git/objects"
2244 mkdir "$tg_wayback_dir/.git/refs"
2245 printf '0 Wayback Machine' >"$tg_wayback_dir/.git/gc.pid"
2246 qpesc="$(printf '%s\n' "$git_common_dir" | sed -e 's/\([\\""]\)/\\\1/g' -e '$!s/$/\\n/' | tr -d '\n')"
2247 laru="false"
2248 [ -z "$2" ] || laru="true"
2249 printf '%s' "\
2250 [include]
2251 path = \"$qpesc/config\"
2252 [core]
2253 bare = false
2254 logAllRefUpdates = $laru
2255 repositoryFormatVersion = 0
2256 [extensions]
2257 preciousObjects = true
2258 [gc]
2259 auto = 0
2260 autoDetach = false
2261 autoPackLimit = 0
2262 packRefs = false
2263 [remote \"wayback\"]
2264 url = \"$qpesc\"
2265 [push]
2266 default = nothing
2267 followTags = true
2268 [alias]
2269 wayback-updates = fetch -u --force --no-tags --dry-run wayback refs/*:refs/*
2270 " >"$tg_wayback_dir/.git/config"
2271 cat "$git_dir/HEAD" >"$tg_wayback_dir/.git/HEAD"
2272 case "$1" in ":"?*);;*)
2273 git show-ref >"$tg_wayback_dir/.git/packed-refs"
2274 git --git-dir="$tg_wayback_dir/.git" pack-refs --all
2275 esac
2276 noalt_setup
2277 TG_OBJECT_DIRECTORY="$altodb" && export TG_OBJECT_DIRECTORY
2278 if [ -n "${1#:}" ]; then
2279 <"$tgwbr" sed 's/^\([^ ][^ ]*\) \([^ ][^ ]*\)$/update \2 \1/' |
2280 git --git-dir="$tg_wayback_dir/.git" update-ref -m "wayback to $1" ${2:+--create-reflog} --stdin
2282 if test -n "$2"; then
2283 # extra setup for potential shell
2284 qpesc2="$(printf '%s\n' "$git_common_dir" | sed -e 's/\([\\""]\)/\\\\\1/g' -e '$!s/$/\\n/' | tr -d '\n')"
2285 printf '\twayback-repository = "!printf '\''%%s\\\\n'\'' \\"%s\\""\n' "$qpesc2" >>"$tg_wayback_dir/.git/config"
2286 qtesc="$(printf '%s\n' "${1:-:}" | sed 's/\([""]\)/\\\1/g')"
2287 printf '\twayback-tag = "!printf '\''%%s\\\\n'\'' \\"%s\\""\n' "$qtesc" >>"$tg_wayback_dir/.git/config"
2288 if [ -d "$git_common_dir/rr-cache" ]; then
2289 ln -s "$git_common_dir/rr-cache" "$tg_wayback_dir/.git/rr-cache"
2290 printf "[rerere]\n\tenabled = true\n" >>"$tg_wayback_dir/.git/config"
2292 if [ z"$2" != z"2" ]; then
2293 wbauth=
2294 wbprnt=
2295 if [ -n "${1#:}" ]; then
2296 [ -n "$tgwbr2" ] || tgwbr2="$(get_temp wbtag)"
2297 git --git-dir="$git_common_dir" cat-file tag "${1#:}" >"$tgwbr2" || return 1
2298 wbprnt="${lf}parent $(git --git-dir="$git_common_dir" rev-parse --verify --quiet "${1#:}"^0 -- 2>/dev/null)" || wbprnt=
2299 wbauth="$(<"$tgwbr2" awk '{if(!$0)exit;if($1=="tagger")print "author" substr($0,7)}')"
2301 wbcmtr="committer Wayback Machine <-> $(date "+%s %z")"
2302 [ -n "$wbauth" ] || wbauth="author${wbcmtr#committer}"
2303 wbtree="$(git --git-dir="$tg_wayback_dir/.git" mktree </dev/null)"
2304 wbcmt="$({
2305 printf '%s\n' "tree $wbtree$wbprnt" "$wbauth" "$wbcmtr" ""
2306 if [ -n "$tgwbr2" ]; then
2307 <"$tgwbr2" sed -e '1,/^$/d' -e '/^-----BEGIN/,$d' | git stripspace
2308 else
2309 echo "Wayback Machine"
2311 } | git --git-dir="$tg_wayback_dir/.git" hash-object -t commit -w --stdin)"
2312 test -n "$wbcmt" || return 1
2313 echo "$wbcmt" >"$tg_wayback_dir/.git/HEAD"
2316 cd "$tg_wayback_dir"
2317 unset git_dir git_common_dir
2320 set_topbases()
2322 # refer to "top-bases" in a refname with $topbases
2324 [ -z "$tg_topbases_set" ] || return 0
2326 topbases_implicit_default=1
2327 # See if topgit.top-bases is set to heads or refs
2328 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
2329 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
2330 if [ -n "$1" ]; then
2331 # never die on the hook script
2332 unset_ tgtb
2333 else
2334 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
2337 if [ -n "$tgtb" ]; then
2338 case "$tgtb" in
2339 heads)
2340 topbases="heads/{top-bases}"
2341 topbasesrx="heads/[{]top-bases[}]"
2342 oldbases="top-bases";;
2343 refs)
2344 topbases="top-bases"
2345 topbasesrx="top-bases"
2346 oldbases="heads/{top-bases}";;
2347 esac
2348 # MUST NOT be exported
2349 unset_ tgtb tg_topbases_set topbases_implicit_default
2350 tg_topbases_set=1
2351 return 0
2353 unset_ tgtb
2355 # check heads and top-bases and see what state the current
2356 # repository is in. remotes are ignored.
2358 rc=0 activebases=
2359 activebases="$(
2360 git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null |
2361 run_awk_ref_prefixes ${1:+-e} -n -- "refs/heads/{top-bases}" "refs/top-bases" "refs/heads")" ||
2362 rc=$?
2363 if [ "$rc" = "65" ]; then
2364 # Complain and die
2365 err "repository contains existing TopGit branches"
2366 err "but some use refs/top-bases/... for the base"
2367 err "and some use refs/heads/{top-bases}/... for the base"
2368 err "with the latter being the new, preferred location"
2369 err "set \"topgit.top-bases\" to either \"heads\" to use"
2370 err "the new heads/{top-bases} location or \"refs\" to use"
2371 err "the old top-bases location."
2372 err "(the tg migrate-bases command can also resolve this issue)"
2373 die "schizophrenic repository requires topgit.top-bases setting"
2375 [ -z "$activebases" ] || unset_ topbases_implicit_default
2376 if [ "$activebases" = "refs/heads/{top-bases}" ]; then
2377 topbases="heads/{top-bases}"
2378 topbasesrx="heads/[{]top-bases[}]"
2379 oldbases="top-bases"
2380 else
2381 # default is still top-bases for now
2382 topbases="top-bases"
2383 topbasesrx="top-bases"
2384 oldbases="heads/{top-bases}"
2386 # MUST NOT be exported
2387 unset_ rc activebases tg_topases_set
2388 tg_topbases_set=1
2389 return 0
2392 # $1 is remote name to check
2393 # $2 is optional variable name to set to result of check
2394 # $3 is optional command name to use in message (defaults to $cmd)
2395 # Fatal error if remote has schizophrenic top-bases
2396 # No error (and $2, if provided, will be set to empty) if remote has no top-bases at all
2397 check_remote_topbases()
2399 [ -n "$1" ] || die "programmer error: check_remote_topbases called with no remote argument"
2400 _crrc=0 _crremotebases=
2401 _crremotebases="$(
2402 git for-each-ref --format='%(refname)' "refs/remotes/$1" 2>/dev/null |
2403 run_awk_ref_prefixes -n -- "refs/remotes/$1/{top-bases}" "refs/remotes/$1/top-bases" "refs/remotes/$1")" ||
2404 _crrc=$?
2405 if [ "$_crrc" = "65" ]; then
2406 err "remote \"$1\" has top-bases in both locations:"
2407 err " refs/remotes/$1/{top-bases}/..."
2408 err " refs/remotes/$1/top-bases/..."
2409 err "set \"topgit.top-bases\" to \"heads\" for the first, preferred location"
2410 err "or set \"topgit.top-bases\" to \"refs\" for the second, old location"
2411 err "(the \"-c topgit.top-bases=<val>\" option can be used for this)"
2412 err "then re-run the tg ${3:-$cmd} command"
2413 err "(the tg migrate-bases command can also help with this problem)"
2414 die "schizophrenic remote \"$1\" requires topgit.top-bases setting"
2416 [ "$_crrc" != "66" ] || _crremotebases= # just to be sure
2417 [ -z "$2" ] || eval "$2="'"$_crremotebases"'
2418 unset _crrc _crremotebases
2419 return 0
2422 # init_reflog "ref"
2423 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
2424 # an empty log file to exist so that ref changes will be logged
2425 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
2426 # However, if "$1" is "refs/tgstash" then always make the reflog
2427 # The only ref not under refs/ that Git will write a reflog for is HEAD;
2428 # no matter what, it will NOT update a reflog for any other bare refs so
2429 # just quietly succeed when passed TG_STASH without doing anything.
2430 init_reflog()
2432 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
2433 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
2434 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
2435 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
2436 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
2439 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
2440 # a symbolic link. The directory part must exist, but the basename need not.
2441 v_get_abs_path()
2443 [ -n "$1" ] && [ -n "$2" ] || return 1
2444 set -- "$1" "$2" "${2%/}"
2445 case "$3" in
2446 */*) set -- "$1" "$2" "${3%/*}";;
2447 * ) set -- "$1" "$2" ".";;
2448 esac
2449 case "$2" in */)
2450 set -- "$1" "${2%/}" "$3" "/"
2451 esac
2452 [ -d "$3" ] || return 1
2453 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
2456 ## Startup
2458 : "${TG_INST_CMDDIR:=@cmddir@}"
2459 : "${TG_INST_SHAREDIR:=@sharedir@}"
2460 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
2462 [ -d "$TG_INST_CMDDIR" ] ||
2463 die "No command directory: '$TG_INST_CMDDIR'"
2465 ## Include awk scripts and their utility functions (separated for easier debugging)
2467 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
2468 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
2469 . "$TG_INST_CMDDIR/tg--awksome"
2471 if [ -n "$tg__include" ]; then
2473 # We were sourced from another script for our utility functions;
2474 # this is set by hooks. Skip the rest of the file. A simple return doesn't
2475 # work as expected in every shell. See http://bugs.debian.org/516188
2477 # ensure setup happens
2479 initial_setup 1
2480 set_topbases 1
2481 noalt_setup
2483 else
2485 set -e
2487 tgbin="$0"
2488 tgdir="${tgbin%/}"
2489 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
2490 tgdir="${tgdir%/*}/"
2491 tgname="${tgbin##*/}"
2492 [ "$0" != "$tgname" ] || tgdir=""
2494 # If tg contains a '/' but does not start with one then replace it with an absolute path
2496 case "$0" in /*) ;; */*)
2497 tgdir="$(cd "${0%/*}" && pwd -P)/"
2498 tgbin="$tgdir$tgname"
2499 esac
2501 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
2502 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2504 tgdisplaydir="$tgdir"
2505 tgdisplay="$tgbin"
2506 tgdisplayac="$tgdisplay"
2508 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2509 _tgabs="$_tgnameabs" &&
2510 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2511 [ "$_tgabs" = "$_tgnameabs" ]
2512 then
2513 tgdisplaydir=""
2514 tgdisplay="$tgname"
2515 tgdisplayac="$tgdisplay"
2517 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2518 unset_ _tgabs _tgnameabs
2520 tg() (
2521 TG_TMPDIR="$tg_tmp_dir" && export TG_TMPDIR &&
2522 exec "$tgbin" "$@"
2525 explicit_remote=
2526 explicit_dir=
2527 gitcdopt=
2528 noremote=
2529 forcepager=
2530 wayback=
2532 cmd=
2533 while :; do case "$1" in
2535 help|--help|-h)
2536 cmd=help
2537 shift
2538 break;;
2540 status|--status)
2541 cmd=status
2542 shift
2543 break;;
2545 --hooks-path)
2546 cmd=hooks-path
2547 shift
2548 break;;
2550 --exec-path)
2551 cmd=exec-path
2552 shift
2553 break;;
2555 --awk-path)
2556 cmd=awk-path
2557 shift
2558 break;;
2560 --top-bases)
2561 cmd=top-bases
2562 shift
2563 break;;
2565 --no-pager)
2566 forcepager=0
2567 shift;;
2569 --pager|-p)
2570 forcepager=1
2571 shift;;
2574 shift
2575 if [ -z "$1" ]; then
2576 echo "Option -r requires an argument." >&2
2577 do_help
2578 exit 1
2580 unset_ noremote
2581 base_remote="$1"
2582 explicit_remote="$base_remote"
2583 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2584 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2585 shift;;
2588 unset_ base_remote explicit_remote
2589 noremote=1
2590 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2591 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2592 shift;;
2595 shift
2596 if [ -z "$1" ]; then
2597 echo "Option -C requires an argument." >&2
2598 do_help
2599 exit 1
2601 cd "$1"
2602 unset_ GIT_DIR GIT_COMMON_DIR
2603 if [ -z "$explicit_dir" ]; then
2604 explicit_dir="$1"
2605 else
2606 explicit_dir="$PWD"
2608 gitcdopt=" -C \"$explicit_dir\""
2609 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2610 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2611 tgdisplayac="$tgdisplay"
2612 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2613 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2614 shift;;
2617 shift
2618 if [ -z "$1" ]; then
2619 echo "Option -c requires an argument." >&2
2620 do_help
2621 exit 1
2623 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2624 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2625 export GIT_CONFIG_PARAMETERS
2626 shift;;
2629 if [ -n "$wayback" ]; then
2630 echo "Option -w may be used at most once." >&2
2631 do_help
2632 exit 1
2634 shift
2635 if [ -z "$1" ]; then
2636 echo "Option -w requires an argument." >&2
2637 do_help
2638 exit 1
2640 wayback="$1"
2641 shift;;
2644 shift
2645 break;;
2648 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2649 do_help
2650 exit 1;;
2653 break;;
2655 esac; done
2656 if [ z"$forcepager" = z"0" ]; then
2657 GIT_PAGER_IN_USE=1 TG_PAGER_IN_USE=1 &&
2658 export GIT_PAGER_IN_USE TG_PAGER_IN_USE
2661 [ -n "$cmd" ] || [ $# -lt 1 ] || { cmd="$1"; shift; }
2663 ## Dispatch
2665 [ -n "$cmd" ] || { do_help; exit 1; }
2667 case "$cmd" in
2669 help)
2670 do_help "$@"
2671 exit 0;;
2673 status|st)
2674 unset_ base_remote
2675 basic_setup
2676 set_topbases
2677 do_status "$@"
2678 exit ${do_status_result:-0};;
2680 hooks-path)
2681 # Internal command
2682 echol "$TG_INST_HOOKSDIR";;
2684 exec-path)
2685 # Internal command
2686 echol "$TG_INST_CMDDIR";;
2688 awk-path)
2689 # Internal command
2690 echol "$TG_INST_CMDDIR/awk";;
2692 top-bases)
2693 # Maintenance command
2694 do_topbases_help=
2695 show_remote_topbases=
2696 case "$1" in
2697 --help|-h)
2698 do_topbases_help=0;;
2699 -r|--remote)
2700 if [ $# -eq 2 ] && [ -n "$2" ]; then
2701 # unadvertised, but make it work
2702 base_remote="$2"
2703 shift
2705 show_remote_topbases=1;;
2707 [ $# -eq 0 ] || do_topbases_help=1;;
2708 esac
2709 [ $# -le 1 ] || do_topbases_help=1
2710 if [ -n "$do_topbases_help" ]; then
2711 helpcmd='echo "Usage: ${tgname:-tg} [-r <remote>] --top-bases [-r]"'
2712 [ $do_topbases_help -eq 0 ] || helpcmd="$helpcmd >&2"
2713 eval "$helpcmd"
2714 exit $do_topbases_help
2716 git_dir=
2717 if git_dir="$(git rev-parse --git-dir 2>&1)"; then
2718 [ -z "$wayback" ] || activate_wayback_machine "$wayback"
2719 setup_git_dirs
2721 set_topbases
2722 if [ -n "$show_remote_topbases" ]; then
2723 basic_setup_remote
2724 [ -n "$base_remote" ] ||
2725 die "no remote location given. Either use -r <remote> option or set topgit.remote"
2726 rbases=
2727 [ -z "$topbases_implicit_default" ] ||
2728 check_remote_topbases "$base_remote" rbases "--top-bases"
2729 if [ -n "$rbases" ]; then
2730 echol "$rbases"
2731 else
2732 echol "refs/remotes/$base_remote/${topbases#heads/}"
2734 else
2735 echol "refs/$topbases"
2736 fi;;
2739 isutil=
2740 case "$cmd" in index-merge-one-file)
2741 isutil="-"
2742 esac
2743 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2744 looplevel="$TG_ALIAS_DEPTH"
2745 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2746 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2747 looplevel=0
2748 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2749 [ -n "$tgalias" ] || {
2750 echo "Unknown subcommand: $cmd" >&2
2751 do_help
2752 exit 1
2754 looplevel=$(( $looplevel + 1 ))
2755 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2756 TG_ALIAS_DEPTH="$looplevel"
2757 export TG_ALIAS_DEPTH
2758 if [ "!${tgalias#?}" = "$tgalias" ]; then
2759 [ -z "$wayback" ] ||
2760 die "-w is not allowed before an '!' alias command"
2761 unset_ GIT_PREFIX
2762 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2763 GIT_PREFIX="$pfx"
2764 export GIT_PREFIX
2766 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2767 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2768 else
2769 eval 'exec "$tgbin"' "${wayback:+-w \"\$wayback\"}" "$tgalias" '"$@"'
2771 die "alias execution failed for: $tgalias"
2773 unset_ TG_ALIAS_DEPTH
2775 showing_help=
2776 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2777 showing_help=1
2780 nomergesetup="$showing_help"
2781 case "$cmd" in base|contains|export|files|info|log|mail|next|patch|prev|rebase|revert|shell|summary|tag)
2782 # avoid merge setup where not necessary
2784 nomergesetup=1
2785 esac
2787 if [ -n "$wayback" ] && [ -z "$showing_help" ]; then
2788 [ -n "$nomergesetup" ] ||
2789 die "the wayback machine cannot be used with the \"$cmd\" subcommand"
2790 if [ "$cmd" = "shell" ]; then
2791 # this is ugly; `tg shell` should handle this but it's too
2792 # late there so we have to do it here
2793 wayback_dir=
2794 case "$1" in
2795 "--directory="?*)
2796 wayback_dir="${1#--directory=}" && shift;;
2797 "--directory=")
2798 die "--directory requires an argument";;
2799 "--directory")
2800 [ $# -ge 2 ] || die "--directory requires an argument"
2801 wayback_dir="$2" && shift 2;;
2802 esac
2803 activate_wayback_machine "$wayback" 1 "$wayback_dir"
2804 else
2805 _fullwb=
2806 # export might drop out into a shell for conflict resolution
2807 [ "$cmd" != "export" ] || _fullwb=2
2808 activate_wayback_machine "$wayback" "$_fullwb"
2809 fi ||
2810 die "failed to set the wayback machine to target \"$wayback\""
2813 [ -n "$showing_help" ] || initial_setup
2814 [ -z "$noremote" ] || unset_ base_remote
2816 if [ -z "$nomergesetup" ]; then
2817 # make sure merging the .top* files will always behave sanely
2819 setup_ours
2820 setup_hook "pre-commit"
2823 # everything but rebase needs topbases set
2824 carefully="$showing_help"
2825 [ "$cmd" != "migrate-bases" ] || carefully=1
2826 [ "$cmd" = "rebase" ] || set_topbases $carefully
2828 _use_ref_cache=
2829 tg_read_only=1
2830 _suppress_alt=
2831 case "$cmd$showing_help" in
2832 contains|info|summary|tag)
2833 _use_ref_cache=1;;
2834 "export")
2835 _use_ref_cache=1
2836 _suppress_alt=1;;
2837 annihilate|create|delete|depend|import|update)
2838 tg_read_only=
2839 _suppress_alt=1;;
2840 esac
2841 [ -z "$_suppress_alt" ] || noalt_setup
2842 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2844 fullcmd="${tgname:-tg} $cmd $*"
2845 if [ z"$forcepager" = z"1" ]; then
2846 page '. "$TG_INST_CMDDIR"/tg-$isutil$cmd' "$@"
2847 else
2848 . "$TG_INST_CMDDIR"/tg-$isutil$cmd
2849 fi;;
2850 esac