tg.sh: fully enable caching as designed
[topgit/pro.git] / tg.sh
blob93d21a9627b415453ec7d34413c3498f959e3c66
1 #!/bin/sh
2 # TopGit - A different patch queue manager
3 # Copyright (C) 2008 Petr Baudis <pasky@suse.cz>
4 # Copyright (C) 2014-2017 Kyle J. McKay <mackyle@gmail.com>
5 # All rights reserved.
6 # GPLv2
8 TG_VERSION=0.19.8
10 # Update in Makefile if you add any code that requires a newer version of git
11 GIT_MINIMUM_VERSION="@mingitver@"
13 ## SHA-1 pattern
15 octet='[0-9a-f][0-9a-f]'
16 octet4="$octet$octet$octet$octet"
17 octet19="$octet4$octet4$octet4$octet4$octet$octet$octet"
18 octet20="$octet4$octet4$octet4$octet4$octet4"
19 nullsha="0000000000000000000000000000000000000000" # :|git mktree|tr 0-9a-f 0
20 mtblob="e69de29bb2d1d6434b8b29ae775ad8c2e48c5391" # :|git hash-object --stdin -w
21 tab=' '
22 lf='
25 ## Auxiliary functions
27 # some ridiculous sh implementations require 'trap ... EXIT' to be executed
28 # OUTSIDE ALL FUNCTIONS to work in a sane fashion. Always trap it and eval
29 # "${TRAPEXIT_:-exit}" as a substitute.
30 trapexit_()
32 EXITCODE_=${1:-$?}
33 trap - EXIT
34 eval "${TRAPEXIT_:-exit $EXITCODE_}"
35 exit $EXITCODE_
37 trap 'trapexit_ $?' EXIT
39 # unset that ignores error code that shouldn't be produced according to POSIX
40 unset_()
42 { unset "$@"; } >/dev/null 2>&1 || :
45 # Preserves current $? value while triggering a non-zero set -e exit if active
46 # This works even for shells that sometimes fail to correctly trigger a -e exit
47 check_exit_code()
49 return $?
52 # This is the POSIX equivalent of which
53 cmd_path()
55 { "unset" -f command unset unalias "$1"; } >/dev/null 2>&1 || :
56 { "unalias" -a || unalias -m "*"; } >/dev/null 2>&1 || :
57 command -v "$1"
60 # helper for wrappers
61 # note deliberate use of '(' ... ')' rather than '{' ... '}'
62 exec_lc_all_c()
64 { "unset" -f "$1" || :; } >/dev/null 2>&1 &&
65 shift &&
66 LC_ALL="C" &&
67 export LC_ALL &&
68 exec "$@"
71 # These tools work better for us with LC_ALL=C and by using these little
72 # convenience functions LC_ALL=C does not have to appear in the code but
73 # any Git translations will still appear for Git commands
74 awk() { exec_lc_all_c awk @AWK_PATH@ "$@"; }
75 cat() { exec_lc_all_c cat cat "$@"; }
76 cut() { exec_lc_all_c cut cut "$@"; }
77 find() { exec_lc_all_c find find "$@"; }
78 grep() { exec_lc_all_c grep grep "$@"; }
79 join() { exec_lc_all_c join join "$@"; }
80 paste() { exec_lc_all_c paste paste "$@"; }
81 sed() { exec_lc_all_c sed sed "$@"; }
82 sort() { exec_lc_all_c sort sort "$@"; }
83 tr() { exec_lc_all_c tr tr "$@"; }
84 wc() { exec_lc_all_c wc wc "$@"; }
85 xargs() { exec_lc_all_c xargs xargs "$@"; }
87 # Output arguments without any possible interpretation
88 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
89 echol()
91 printf '%s\n' "$*"
94 info()
96 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
99 warn()
101 info "warning: $*" >&2
104 err()
106 info "error: $*" >&2
109 fatal()
111 info "fatal: $*" >&2
114 die()
116 fatal "$@"
117 exit 1
120 # shift off first arg then return "$*" properly quoted in single-quotes
121 # if $1 was '' output goes to stdout otherwise it's assigned to $1
122 # the final \n, if any, is omitted from the result but any others are included
123 v_quotearg()
125 _quotearg_v="$1"
126 shift
127 set -- "$_quotearg_v" \
128 "sed \"s/'/'\\\\\\''/g;1s/^/'/;\\\$s/\\\$/'/;s/'''/'/g;1s/^''\\(.\\)/\\1/\"" "$*"
129 unset_ _quotearg_v
130 if [ -z "$3" ]; then
131 if [ -z "$1" ]; then
132 echo "''"
133 else
134 eval "$1=\"''\""
136 else
137 if [ -z "$1" ]; then
138 printf "%s$4" "$3" | eval "$2"
139 else
140 eval "$1="'"$(printf "%s$4" "$3" | eval "$2")"'
145 # same as v_quotearg except there's no extra $1 so output always goes to stdout
146 quotearg()
148 v_quotearg '' "$@"
151 vcmp()
153 # Compare $1 to $3 each of which must match ^[^0-9]*\d*(\.\d*)*.*$
154 # where only the "\d*" parts in the regex participate in the comparison
155 # Since EVERY string matches that regex this function is easy to use
156 # An empty string ('') for $1 or $3 or any "\d*" part is treated as 0
157 # $2 is a compare op '<', '<=', '=', '==', '!=', '>=', '>'
158 # Return code is 0 for true, 1 for false (or unknown compare op)
159 # There is NO difference in behavior between '=' and '=='
160 # Note that "vcmp 1.8 == 1.8.0.0.0.0" correctly returns 0
161 set -- "$1" "$2" "$3" "${1%%[0-9]*}" "${3%%[0-9]*}"
162 set -- "${1#"$4"}" "$2" "${3#"$5"}"
163 set -- "${1%%[!0-9.]*}" "$2" "${3%%[!0-9.]*}"
164 while
165 vcmp_a_="${1%%.*}"
166 vcmp_b_="${3%%.*}"
167 [ "z$vcmp_a_" != "z" -o "z$vcmp_b_" != "z" ]
169 if [ "${vcmp_a_:-0}" -lt "${vcmp_b_:-0}" ]; then
170 unset_ vcmp_a_ vcmp_b_
171 case "$2" in "<"|"<="|"!=") return 0; esac
172 return 1
173 elif [ "${vcmp_a_:-0}" -gt "${vcmp_b_:-0}" ]; then
174 unset_ vcmp_a_ vcmp_b_
175 case "$2" in ">"|">="|"!=") return 0; esac
176 return 1;
178 vcmp_a_="${1#$vcmp_a_}"
179 vcmp_b_="${3#$vcmp_b_}"
180 set -- "${vcmp_a_#.}" "$2" "${vcmp_b_#.}"
181 done
182 unset_ vcmp_a_ vcmp_b_
183 case "$2" in "="|"=="|"<="|">=") return 0; esac
184 return 1
187 precheck() {
188 if ! git_version="$(git version)"; then
189 die "'git version' failed"
191 case "$git_version" in [Gg]"it version "*);;*)
192 die "'git version' output does not start with 'git version '"
193 esac
195 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
196 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
199 case "$1" in version|--version|-V)
200 echo "TopGit version $TG_VERSION"
201 exit 0
202 esac
204 [ $# -eq 1 ] && [ "$1" = "--make-empty-blob" ] || precheck
205 [ $# -ne 1 ] || [ "$1" != "precheck" ] || exit 0
207 cat_depsmsg_internal()
209 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
210 if [ -s "$tg_cache_dir/refs/heads/$1/.$2" ]; then
211 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
212 _line=
213 while IFS= read -r _line || [ -n "$_line" ]; do
214 printf '%s\n' "$_line"
215 done
216 return 0
217 fi <"$tg_cache_dir/refs/heads/$1/.$2"
219 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null || :
220 if [ -d "$tg_cache_dir/refs/heads/$1" ]; then
221 printf '%s\n' "$_rev" >"$tg_cache_dir/refs/heads/$1/.$2"
222 _line=
223 git cat-file blob "$_rev:.$2" 2>/dev/null |
224 while IFS= read -r _line || [ -n "$_line" ]; do
225 printf '%s\n' "$_line" >&3
226 printf '%s\n' "$_line"
227 done 3>>"$tg_cache_dir/refs/heads/$1/.$2"
228 else
229 git cat-file blob "$_rev:.$2" 2>/dev/null
233 # cat_deps BRANCHNAME
234 # Caches result
235 cat_deps()
237 cat_depsmsg_internal "$1" topdeps
240 # cat_msg BRANCHNAME
241 # Caches result
242 cat_msg()
244 cat_depsmsg_internal "$1" topmsg
247 # cat_file TOPIC:PATH [FROM]
248 # cat the file PATH from branch TOPIC when FROM is empty.
249 # FROM can be -i or -w, than the file will be from the index or worktree,
250 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
251 cat_file()
253 path="$1"
254 case "$2" in
256 cat "$root_dir/${path#*:}"
259 # ':file' means cat from index
260 git cat-file blob ":${path#*:}" 2>/dev/null
263 case "$path" in
264 refs/heads/*:.topdeps)
265 _temp="${path%:.topdeps}"
266 cat_deps "${_temp#refs/heads/}"
268 refs/heads/*:.topmsg)
269 _temp="${path%:.topmsg}"
270 cat_msg "${_temp#refs/heads/}"
273 git cat-file blob "$path" 2>/dev/null
275 esac
278 die "Wrong argument to cat_file: '$2'"
280 esac
283 # if use_alt_temp_odb and tg_use_alt_odb are true try to write the object(s)
284 # into the temporary alt odb area instead of the usual location
285 git_temp_alt_odb_cmd()
287 if [ -n "$use_alt_temp_odb" ] && [ -n "$tg_use_alt_odb" ] &&
288 [ -n "$TG_OBJECT_DIRECTORY" ] &&
289 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
291 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
292 GIT_OBJECT_DIRECTORY="$TG_OBJECT_DIRECTORY"
293 unset_ TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES
294 export GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
295 git "$@"
297 else
298 git "$@"
302 git_write_tree() { git_temp_alt_odb_cmd write-tree "$@"; }
303 git_mktree() { git_temp_alt_odb_cmd mktree "$@"; }
305 make_mtblob() {
306 use_alt_temp_odb=1
307 tg_use_alt_odb=1
308 git_temp_alt_odb_cmd hash-object -t blob -w --stdin </dev/null >/dev/null 2>&1
310 # short-circuit this for speed
311 [ $# -eq 1 ] && [ "$1" = "--make-empty-blob" ] && { make_mtblob || :; exit 0; }
313 # get tree for the committed topic
314 get_tree_()
316 echo "refs/heads/$1"
319 # get tree for the base
320 get_tree_b()
322 echo "refs/$topbases/$1"
325 # get tree for the index
326 get_tree_i()
328 git_write_tree
331 # get tree for the worktree
332 get_tree_w()
334 i_tree=$(git_write_tree)
336 # the file for --index-output needs to sit next to the
337 # current index file
338 cd "$root_dir"
339 : ${GIT_INDEX_FILE:="$git_dir/index"}
340 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
341 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
342 GIT_INDEX_FILE="$TMP_INDEX" &&
343 export GIT_INDEX_FILE &&
344 git diff --name-only -z HEAD |
345 git update-index -z --add --remove --stdin &&
346 git_write_tree &&
347 rm -f "$TMP_INDEX"
351 # get tree for arbitrary ref
352 get_tree_r()
354 echo "$1"
357 # strip_ref "$(git symbolic-ref HEAD)"
358 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
359 strip_ref()
361 case "$1" in
362 refs/"$topbases"/*)
363 echol "${1#refs/$topbases/}"
365 refs/heads/*)
366 echol "${1#refs/heads/}"
369 echol "$1"
370 esac
373 # pretty_tree [-t] NAME [-b | -i | -w | -r]
374 # Output tree ID of a cleaned-up tree without tg's artifacts.
375 # NAME will be ignored for -i and -w, but needs to be present
376 # With -r NAME must be a full ref name to a treeish (it's used as-is)
377 # If -t is used the tree is written into the alternate temporary objects area
378 pretty_tree()
380 use_alt_temp_odb=
381 [ "$1" != "-t" ] || { shift; use_alt_temp_odb=1; }
382 name="$1"
383 source="${2#?}"
384 git ls-tree --full-tree "$(get_tree_$source "$name")" |
385 sed -ne '/ \.top.*$/!p' |
386 git_mktree
389 # return an empty-tree root commit -- date is either passed in or current
390 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
391 # An invalid secs causes the current date to be used, an invalid zone offset
392 # causes +0000 to be used
393 make_empty_commit()
395 # the empty tree is guaranteed to always be there even in a repo with
396 # zero objects, but for completeness we force it to exist as a real object
397 SECS=
398 read -r SECS ZONE JUNK <<-EOT || :
401 case "$SECS" in *[!0-9]*) SECS=; esac
402 if [ -z "$SECS" ]; then
403 MTDATE="$(date '+%s %z')"
404 else
405 case "$ZONE" in
406 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
408 [01][0-9][0-5][0-9])
409 ZONE="+$ZONE"
412 ZONE="+0000"
413 esac
414 MTDATE="$SECS $ZONE"
416 EMPTYID="- <-> $MTDATE"
417 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
418 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
419 git hash-object -t commit -w --stdin
422 # standard input is a diff
423 # standard output is the "+" lines with leading "+ " removed
424 # beware that old lines followed by the dreaded '\ No newline at end of file'
425 # will appear to be new lines if lines are added after them
426 # the git diff --ignore-space-at-eol option can be used to prevent this
427 diff_added_lines()
429 awk '
430 BEGIN { in_hunk = 0; }
431 /^@@ / { in_hunk = 1; }
432 /^\+/ { if (in_hunk == 1) printf("%s\n", substr($0, 2)); }
433 !/^\\ No newline at end of file/ &&
434 /^[^@ +-]/ { in_hunk = 0; }
438 # $1 is name of new branch to create locally if all of these are true:
439 # a) exists as a remote TopGit branch for "$base_remote"
440 # b) the branch "name" does not have any invalid characters in it
441 # c) neither of the two branch refs (branch or base) exist locally
442 # returns success only if a new local branch was created (and dumps message)
443 auto_create_local_remote()
445 case "$1" in ""|*[" $tab$lf~^:\\*?["]*|.*|*/.*|*.|*./|/*|*/|*//*) return 1; esac
446 [ -n "$base_remote" ] &&
447 git update-ref --stdin <<-EOT >/dev/null 2>&1 &&
448 verify refs/remotes/$base_remote/${topbases#heads/}/$1 refs/remotes/$base_remote/${topbases#heads/}/$1
449 verify refs/remotes/$base_remote/$1 refs/remotes/$base_remote/$1
450 create refs/$topbases/$1 refs/remotes/$base_remote/${topbases#heads/}/$1^0
451 create refs/heads/$1 refs/remotes/$base_remote/$1^0
453 { init_reflog "refs/$topbases/$1" || :; } &&
454 info "topic branch '$1' automatically set up from remote '$base_remote'"
457 # setup_hook NAME
458 setup_hook()
460 setup_git_dir_is_bare
461 [ -z "$git_dir_is_bare" ] || return 0
462 tgname="${0##*/}"
463 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
464 if [ -f "$git_hooks_dir/$1" ] && grep -Fq "$hook_call" "$git_hooks_dir/$1"; then
465 # Another job well done!
466 return
468 # Prepare incantation
469 hook_chain=
470 if [ -s "$git_hooks_dir/$1" -a -x "$git_hooks_dir/$1" ]; then
471 hook_call="$hook_call"' || exit $?'
472 if [ -L "$git_hooks_dir/$1" ] || ! sed -n 1p <"$git_hooks_dir/$1" | grep -Fqx "#!@SHELL_PATH@"; then
473 chain_num=
474 while [ -e "$git_hooks_dir/$1-chain$chain_num" ]; do
475 chain_num=$(( $chain_num + 1 ))
476 done
477 mv -f "$git_hooks_dir/$1" "$git_hooks_dir/$1-chain$chain_num"
478 hook_chain=1
480 else
481 hook_call="exec $hook_call"
482 [ -d "$git_hooks_dir" ] || mkdir -p "$git_hooks_dir" || :
484 # Don't call hook if tg is not installed
485 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
486 # Insert call into the hook
488 echol "#!@SHELL_PATH@"
489 echol "$hook_call"
490 if [ -n "$hook_chain" ]; then
491 echol "exec \"\$0-chain$chain_num\" \"\$@\""
492 else
493 [ ! -s "$git_hooks_dir/$1" ] || cat "$git_hooks_dir/$1"
495 } >"$git_hooks_dir/$1+"
496 chmod a+x "$git_hooks_dir/$1+"
497 mv "$git_hooks_dir/$1+" "$git_hooks_dir/$1"
500 # setup_ours (no arguments)
501 setup_ours()
503 setup_git_dir_is_bare
504 [ -z "$git_dir_is_bare" ] || return 0
505 if [ ! -s "$git_common_dir/info/attributes" ] || ! grep -q topmsg "$git_common_dir/info/attributes"; then
506 [ -d "$git_common_dir/info" ] || mkdir "$git_common_dir/info"
508 echo ".topmsg merge=ours"
509 echo ".topdeps merge=ours"
510 } >>"$git_common_dir/info/attributes"
512 if ! git config merge.ours.driver >/dev/null; then
513 git config merge.ours.name '"always keep ours" merge driver'
514 git config merge.ours.driver 'touch %A'
518 # measure_branch NAME [BASE] [EXTRAHEAD...]
519 measure_branch()
521 _bname="$1"; _base="$2"
522 shift; shift
523 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
524 # The caller should've verified $name is valid
525 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
526 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
527 if [ $_commits -ne 1 ]; then
528 _suffix="commits"
529 else
530 _suffix="commit"
532 echo "$_commits/$_nmcommits $_suffix"
535 # true if $1 is contained by (or the same as) $2
536 # this is never slower than merge-base --is-ancestor and is often slightly faster
537 contained_by()
539 [ "$(git rev-list --count --max-count=1 "$1" --not "$2" --)" = "0" ]
542 # branch_contains B1 B2
543 # Whether B1 is a superset of B2.
544 branch_contains()
546 _revb1="$(ref_exists_rev "$1")" || return 0
547 _revb2="$(ref_exists_rev "$2")" || return 0
548 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
549 if read _result _rev_matchb1 _rev_matchb2 &&
550 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
551 return $_result
552 fi <"$tg_cache_dir/$1/.bc/$2/.d"
554 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
555 _result=0
556 contained_by "$_revb2" "$_revb1" || _result=1
557 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
558 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
560 return $_result
563 create_ref_dirs()
565 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
566 mkdir -p "$tg_tmp_dir/cached/refs"
567 awk '{x = $1; sub(/^refs\//, "", x); if (x != "") print x}' <"$tg_ref_cache" | tr '\n' '\0' | {
568 cd "$tg_tmp_dir/cached/refs" &&
569 xargs -0 mkdir -p
571 awk -v p="$tg_tmp_dir/cached/" '
572 NF == 2 &&
573 $1 ~ /^refs\/./ &&
574 $2 ~ /^[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]+$/ {
575 fn = p $1 "/.ref"
576 print "0 " $2 >fn
577 close(fn)
579 ' <"$tg_ref_cache"
580 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
583 # If the first argument is non-empty, stores "1" there if this call created the cache
584 v_create_ref_cache()
586 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
587 _remotespec=
588 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
589 [ -z "$1" ] || eval "$1=1"
590 git for-each-ref --format='%(refname) %(objectname)' \
591 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
592 create_ref_dirs
595 remove_ref_cache()
597 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
598 >"$tg_ref_cache"
599 >"$tg_ref_cache_br"
600 >"$tg_ref_cache_rbr"
601 >"$tg_ref_cache_ann"
602 >"$tg_ref_cache_dep"
605 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
606 rev_parse()
608 rev_parse_code_=1
609 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
610 rev_parse_code_=0
611 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache" ||
612 rev_parse_code_=$?
614 [ $rev_parse_code_ -ne 0 ] && [ -z "$tg_ref_cache_only" ] || return $rev_parse_code_
615 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
618 # ref_exists_rev REF
619 # Whether REF is a valid ref name
620 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
621 # or, if $base_remote is set, refs/remotes/$base_remote/
622 # Caches result if $tg_read_only and outputs HASH on success
623 ref_exists_rev()
625 case "$1" in
626 refs/*)
628 $octet20)
629 printf '%s' "$1"
630 return;;
632 die "ref_exists_rev requires fully-qualified ref name (given: $1)"
633 esac
634 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
635 _result=
636 _result_rev=
637 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
638 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
639 _result=0
640 _result_rev="$(rev_parse "$1")" || _result=$?
641 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
642 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
643 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
644 printf '%s' "$_result_rev"
645 return $_result
648 # Same as ref_exists_rev but output is abbreviated hash
649 # Optional second argument defaults to --short but may be any --short=.../--no-short option
650 ref_exists_rev_short()
652 case "$1" in
653 refs/*)
655 $octet20)
658 die "ref_exists_rev_short requires fully-qualified ref name"
659 esac
660 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
661 _result=
662 _result_rev=
663 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
664 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
665 _result=0
666 _result_rev="$(rev_parse "$1")" || _result=$?
667 if [ $_result -eq 0 ]; then
668 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev^0" --)"
669 _result=$?
671 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
672 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
673 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
674 printf '%s' "$_result_rev"
675 return $_result
678 # ref_exists REF
679 # Whether REF is a valid ref name
680 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
681 # or, if $base_remote is set, refs/remotes/$base_remote/
682 # Caches result
683 ref_exists()
685 ref_exists_rev "$1" >/dev/null
688 # rev_parse_tree REF
689 # Runs git rev-parse REF^{tree}
690 # Caches result if $tg_read_only
691 rev_parse_tree()
693 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
694 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
695 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
696 printf '%s\n' "$_result"
697 return 0
699 return 1
701 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
702 if [ -d "$tg_tmp_dir/cached/$1" ]; then
703 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
704 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
705 printf '%s\n' "$_result"
706 return 0
708 return 1
710 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
713 # has_remote BRANCH
714 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
715 has_remote()
717 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
720 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
721 # If -z "$1" still set return code but do not return result
722 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
723 # refs/heads/... then ... will be verified instead.
724 # if "$3" = "-f" (for fail) then return an error rather than dying.
725 v_verify_topgit_branch()
727 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
728 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
729 [ -n "$_verifyname" -o "$3" = "-f" ] || die "HEAD is not a symbolic ref"
730 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
731 [ "$3" != "-f" ] || return 1
732 die "HEAD is not a symbolic ref to the refs/heads namespace"
733 esac
734 set -- "$1" "$_verifyname" "$3"
736 case "$2" in
737 refs/"$topbases"/*)
738 _verifyname="${2#refs/$topbases/}"
740 refs/heads/*)
741 _verifyname="${2#refs/heads/}"
744 _verifyname="$2"
746 esac
747 if ! ref_exists "refs/heads/$_verifyname"; then
748 [ "$3" != "-f" ] || return 1
749 die "no such branch: $_verifyname"
751 if ! ref_exists "refs/$topbases/$_verifyname"; then
752 [ "$3" != "-f" ] || return 1
753 die "not a TopGit-controlled branch: $_verifyname"
755 [ -z "$1" ] || eval "$1="'"$_verifyname"'
758 # Return the verified TopGit branch name or die with an error.
759 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
760 # refs/heads/... then ... will be verified instead.
761 # if "$2" = "-f" (for fail) then return an error rather than dying.
762 verify_topgit_branch()
764 v_verify_topgit_branch _verifyname "$@" || return
765 printf '%s' "$_verifyname"
768 # Caches result
769 # $1 = branch name (i.e. "t/foo/bar")
770 # $2 = optional result of rev-parse "refs/heads/$1"
771 # $3 = optional result of rev-parse "refs/$topbases/$1"
772 branch_annihilated()
774 _branch_name="$1"
775 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
776 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
778 _result=
779 _result_rev=
780 _result_rev_base=
781 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/refs/heads/$_branch_name/.ann"; } 2>/dev/null || :
782 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
784 # use the merge base in case the base is ahead.
785 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
787 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
788 _result=$?
789 [ -d "$tg_cache_dir/refs/heads/$_branch_name" ] || mkdir -p "$tg_cache_dir/refs/heads/$_branch_name" 2>/dev/null
790 [ ! -d "$tg_cache_dir/refs/heads/$_branch_name" ] ||
791 echo $_result $_rev $_rev_base >"$tg_cache_dir/refs/heads/$_branch_name/.ann" 2>/dev/null || :
792 return $_result
795 non_annihilated_branches()
797 refscacheopt="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
798 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
799 refscacheopt="$refscacheopt"'-r="$tg_ref_cache" "refs/$topbases"'
801 eval run_awk_topgit_branches -n "$refscacheopt" '"refs/$topbases" "$@"'
804 # Make sure our tree is clean
805 # if optional "$1" given also verify that a checkout to "$1" would succeed
806 ensure_clean_tree()
808 check_status
809 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
810 git update-index --ignore-submodules --refresh ||
811 die "the working directory has uncommitted changes (see above) - first commit or reset them"
812 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
813 die "the index has uncommited changes"
814 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
815 die "git checkout \"$1\" would fail"
818 # Make sure .topdeps and .topmsg are "clean"
819 # They are considered "clean" if each is identical in worktree, index and HEAD
820 # With "-u" as the argument skip the HEAD check (-u => unborn)
821 # untracked .topdeps and/or .topmsg files are always considered "dirty" as well
822 # with -u them just existing constitutes "dirty"
823 ensure_clean_topfiles()
825 _dirtw=0
826 _dirti=0
827 _dirtu=0
828 _check="$(git diff-files --ignore-submodules --name-only -- :/.topdeps :/.topmsg)" &&
829 [ -z "$_check" ] || _dirtw=1
830 if [ "$1" != "-u" ]; then
831 _check="$(git diff-index --cached --ignore-submodules --name-only HEAD -- :/.topdeps :/.topmsg)" &&
832 [ -z "$_check" ] || _dirti=1
834 if [ "$_dirti$_dirtw" = "00" ]; then
835 v_get_show_cdup
836 if [ -e "${git_cdup_result}.topdeps" ] || [ -e "${git_cdup_result}.topmsg" ]; then
837 [ "$1" != "-u" ] &&
838 _check="$(git status --porcelain --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg)" &&
839 [ -z "$_check" ] || _dirtu=1
842 if [ "$_dirtu$_dirti$_dirtw" != "000" ]; then
843 git status --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg || :
844 case "$_dirtu$_dirti$_dirtw" in
845 001) die "the working directory has uncommitted changes (see above) - first commit or reset them";;
846 010) die "the index has uncommited changes (see above)";;
847 011) die "the working directory and index have uncommitted changes (see above) - first commit or reset them";;
848 100) die "the working directory has untracked files that would be overwritten (see above)";;
849 esac
853 # is_sha1 REF
854 # Whether REF is a SHA1 (compared to a symbolic name).
855 is_sha1()
857 case "$1" in $octet20) return 0;; esac
858 return 1
861 # navigate_deps <run_awk_topgit_navigate options and arguments>
862 # all options and arguments are passed through to run_awk_topgit_navigate
863 # except for a leading -td= option, if any, which is picked off for deps
864 # after arranging to feed it a suitable deps list
865 navigate_deps()
867 dogfer=
868 dorad=1
869 userc=
870 tmpdep=
871 ratd_opts="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
872 ratn_opts=
873 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
874 userc=1
875 tmprfs="$tg_ref_cache"
876 tmptgbr="$tg_ref_cache_br"
877 tmpann="$tg_ref_cache_ann"
878 tmpdep="$tg_ref_cache_dep"
879 [ -s "$tg_ref_cache" ] || dogfer=1
880 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
881 else
882 ratd_opts="${ratd_opts}-rmr"
883 ratn_opts="-rma -rmb"
884 tmprfs="$tg_tmp_dir/refs.$$"
885 tmpann="$tg_tmp_dir/ann.$$"
886 tmptgbr="$tg_tmp_dir/tgbr.$$"
887 dogfer=1
889 refpats="\"refs/heads\" \"refs/\$topbases\""
890 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
891 [ -z "$dogfer" ] ||
892 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
893 depscmd="run_awk_topgit_deps $ratd_opts"
894 case "$1" in -td=*)
895 userc=
896 depscmd="$depscmd $1"
897 shift
898 esac
899 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -s "refs/$topbases"'
900 if [ -n "$userc" ]; then
901 if [ -n "$dorad" ]; then
902 eval "$depscmd" >"$tmpdep"
904 depscmd='<"$tmpdep" '
905 else
906 depscmd="$depscmd |"
908 eval "$depscmd" run_awk_topgit_navigate '-a="$tmpann" -b="$tmptgbr"' "$ratn_opts" '"$@"'
911 # recurse_deps_internal NAME [BRANCHPATH...]
912 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
913 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
914 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
915 # (but missing and remotes are always "0")
916 # followed by a 0 for no excess visits or a positive number of excess visits
917 # then the branch name followed by its depedency chain (which might be empty)
918 # An output line might look like this:
919 # 0 1 1 0 t/foo/leaf t/foo/int t/stage
920 # If no_remotes is non-empty, exclude remotes
921 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
922 # If with_top_level is non-empty, include the top-level that's normally omitted
923 # any branch names in the space-separated recurse_deps_exclude variable
924 # are skipped (along with their dependencies)
925 recurse_deps_internal()
927 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
928 ratr_opts="${recurse_preorder:+-f} ${with_top_level:+-s}"
929 dogfer=
930 dorad=1
931 userc=
932 tmpdep=
933 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
934 userc=1
935 tmprfs="$tg_ref_cache"
936 tmptgbr="$tg_ref_cache_br"
937 tmpann="$tg_ref_cache_ann"
938 tmpdep="$tg_ref_cache_dep"
939 [ -s "$tg_ref_cache" ] || dogfer=1
940 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
941 else
942 ratr_opts="$ratr_opts -rmh -rma -rmb"
943 tmprfs="$tg_tmp_dir/refs.$$"
944 tmpann="$tg_tmp_dir/ann.$$"
945 tmptgbr="$tg_tmp_dir/tgbr.$$"
946 dogfer=1
948 refpats="\"refs/heads\" \"refs/\$topbases\""
949 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
950 tmptgrmtbr=
951 dorab=1
952 if [ -z "$no_remotes" ] && [ -n "$base_remote" ]; then
953 if [ -n "$userc" ]; then
954 tmptgrmtbr="$tg_ref_cache_rbr"
955 [ -n "$dogfer" ] || ! [ -s "$tmptgrmtbr" ] || dorab=
956 else
957 tmptgrmtbr="$tg_tmp_dir/tgrmtbr.$$"
958 ratr_opts="$ratr_opts -rmr"
960 ratr_opts="$ratr_opts -r=\"\$tmptgrmtbr\" -u=\":refs/remotes/\$base_remote/\${topbases#heads/}\""
962 [ -z "$dogfer" ] ||
963 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
964 if [ -n "$tmptgrmtbr" ] && [ -n "$dorab" ]; then
965 run_awk_topgit_branches -n -h="refs/remotes/$base_remote" -r="$tmprfs" \
966 "refs/remotes/$base_remote/${topbases#heads/}" >"$tmptgrmtbr"
968 depscmd="run_awk_topgit_deps -s${TG_DEBUG:+ -p=\"\$tg_ref_cache.pre\"}"
969 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" "refs/$topbases"'
970 if [ -n "$userc" ]; then
971 if [ -n "$dorad" ]; then
972 eval "$depscmd" >"$tmpdep"
974 depscmd='<"$tmpdep" '
975 else
976 depscmd="$depscmd |"
978 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
979 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
982 # do_eval CMD
983 # helper for recurse_deps so that a return statement executed inside CMD
984 # does not return from recurse_deps. This shouldn't be necessary, but it
985 # seems that it actually is.
986 do_eval()
988 eval "$@"
991 # becomes read-only for caching purposes
992 # assigns new value to tg_read_only
993 # become_cacheable/undo_become_cacheable calls may be nested
994 become_cacheable()
996 _old_tg_read_only="$tg_read_only"
997 if [ -z "$tg_read_only" ]; then
998 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
999 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1000 tg_read_only=1
1002 _my_ref_cache=
1003 v_create_ref_cache _my_ref_cache
1004 _my_ref_cache="${_my_ref_cache:+1}"
1005 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
1008 # restores tg_read_only and ref_cache to state before become_cacheable call
1009 # become_cacheable/undo_bocome_cacheable calls may be nested
1010 undo_become_cacheable()
1012 case "$tg_read_only" in
1013 "undo"[01]"-"*)
1014 _suffix="${tg_read_only#undo?-}"
1015 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
1016 tg_read_only="$_suffix"
1017 esac
1020 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
1021 become_non_cacheable()
1023 remove_ref_cache
1024 tg_read_only=
1025 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1026 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1029 # call this to make sure the current Git repository has an associated work tree
1030 ensure_work_tree()
1032 setup_git_dir_is_bare
1033 [ -n "$git_dir_is_bare" ] || return 0
1034 die "This operation must be run in a work tree"
1037 # call this to make sure Git will not complain about a missing user/email
1038 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
1039 ensure_ident_available()
1041 [ -z "$TG_IDENT_CHECKED" ] || return 0
1042 git var GIT_AUTHOR_IDENT >/dev/null &&
1043 git var GIT_COMMITTER_IDENT >/dev/null || exit
1044 TG_IDENT_CHECKED=1
1045 export TG_IDENT_CHECKED
1046 return 0
1049 # recurse_deps [-o=<options string>] CMD NAME [BRANCHPATH...]
1050 # Recursively eval CMD on all dependencies of NAME.
1051 # Dependencies are visited in topological order.
1052 # If <options string> is given, it's eval'd into the recurse_deps_internal
1053 # call just before the "--" that's passed just before NAME
1054 # CMD can refer to the following variables:
1056 # _ret starts as 0; CMD can change; will be final return result
1057 # _dep bare branch name or ":refs/remotes/..." for a remote
1058 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
1059 # _depchain 0+ space-sep branch names (_name first) form a path to top
1060 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
1061 # _dep_is_leaf boolean "1" if leaf; "" if not
1062 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
1063 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
1064 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
1065 # _dep_xvisits non-negative integer number of excess visits (often 0)
1067 # CMD may use a "return" statement without issue; its return value is ignored,
1068 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
1069 # will stop immediately and the value with the leading "-" stripped off will
1070 # be the final result code
1072 # CMD can refer to $_name for queried branch name,
1073 # $_dep for dependency name,
1074 # $_depchain for space-seperated branch backtrace,
1075 # $_dep_missing boolean to check whether $_dep is present
1076 # and the $_dep_is_tgish and $_dep_annihilated booleans.
1077 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
1078 # It can modify $_ret to affect the return value
1079 # of the whole function.
1080 # If recurse_deps() hits missing dependencies, it will append
1081 # them to space-separated $missing_deps list and skip them
1082 # after calling CMD with _dep_missing set.
1083 # remote dependencies are processed if no_remotes is unset.
1084 # any branch names in the space-separated recurse_deps_exclude variable
1085 # are skipped (along with their dependencies)
1087 # If no_remotes is non-empty, exclude remotes
1088 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1089 # If with_top_level is non-empty, include the top-level that's normally omitted
1090 # any branch names in the space-separated recurse_deps_exclude variable
1091 # are skipped (along with their dependencies)
1092 recurse_deps()
1094 _opts=
1095 case "$1" in -o=*) _opts="${1#-o=}"; shift; esac
1096 _cmd="$1"; shift
1098 _depsfile="$(get_temp tg-depsfile)"
1099 eval recurse_deps_internal "$_opts" -- '"$@"' >"$_depsfile" || :
1101 _ret=0
1102 while read _ismissing _istgish _isleaf _dep_xvisits _dep _name _deppath; do
1103 _depchain="$_name${_deppath:+ $_deppath}"
1104 _dep_is_tgish=
1105 [ "$_istgish" = "0" ] || _dep_is_tgish=1
1106 _dep_has_remote=
1107 [ "$_istgish" != "2" ] || _dep_has_remote=1
1108 _dep_missing=
1109 if [ "$_ismissing" != "0" ]; then
1110 _dep_missing=1
1111 case " $missing_deps " in *" $_dep "*);;*)
1112 missing_deps="${missing_deps:+$missing_deps }$_dep"
1113 esac
1115 _dep_annihilated=
1116 _dep_is_leaf=
1117 if [ "$_isleaf" = "1" ]; then
1118 _dep_is_leaf=1
1119 elif [ "$_isleaf" = "2" ]; then
1120 _dep_annihilated=1
1122 do_eval "$_cmd" || :
1123 if [ "${_ret#-}" != "$_ret" ]; then
1124 _ret="${_ret#-}"
1125 break
1127 done <"$_depsfile"
1128 rm -f "$_depsfile"
1129 return ${_ret:-0}
1132 # find_leaves NAME
1133 # output (one per line) the unique leaves of NAME
1134 # a leaf is either
1135 # 1) a non-tgish dependency
1136 # 2) the base of a tgish dependency with no non-annihilated dependencies
1137 # duplicates are suppressed (by commit rev) and remotes are always ignored
1138 # if a leaf has an exact tag match that will be output
1139 # note that recurse_deps_exclude IS honored for this operation
1140 find_leaves()
1142 no_remotes=1
1143 with_top_level=1
1144 recurse_preorder=
1145 seen_leaf_refs=
1146 seen_leaf_revs=
1147 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1148 [ "$_isleaf" = "1" ] && [ "$_ismissing" = "0" ] || continue
1149 if [ "$_istgish" != "0" ]; then
1150 fulldep="refs/$topbases/$_dep"
1151 else
1152 fulldep="refs/heads/$_dep"
1154 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1155 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1156 if fullrev="$(ref_exists_rev "$fulldep")"; then
1157 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1158 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1159 # See if Git knows it by another name
1160 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1161 echo "refs/tags/$tagname"
1162 else
1163 echo "$fulldep"
1165 esac
1167 esac
1168 done <<-EOT
1169 $(recurse_deps_internal -l -o=1 -- "$1")
1171 with_top_level=
1174 # branch_needs_update
1175 # This is a helper function for determining whether given branch
1176 # is up-to-date wrt. its dependencies. It expects input as if it
1177 # is called as a recurse_deps() helper.
1178 # In case the branch does need update, it will echo it together
1179 # with the branch backtrace on the output (see needs_update()
1180 # description for details) and set $_ret to non-zero.
1181 branch_needs_update()
1183 if [ -n "$_dep_missing" ]; then
1184 echo "! $_dep $_depchain"
1185 return 0
1188 if [ -n "$_dep_is_tgish" ]; then
1189 [ -z "$_dep_annihilated" ] || return 0
1191 if [ -n "$_dep_has_remote" ]; then
1192 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" || {
1193 echo ":refs/remotes/$base_remote/$_dep $_dep $_depchain"
1194 _ret=1
1197 # We want to sync with our base first and should output this before
1198 # the remote branch, but the order does not actually matter to tg-update
1199 # as it just recurses regardless, but it does matter for tg-info (which
1200 # treats out-of-date bases as though they were already merged in) so
1201 # we output the remote before the base.
1202 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1203 echo ": $_dep $_depchain"
1204 _ret=1
1205 return
1209 if [ -n "$_name" ]; then
1210 case "$_dep" in :*) _fulldep="${_dep#:}";; *) _fulldep="refs/heads/$_dep";; esac
1211 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1212 # Some new commits in _dep
1213 echo "$_dep $_depchain"
1214 _ret=1
1219 # needs_update NAME
1220 # This function is recursive; it outputs reverse path from NAME
1221 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1222 # inner paths first. Innermost name can be :refs/remotes/<remote>/<name>
1223 # if the head is not in sync with the <remote> branch <name>, ':' if
1224 # the head is not in sync with the base (in this order of priority)
1225 # or '!' if dependency is missing. Note that the remote branch, base
1226 # order is reversed from the order they will actually be updated in
1227 # order to accomodate tg info which treats out-of-date items that are
1228 # only in the base as already being in the head for status purposes.
1229 # It will also return non-zero status if NAME needs update (seems backwards
1230 # but think of it as non-zero status if any non-missing output lines produced)
1231 # If needs_update() hits missing dependencies, it will append
1232 # them to space-separated $missing_deps list and skip them.
1233 needs_update()
1235 recurse_deps branch_needs_update "$1"
1238 # append second arg to first arg variable gluing with space if first already set
1239 vplus()
1241 eval "$1=\"\${$1:+\$$1 }\$2\""
1244 # true if whitespace separated first var name list contains second arg
1245 # use `vcontains 3 "value" "some list"` for a literal list
1246 vcontains()
1248 eval case "\" \${$1} \"" in '*" $2 "*) return 0; esac; return 1'
1251 # if the $1 var does not already contain $2 it's appended
1252 vsetadd()
1254 vcontains "$1" "$2" || vplus "$1" "$2"
1257 # reset needs_update_check results to empty
1258 needs_update_check_clear()
1260 unset_ needs_update_processed needs_update_behind needs_update_ahead needs_update_partial
1263 # needs_update_check NAME...
1265 # A faster version of needs_update that always succeeds
1266 # No output and unsuitable for actually performing updates themselves
1267 # If any of NAME... are NOT up-to-date AND they were not already processed
1268 # return status always will be zero however a simple check of
1269 # needs_update_behind after the call will answer the:
1270 # "are any out of date?": test -n "$needs_update_behind"
1271 # "is <x> out of date?": vcontains needs_update_behind "<x>"
1273 # Note that results are cumulative and "no_remotes" is honored as well as other
1274 # variables that modify recurse_deps_internal behavior. See the preceding
1275 # function to reset the results to empty when accumulation should start over.
1277 # Unlike needs_update, the branch names are themselves also checked to see if
1278 # they are out-of-date with respect to their bases or remote branches (not just
1279 # their remote bases). However, this can muddy some status results so this
1280 # can be disabled by setting needs_update_check_no_self to a non-empty value.
1282 # Unlike needs_update, here the remote base check is handled together with the
1283 # remote head check so if one is modified the other is too in the same way.
1285 # Dependencies are normally considered "behind" if they need an update from
1286 # their base or remote but this can be suppressed by setting the
1287 # needs_update_check_no_same to a non-empty value. This will NOT prevent
1288 # parents of those dependencies from still being considered behind in such a
1289 # case even though the dependency itself will not be. Note that setting
1290 # needs_update_check_no_same also implies needs_update_check_no_self.
1292 # The following whitespace-separated lists are updated with the results:
1294 # The "no_remotes" setting is obeyed but remote names themselves will never
1295 # appear in any of the lists
1297 # needs_update_processed
1298 # The branch names in here have been processed and will be skipped
1300 # needs_update_behind
1301 # Any branch named in here needs an update from one or more of its
1302 # direct or indirect dependencies (i.e. it's "out-of-date")
1304 # needs_update_ahead
1305 # Any branch named in here is NOT fully contained by at least one of
1306 # its dependents (i.e. it's a source of "out-of-date (aka dirty)"ness
1308 # needs_update_partial
1309 # Any branch names in here are either missing themselves or have one
1310 # or more detected missing dependencies (a completely missing remote
1311 # branch is never "detected")
1312 needs_update_check()
1314 # each head must be processed independently or else there will be
1315 # confusion about who's missing what and which branches actually are
1316 # out of date
1317 tmptgrdi="$tg_tmp_dir/tgrdi.$$"
1318 for nucname in "$@"; do
1319 ! vcontains needs_update_processed "$nucname" || continue
1320 # no need to fuss with recurse_deps, just use
1321 # recurse_deps_internal directly
1322 recurse_deps_internal -s -o=-1 "$nucname" >"$tmptgrdi"
1323 while read -r _rdi_m _rdi_t _rdi_l _rdi_v _rdi_node _rdi_parent _rdi_chain; do
1324 case "$_rdi_node" in ""|:*) continue; esac # empty or checked with remote
1325 vsetadd needs_update_processed "$_rdi_node"
1326 if [ "$_rdi_m" != "0" ]; then # missing
1327 vsetadd needs_update_partial "$_rdi_node"
1328 [ -z "$_rdi_parent" ] || vsetadd needs_update_partial "$_rdi_parent"
1329 continue
1331 [ "$_rdi_t$_rdi_l" != "12" ] || continue # always skip annihilated
1332 _rdi_dertee= # :)
1333 if [ -n "$_rdi_parent" ]; then # not a "self" line
1334 ! vcontains needs_update_partial "$_rdi_node" || vsetadd needs_update_partial "$_rdi_parent"
1335 ! vcontains needs_update_behind "$_rdi_node" || _rdi_dertee=2
1336 else
1337 [ -z "$needs_update_check_no_self$needs_update_check_no_same" ] || continue # skip self
1339 if [ -z "$_rdi_dertee" ]; then
1340 if [ "$_rdi_t" != "0" ]; then # tgish
1341 if branch_contains "refs/heads/$_rdi_node" "refs/$topbases/$_rdi_node"; then
1342 if [ "$_rdi_t" = "2" ]; then # will never be "2" when no_remotes is set
1343 branch_contains "refs/heads/$_rdi_node" "refs/remotes/$base_remote/$_rdi_node" &&
1344 branch_contains "refs/$topbases/$_rdi_node" "refs/remotes/$base_remote/${topbases#heads/}/$_rdi_node" ||
1345 _rdi_dertee=3
1347 else
1348 _rdi_dertee=3
1350 [ -z "$_rdi_dertee" ] || [ -n "$needs_update_check_no_same" ] || _rdi_dertee=1
1353 [ z"$_rdi_dertee" != z"1" ] || vsetadd needs_update_behind "$_rdi_node"
1354 [ -n "$_rdi_parent" ] || continue # self line
1355 if ! branch_contains "refs/$topbases/$_rdi_parent" "refs/heads/$_rdi_node"; then
1356 _rdi_dertee=1
1357 vsetadd needs_update_ahead "$_rdi_node"
1359 [ -z "$_rdi_dertee" ] || vsetadd needs_update_behind "$_rdi_parent"
1360 done <"$tmptgrdi"
1361 done
1364 # branch_empty NAME [-i | -w]
1365 branch_empty()
1367 if [ -z "$2" ]; then
1368 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1369 _result=
1370 _result_rev=
1371 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1372 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
1373 _result=0
1374 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1375 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1376 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1377 return $_result
1378 else
1379 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1383 v_get_tdmopt_internal()
1385 [ -n "$1" ] && [ -n "$3" ] || return 0
1386 [ "$2" = "-i" ] || [ "$2" = "-w" ] || return 0
1387 ensure_work_tree
1388 _optval=
1389 if v_verify_topgit_branch _tghead "HEAD" -f; then
1390 if [ "$2" = "-w" ] && [ -f "$root_dir/$3" ] && [ -r "$root_dir/$3" ]; then
1391 _opthash=
1392 if _opthash="$(git hash-object -w -t blob --stdin <"$root_dir/$3")" && [ -n "$_opthash" ]; then
1393 _optval="$4\"$_tghead:$_opthash\""
1395 elif [ "$2" = "-i" ]; then
1396 if _opthash="$(git rev-parse --quiet --verify ":0:$3" --)" && [ -n "$_opthash" ]; then
1397 _optval="$4\"$_tghead:$_opthash\""
1401 eval "$1="'"$_optval"'
1404 # set var $1 to the correct -td= option for use in an eval for $2 -i or -w mode
1405 v_get_tdopt() { v_get_tdmopt_internal "$1" "$2" ".topdeps" "-td="; }
1407 # set var $1 to the correct -tm= option for use in an eval for $2 -i or -w mode
1408 v_get_tmopt() { v_get_tdmopt_internal "$1" "$2" ".topmsg" "-tm="; }
1410 # checkout_symref_full [-f] FULLREF [SEED]
1411 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1412 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1413 # MUST be a committish which if present will be used instead of current FULLREF
1414 # (and FULLREF will be updated to it as well in that case)
1415 # Any merge state is always cleared by this function
1416 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1417 # instead of -m) but it will clear out any unmerged entries
1418 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1419 checkout_symref_full()
1421 _mode=-m
1422 _head="HEAD"
1423 if [ "$1" = "-f" ]; then
1424 _mode="--reset"
1425 _head=
1426 shift
1428 _ishash=
1429 case "$1" in
1430 refs/?*)
1432 $octet20)
1433 _ishash=1
1434 [ -z "$2" ] || [ "$1" = "$2" ] ||
1435 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1436 set -- HEAD "$1"
1439 die "programmer error: invalid checkout_symref_full \"$1\""
1441 esac
1442 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1443 die "invalid committish: \"${2:-$1}\""
1444 # Clear out any MERGE_HEAD kruft
1445 rm -f "$git_dir/MERGE_HEAD" || :
1446 # We have to do all the hard work ourselves :/
1447 # This is like git checkout -b "$1" "$2"
1448 # (or just git checkout "$1"),
1449 # but never creates a detached HEAD (unless $1 is a hash)
1450 git read-tree -u $_mode $_head "$_seedrev" &&
1452 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1453 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1454 } && {
1455 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1459 # switch_to_base NAME [SEED]
1460 switch_to_base()
1462 checkout_symref_full "refs/$topbases/$1" "$2"
1465 # run editor with arguments
1466 # the editor setting will be cached in $tg_editor (which is eval'd)
1467 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1468 # just in case, noalt_setup will be in effect while the editor is running
1469 run_editor()
1471 tg_editor="$GIT_EDITOR"
1472 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1474 noalt_setup
1475 eval "$tg_editor" '"$@"'
1479 # Show the help messages.
1480 do_help()
1482 _www=
1483 if [ "$1" = "-w" ]; then
1484 _www=1
1485 shift
1487 if [ -z "$1" ] ; then
1488 # This is currently invoked in all kinds of circumstances,
1489 # including when the user made a usage error. Should we end up
1490 # providing more than a short help message, then we should
1491 # differentiate.
1492 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1494 ## Build available commands list for help output
1496 cmds=
1497 sep=
1498 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1499 ! [ -r "$cmd" ] && continue
1500 # strip directory part and "tg-" prefix
1501 cmd="${cmd##*/}"
1502 cmd="${cmd#tg-}"
1503 [ "$cmd" != "migrate-bases" ] || continue
1504 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1505 cmds="$cmds$sep$cmd"
1506 sep="|"
1507 done
1509 echo "TopGit version $TG_VERSION - A different patch queue manager"
1510 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u]" \
1511 "[-c <name>=<val>] [--[no-]pager|-p] ($cmds) ..."
1512 echo " Or: $tgname help [-w] [<command>]"
1513 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1514 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1515 if [ -n "$_www" ]; then
1516 nohtml=
1517 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1518 echo "${0##*/}: missing html help file:" \
1519 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1520 nohtml=1
1522 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1523 echo "${0##*/}: missing html help file:" \
1524 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1525 nohtml=1
1527 if [ -n "$nohtml" ]; then
1528 echo "${0##*/}: use" \
1529 "\"${0##*/} help $1\" instead" 1>&2
1530 exit 1
1532 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1533 exit
1535 output()
1537 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1538 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1539 echo
1540 elif [ "$1" = "help" ]; then
1541 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1542 echo
1543 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1544 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1545 echo
1547 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1548 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1551 page output "$1"
1552 else
1553 echo "${0##*/}: no help for $1" 1>&2
1554 do_help
1555 exit 1
1559 check_status()
1561 git_state=
1562 git_remove=
1563 tg_state=
1564 tg_remove=
1565 tg_topmerge=
1566 setup_git_dir_is_bare
1567 [ -z "$git_dir_is_bare" ] || return 0
1569 if [ -e "$git_dir/MERGE_HEAD" ]; then
1570 git_state="merge"
1571 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1572 git_state="am"
1573 git_remove="$git_dir/rebase-apply"
1574 elif [ -e "$git_dir/rebase-apply" ]; then
1575 git_state="rebase"
1576 git_remove="$git_dir/rebase-apply"
1577 elif [ -e "$git_dir/rebase-merge" ]; then
1578 git_state="rebase"
1579 git_remove="$git_dir/rebase-merge"
1580 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1581 git_state="cherry-pick"
1582 elif [ -e "$git_dir/BISECT_LOG" ]; then
1583 git_state="bisect"
1584 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1585 git_state="revert"
1587 git_remove="${git_remove#./}"
1589 if [ -e "$git_dir/tg-update" ]; then
1590 tg_state="update"
1591 tg_remove="$git_dir/tg-update"
1592 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1594 tg_remove="${tg_remove#./}"
1597 # Show status information
1598 do_status()
1600 do_status_result=0
1601 do_status_verbose=
1602 do_status_help=
1603 abbrev=refs
1604 pfx=
1605 while [ $# -gt 0 ] && case "$1" in
1606 --help|-h)
1607 do_status_help=1
1608 break;;
1609 -vv)
1610 # kludge in this common bundling option
1611 abbrev=
1612 do_status_verbose=1
1613 pfx="## "
1615 --verbose|-v)
1616 [ -z "$do_status_verbose" ] || abbrev=
1617 do_status_verbose=1
1618 pfx="## "
1620 --exit-code)
1621 do_status_result=2
1624 die "unknown status argument: $1"
1626 esac; do shift; done
1627 if [ -n "$do_status_help" ]; then
1628 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1629 return
1631 check_status
1632 symref="$(git symbolic-ref --quiet HEAD)" || :
1633 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1634 if [ -n "$symref" ]; then
1635 uprefpart=
1636 if [ -n "$headrv" ]; then
1637 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1638 if [ -n "$upref" ]; then
1639 uprefpart=" ... ${upref#$abbrev/remotes/}"
1640 mbase="$(git merge-base HEAD "$upref")" || :
1641 ahead="$(git rev-list --count HEAD ${mbase:+--not $mbase})" || ahead=0
1642 behind="$(git rev-list --count "$upref" ${mbase:+--not $mbase})" || behind=0
1643 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1644 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1645 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1646 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1647 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1650 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1651 else
1652 echol "${pfx}HEAD -> ${headrv:-?}"
1654 if [ -n "$tg_state" ]; then
1655 extra=
1656 if [ "$tg_state" = "update" ]; then
1657 IFS= read -r uname <"$git_dir/tg-update/name" || :
1658 [ -z "$uname" ] ||
1659 extra="; currently updating branch '$uname'"
1661 echol "${pfx}tg $tg_state in progress$extra"
1662 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1663 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1664 cat "$git_dir/tg-update/fullcmd"
1665 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1666 if [ $bcnt -gt 1 ]; then
1667 pcnt=0
1668 ! [ -s "$git_dir/tg-update/processed" ] ||
1669 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1670 echo "${pfx}$pcnt of $bcnt branches updated so far"
1673 if [ "$tg_state" = "update" ]; then
1674 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1675 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1676 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1677 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1680 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1681 if [ "$git_state" = "merge" ]; then
1682 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1683 if [ $ucnt -gt 0 ]; then
1684 echo "${pfx}"'fix conflicts and then "git commit" the result'
1685 else
1686 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1689 if [ -z "$git_state" ]; then
1690 setup_git_dir_is_bare
1691 [ -z "$git_dir_is_bare" ] || return 0
1692 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository???
1693 gspcnt=0
1694 [ -z "$gsp" ] ||
1695 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1696 untr=
1697 if [ "$gspcnt" -eq 0 ]; then
1698 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1699 echo "${pfx}working directory is clean$untr"
1700 [ -n "$tg_state" ] || do_status_result=0
1701 else
1702 echo "${pfx}working directory is DIRTY"
1703 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1708 ## Pager stuff
1710 # isatty FD
1711 isatty()
1713 test -t $1
1716 # pass "diff" to get pager.diff
1717 # if pager.$1 is a boolean false returns cat
1718 # if set to true or unset fails
1719 # otherwise succeeds and returns the value
1720 get_pager()
1722 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1723 [ "$_x" != "true" ] || return 1
1724 echo "cat"
1725 return 0
1727 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1728 echol "$_x"
1729 return 0
1731 return 1
1734 # setup_pager
1735 # Set TG_PAGER to a valid executable
1736 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1737 # See also the following "page" function for ease of use
1738 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1739 # Preference is (same as Git):
1740 # 1. GIT_PAGER
1741 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1742 # 3. core.pager (only if set)
1743 # 4. PAGER
1744 # 5. git var GIT_PAGER
1745 # 6. less
1746 setup_pager()
1748 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1750 emptypager=
1751 if [ -z "$TG_PAGER_IN_USE" ]; then
1752 # TG_PAGER = GIT_PAGER | PAGER | less
1753 # NOTE: GIT_PAGER='' is significant
1754 if [ -n "${GIT_PAGER+set}" ]; then
1755 TG_PAGER="$GIT_PAGER"
1756 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1757 TG_PAGER="$_dp"
1758 elif _cp="$(git config core.pager 2>/dev/null)"; then
1759 TG_PAGER="$_cp"
1760 elif [ -n "${PAGER+set}" ]; then
1761 TG_PAGER="$PAGER"
1762 else
1763 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1764 [ "$_gp" != ":" ] || _gp=
1765 TG_PAGER="${_gp:-less}"
1767 if [ -z "$TG_PAGER" ]; then
1768 emptypager=1
1769 TG_PAGER=cat
1771 else
1772 emptypager=1
1773 TG_PAGER=cat
1776 # Set pager default environment variables
1777 # see pager.c:setup_pager
1778 if [ -z "${LESS+set}" ]; then
1779 LESS="-FRX"
1780 export LESS
1782 if [ -z "${LV+set}" ]; then
1783 LV="-c"
1784 export LV
1787 # this is needed so e.g. $(git diff) will still colorize it's output if
1788 # requested in ~/.gitconfig with color.diff=auto
1789 GIT_PAGER_IN_USE=1
1790 export GIT_PAGER_IN_USE
1792 # this is needed so we don't get nested pagers
1793 TG_PAGER_IN_USE=1
1794 export TG_PAGER_IN_USE
1797 # page eval_arg [arg ...]
1799 # Calls setup_pager then evals the first argument passing it all the rest
1800 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1801 # by setup_pager (in which case the output is left as-is).
1803 # To handle arbitrary paging duties, collect lines to be paged into a
1804 # function and then call page with the function name or perhaps func_name "$@".
1806 # If no arguments at all are passed in do nothing (return with success).
1807 page()
1809 [ $# -gt 0 ] || return 0
1810 setup_pager
1811 _evalarg="$1"; shift
1812 if [ -n "$emptypager" ]; then
1813 eval "$_evalarg" '"$@"'
1814 else
1815 { eval "$_evalarg" '"$@"';} | eval "$TG_PAGER"
1819 # get_temp NAME [-d]
1820 # creates a new temporary file (or directory with -d) in the global
1821 # temporary directory $tg_tmp_dir with pattern prefix NAME
1822 get_temp()
1824 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1827 # automatically called by strftime
1828 # does nothing if already setup
1829 # may be called explicitly if the first call would otherwise be in a subshell
1830 # so that the setup is only done once before subshells start being spawned
1831 setup_strftime()
1833 [ -z "$strftime_is_setup" ] || return 0
1835 # date option to format raw epoch seconds values
1836 daterawopt=
1837 _testes='951807788'
1838 _testdt='2000-02-29 07:03:08 UTC'
1839 _testfm='%Y-%m-%d %H:%M:%S %Z'
1840 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1841 daterawopt='-d@'
1842 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1843 daterawopt='-r'
1845 strftime_is_setup=1
1848 # $1 => strftime format string to use
1849 # $2 => raw timestamp as seconds since epoch
1850 # $3 => optional time zone string (empty/absent for local time zone)
1851 strftime()
1853 setup_strftime
1854 if [ -n "$daterawopt" ]; then
1855 if [ -n "$3" ]; then
1856 TZ="$3" date "$daterawopt$2" "+$1"
1857 else
1858 date "$daterawopt$2" "+$1"
1860 else
1861 if [ -n "$3" ]; then
1862 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1863 else
1864 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1869 got_cdup_result=
1870 git_cdup_result=
1871 v_get_show_cdup()
1873 if [ -z "$got_cdup_result" ]; then
1874 git_cdup_result="$(git rev-parse --show-cdup)"
1875 got_cdup_result=1
1877 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1880 setup_git_dir_is_bare()
1882 if [ -z "$git_dir_is_bare_setup" ]; then
1883 git_dir_is_bare="$(git rev-parse --is-bare-repository)"
1884 [ z"$git_dir_is_bare" = z"true" ] || git_dir_is_bare=
1885 git_dir_is_bare_setup=1
1889 setup_git_dirs()
1891 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1892 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1893 git_dir="$(cd "$git_dir" && pwd)"
1895 if [ -z "$git_common_dir" ]; then
1896 if vcmp "$git_version" '>=' "2.5"; then
1897 # rev-parse --git-common-dir is broken and may give
1898 # an incorrect result unless the current directory is
1899 # already set to the top level directory
1900 v_get_show_cdup
1901 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1902 else
1903 git_common_dir="$git_dir"
1906 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1907 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1908 git_hooks_dir="$git_common_dir/hooks"
1909 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1910 case "$gchp" in
1911 /[!/]*)
1912 git_hooks_dir="$gchp"
1915 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1917 esac
1918 unset_ gchp
1922 basic_setup_remote()
1924 if [ -z "$base_remote" ]; then
1925 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
1926 base_remote="$TG_EXPLICIT_REMOTE"
1927 else
1928 base_remote="$(git config topgit.remote 2>/dev/null)" || :
1933 basic_setup()
1935 setup_git_dirs $1
1936 basic_setup_remote
1937 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1938 tgnosequester=
1939 [ "$tgsequester" != "false" ] || tgnosequester=1
1940 unset_ tgsequester
1942 # catch errors if topbases is used without being set
1943 unset_ tg_topbases_set
1944 topbases="programmer*:error"
1945 topbasesrx="programmer*:error}"
1946 oldbases="$topbases"
1949 ## Initial setup
1950 initial_setup()
1952 # suppress the merge log editor feature since git 1.7.10
1954 GIT_MERGE_AUTOEDIT=no
1955 export GIT_MERGE_AUTOEDIT
1957 basic_setup $1
1958 iowopt=
1959 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
1960 gcfbopt=
1961 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
1962 auhopt=
1963 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1964 v_get_show_cdup root_dir
1965 root_dir="${root_dir:-.}"
1966 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1967 [ "$logrefupdates" = "true" ] || logrefupdates=
1969 # make sure root_dir doesn't end with a trailing slash.
1971 root_dir="${root_dir%/}"
1973 # create global temporary directories, inside GIT_DIR
1975 if [ -n "$TG_TMPDIR" ] && [ -d "$TG_TMPDIR" ] && [ -w "$TG_TMPDIR" ] &&
1976 { >"$TG_TMPDIR/.check"; } >/dev/null 2>&1; then
1977 tg_tmp_dir="$TG_TMPDIR"
1978 else
1979 tg_tmp_dir=
1980 TRAPEXIT_='${TG_DEBUG:+echo} rm -rf "$tg_tmp_dir" >&2'
1981 trap 'trapexit_ 129' HUP
1982 trap 'trapexit_ 130' INT
1983 trap 'trapexit_ 131' QUIT
1984 trap 'trapexit_ 134' ABRT
1985 trap 'trapexit_ 141' PIPE
1986 trap 'trapexit_ 143' TERM
1987 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1988 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1989 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1990 [ -z "$tg_tmp_dir" ] || tg_tmp_dir="$(cd "$tg_tmp_dir" && pwd -P)"
1992 unset_ TG_TMPDIR
1993 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1994 tg_ref_cache_br="$tg_ref_cache.br"
1995 tg_ref_cache_rbr="$tg_ref_cache.rbr"
1996 tg_ref_cache_ann="$tg_ref_cache.ann"
1997 tg_ref_cache_dep="$tg_ref_cache.dep"
1998 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_ref_cache"; } >/dev/null 2>&1 ||
1999 die "could not create a writable temporary directory"
2001 # make sure global cache directory exists inside GIT_DIR or $tg_tmp_dir
2003 user_id_no="$(id -u)" || :
2004 : "${user_id_no:=_99_}"
2005 tg_cache_dir="$git_common_dir/tg-cache"
2006 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2007 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
2008 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2009 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2010 if [ -z "$tg_cache_dir" ]; then
2011 tg_cache_dir="$tg_tmp_dir/tg-cache"
2012 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2013 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2015 [ -n "$tg_cache_dir" ] ||
2016 die "could not create a writable tg-cache directory (even a temporary one)"
2018 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
2019 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
2020 # so we avoid it if possible and require v2.11.1 to do it at all
2021 # otherwise just don't make an alternates temporary store in that case;
2022 # it's okay to not have one; everything will still work; the nicety of
2023 # making the temporary tree objects vanish when tg exits just won't
2024 # happen in that case but nothing will break also be sure to reuse
2025 # the parent's if we've been recursively invoked and it's for the
2026 # same repository we were invoked on
2028 tg_use_alt_odb=1
2029 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
2030 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] || tg_use_alt_odb=
2031 _fulltmpdir=
2032 [ -z "$tg_use_alt_odb" ] || _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
2033 case "$_fulltmpdir" in *[";:"]*|'"'*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
2034 _fullodbdir=
2035 [ -z "$tg_use_alt_odb" ] || _fullodbdir="$(cd "$_odbdir" && pwd -P)"
2036 if [ -n "$tg_use_alt_odb" ] && [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
2037 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
2038 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
2039 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
2040 tg_use_alt_odb=2
2043 if [ "$tg_use_alt_odb" = "1" ]; then
2044 # create an alternate objects database to keep the ephemeral objects in
2045 mkdir -p "$tg_tmp_dir/objects/info"
2046 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
2047 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
2048 case "$TG_OBJECT_DIRECTORY" in
2049 *[";:"]*|'"'*)
2050 # surround in "..." and backslash-escape internal '"' and '\\'
2051 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
2052 sed 's/\([""\\]\)/\\\1/g')\""
2055 _altodbdq="$TG_OBJECT_DIRECTORY"
2057 esac
2058 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2059 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2060 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2061 else
2062 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
2064 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
2065 if [ -n "$GIT_OBJECT_DIRECTORY" ]; then
2066 export GIT_OBJECT_DIRECTORY
2067 else
2068 unset_ GIT_OBJECT_DIRECTORY
2073 noalt_setup()
2075 if [ "${TG_PRESERVED_ALTERNATES+set}" = "set" ]; then
2076 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
2077 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2078 export GIT_ALTERNATE_OBJECT_DIRECTORIES
2079 else
2080 unset_ GIT_ALTERNATE_OBJECT_DIRECTORIES
2083 unset_ TG_TMPDIR TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES tg_use_alt_odb
2086 set_topbases()
2088 # refer to "top-bases" in a refname with $topbases
2090 [ -z "$tg_topbases_set" ] || return 0
2092 topbases_implicit_default=1
2093 # See if topgit.top-bases is set to heads or refs
2094 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
2095 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
2096 if [ -n "$1" ]; then
2097 # never die on the hook script
2098 unset_ tgtb
2099 else
2100 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
2103 if [ -n "$tgtb" ]; then
2104 case "$tgtb" in
2105 heads)
2106 topbases="heads/{top-bases}"
2107 topbasesrx="heads/[{]top-bases[}]"
2108 oldbases="top-bases";;
2109 refs)
2110 topbases="top-bases"
2111 topbasesrx="top-bases"
2112 oldbases="heads/{top-bases}";;
2113 esac
2114 # MUST NOT be exported
2115 unset_ tgtb tg_topbases_set topbases_implicit_default
2116 tg_topbases_set=1
2117 return 0
2119 unset_ tgtb
2121 # check heads and top-bases and see what state the current
2122 # repository is in. remotes are ignored.
2124 rc=0 activebases=
2125 activebases="$(
2126 git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null |
2127 run_awk_ref_prefixes ${1:+-e} -n -- "refs/heads/{top-bases}" "refs/top-bases" "refs/heads")" ||
2128 rc=$?
2129 if [ "$rc" = "65" ]; then
2130 # Complain and die
2131 err "repository contains existing TopGit branches"
2132 err "but some use refs/top-bases/... for the base"
2133 err "and some use refs/heads/{top-bases}/... for the base"
2134 err "with the latter being the new, preferred location"
2135 err "set \"topgit.top-bases\" to either \"heads\" to use"
2136 err "the new heads/{top-bases} location or \"refs\" to use"
2137 err "the old top-bases location."
2138 err "(the tg migrate-bases command can also resolve this issue)"
2139 die "schizophrenic repository requires topgit.top-bases setting"
2141 [ -z "$activebases" ] || unset_ topbases_implicit_default
2142 if [ "$activebases" = "refs/heads/{top-bases}" ]; then
2143 topbases="heads/{top-bases}"
2144 topbasesrx="heads/[{]top-bases[}]"
2145 oldbases="top-bases"
2146 else
2147 # default is still top-bases for now
2148 topbases="top-bases"
2149 topbasesrx="top-bases"
2150 oldbases="heads/{top-bases}"
2152 # MUST NOT be exported
2153 unset_ rc activebases tg_topases_set
2154 tg_topbases_set=1
2155 return 0
2158 # $1 is remote name to check
2159 # $2 is optional variable name to set to result of check
2160 # $3 is optional command name to use in message (defaults to $cmd)
2161 # Fatal error if remote has schizophrenic top-bases
2162 # No error (and $2, if provided, will be set to empty) if remote has no top-bases at all
2163 check_remote_topbases()
2165 [ -n "$1" ] || die "programmer error: check_remote_topbases called with no remote argument"
2166 _crrc=0 _crremotebases=
2167 _crremotebases="$(
2168 git for-each-ref --format='%(refname)' "refs/remotes/$1" 2>/dev/null |
2169 run_awk_ref_prefixes -n -- "refs/remotes/$1/{top-bases}" "refs/remotes/$1/top-bases" "refs/remotes/$1")" ||
2170 _crrc=$?
2171 if [ "$_crrc" = "65" ]; then
2172 err "remote \"$1\" has top-bases in both locations:"
2173 err " refs/remotes/$1/{top-bases}/..."
2174 err " refs/remotes/$1/top-bases/..."
2175 err "set \"topgit.top-bases\" to \"heads\" for the first, preferred location"
2176 err "or set \"topgit.top-bases\" to \"refs\" for the second, old location"
2177 err "(the \"-c topgit.top-bases=<val>\" option can be used for this)"
2178 err "then re-run the tg ${3:-$cmd} command"
2179 err "(the tg migrate-bases command can also help with this problem)"
2180 die "schizophrenic remote \"$1\" requires topgit.top-bases setting"
2182 [ "$_crrc" != "66" ] || _crremotebases= # just to be sure
2183 [ -z "$2" ] || eval "$2="'"$_crremotebases"'
2184 unset _crrc _crremotebases
2185 return 0
2188 # init_reflog "ref"
2189 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
2190 # an empty log file to exist so that ref changes will be logged
2191 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
2192 # However, if "$1" is "refs/tgstash" then always make the reflog
2193 # The only ref not under refs/ that Git will write a reflog for is HEAD;
2194 # no matter what, it will NOT update a reflog for any other bare refs so
2195 # just quietly succeed when passed TG_STASH without doing anything.
2196 init_reflog()
2198 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
2199 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
2200 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
2201 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
2202 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
2205 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
2206 # a symbolic link. The directory part must exist, but the basename need not.
2207 v_get_abs_path()
2209 [ -n "$1" ] && [ -n "$2" ] || return 1
2210 set -- "$1" "$2" "${2%/}"
2211 case "$3" in
2212 */*) set -- "$1" "$2" "${3%/*}";;
2213 * ) set -- "$1" "$2" ".";;
2214 esac
2215 case "$2" in */)
2216 set -- "$1" "${2%/}" "$3" "/"
2217 esac
2218 [ -d "$3" ] || return 1
2219 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
2222 ## Startup
2224 : "${TG_INST_CMDDIR:=@cmddir@}"
2225 : "${TG_INST_SHAREDIR:=@sharedir@}"
2226 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
2228 [ -d "$TG_INST_CMDDIR" ] ||
2229 die "No command directory: '$TG_INST_CMDDIR'"
2231 ## Include awk scripts and their utility functions (separated for easier debugging)
2233 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
2234 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
2235 . "$TG_INST_CMDDIR/tg--awksome"
2237 if [ -n "$tg__include" ]; then
2239 # We were sourced from another script for our utility functions;
2240 # this is set by hooks. Skip the rest of the file. A simple return doesn't
2241 # work as expected in every shell. See http://bugs.debian.org/516188
2243 # ensure setup happens
2245 initial_setup 1
2246 set_topbases 1
2247 noalt_setup
2249 else
2251 set -e
2253 tgbin="$0"
2254 tgdir="${tgbin%/}"
2255 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
2256 tgdir="${tgdir%/*}/"
2257 tgname="${tgbin##*/}"
2258 [ "$0" != "$tgname" ] || tgdir=""
2260 # If tg contains a '/' but does not start with one then replace it with an absolute path
2262 case "$0" in /*) ;; */*)
2263 tgdir="$(cd "${0%/*}" && pwd -P)/"
2264 tgbin="$tgdir$tgname"
2265 esac
2267 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
2268 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2270 tgdisplaydir="$tgdir"
2271 tgdisplay="$tgbin"
2272 tgdisplayac="$tgdisplay"
2274 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2275 _tgabs="$_tgnameabs" &&
2276 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2277 [ "$_tgabs" = "$_tgnameabs" ]
2278 then
2279 tgdisplaydir=""
2280 tgdisplay="$tgname"
2281 tgdisplayac="$tgdisplay"
2283 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2284 unset_ _tgabs _tgnameabs
2286 tg() (
2287 TG_TMPDIR="$tg_tmp_dir" && export TG_TMPDIR &&
2288 exec "$tgbin" "$@"
2291 explicit_remote=
2292 explicit_dir=
2293 gitcdopt=
2294 noremote=
2295 forcepager=
2297 cmd=
2298 while :; do case "$1" in
2300 help|--help|-h)
2301 cmd=help
2302 shift
2303 break;;
2305 status|--status)
2306 cmd=status
2307 shift
2308 break;;
2310 --hooks-path)
2311 cmd=hooks-path
2312 shift
2313 break;;
2315 --exec-path)
2316 cmd=exec-path
2317 shift
2318 break;;
2320 --awk-path)
2321 cmd=awk-path
2322 shift
2323 break;;
2325 --top-bases)
2326 cmd=top-bases
2327 shift
2328 break;;
2330 --no-pager)
2331 forcepager=0
2332 shift;;
2334 --pager|-p)
2335 forcepager=1
2336 shift;;
2339 shift
2340 if [ -z "$1" ]; then
2341 echo "Option -r requires an argument." >&2
2342 do_help
2343 exit 1
2345 unset_ noremote
2346 base_remote="$1"
2347 explicit_remote="$base_remote"
2348 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2349 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2350 shift;;
2353 unset_ base_remote explicit_remote
2354 noremote=1
2355 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2356 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2357 shift;;
2360 shift
2361 if [ -z "$1" ]; then
2362 echo "Option -C requires an argument." >&2
2363 do_help
2364 exit 1
2366 cd "$1"
2367 unset_ GIT_DIR GIT_COMMON_DIR
2368 if [ -z "$explicit_dir" ]; then
2369 explicit_dir="$1"
2370 else
2371 explicit_dir="$PWD"
2373 gitcdopt=" -C \"$explicit_dir\""
2374 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2375 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2376 tgdisplayac="$tgdisplay"
2377 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2378 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2379 shift;;
2382 shift
2383 if [ -z "$1" ]; then
2384 echo "Option -c requires an argument." >&2
2385 do_help
2386 exit 1
2388 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2389 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2390 export GIT_CONFIG_PARAMETERS
2391 shift;;
2394 shift
2395 break;;
2398 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2399 do_help
2400 exit 1;;
2403 break;;
2405 esac; done
2406 if [ z"$forcepager" = z"0" ]; then
2407 GIT_PAGER_IN_USE=1 TG_PAGER_IN_USE=1 &&
2408 export GIT_PAGER_IN_USE TG_PAGER_IN_USE
2411 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
2413 ## Dispatch
2415 [ -n "$cmd" ] || { do_help; exit 1; }
2417 case "$cmd" in
2419 help)
2420 do_help "$@"
2421 exit 0;;
2423 status|st)
2424 unset_ base_remote
2425 basic_setup
2426 set_topbases
2427 do_status "$@"
2428 exit ${do_status_result:-0};;
2430 hooks-path)
2431 # Internal command
2432 echol "$TG_INST_HOOKSDIR";;
2434 exec-path)
2435 # Internal command
2436 echol "$TG_INST_CMDDIR";;
2438 awk-path)
2439 # Internal command
2440 echol "$TG_INST_CMDDIR/awk";;
2442 top-bases)
2443 # Maintenance command
2444 do_topbases_help=
2445 show_remote_topbases=
2446 case "$1" in
2447 --help|-h)
2448 do_topbases_help=0;;
2449 -r|--remote)
2450 if [ $# -eq 2 ] && [ -n "$2" ]; then
2451 # unadvertised, but make it work
2452 base_remote="$2"
2453 shift
2455 show_remote_topbases=1;;
2457 [ $# -eq 0 ] || do_topbases_help=1;;
2458 esac
2459 [ $# -le 1 ] || do_topbases_help=1
2460 if [ -n "$do_topbases_help" ]; then
2461 helpcmd='echo "Usage: ${tgname:-tg} [-r <remote>] --top-bases [-r]"'
2462 [ $do_topbases_help -eq 0 ] || helpcmd="$helpcmd >&2"
2463 eval "$helpcmd"
2464 exit $do_topbases_help
2466 git_dir=
2467 ! git_dir="$(git rev-parse --git-dir 2>&1)" || setup_git_dirs
2468 set_topbases
2469 if [ -n "$show_remote_topbases" ]; then
2470 basic_setup_remote
2471 [ -n "$base_remote" ] ||
2472 die "no remote location given. Either use -r <remote> option or set topgit.remote"
2473 rbases=
2474 [ -z "$topbases_implicit_default" ] ||
2475 check_remote_topbases "$base_remote" rbases "--top-bases"
2476 if [ -n "$rbases" ]; then
2477 echol "$rbases"
2478 else
2479 echol "refs/remotes/$base_remote/${topbases#heads/}"
2481 else
2482 echol "refs/$topbases"
2483 fi;;
2486 isutil=
2487 case "$cmd" in index-merge-one-file)
2488 isutil="-"
2489 esac
2490 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2491 looplevel="$TG_ALIAS_DEPTH"
2492 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2493 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2494 looplevel=0
2495 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2496 [ -n "$tgalias" ] || {
2497 echo "Unknown subcommand: $cmd" >&2
2498 do_help
2499 exit 1
2501 looplevel=$(( $looplevel + 1 ))
2502 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2503 TG_ALIAS_DEPTH="$looplevel"
2504 export TG_ALIAS_DEPTH
2505 if [ "!${tgalias#?}" = "$tgalias" ]; then
2506 unset_ GIT_PREFIX
2507 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2508 GIT_PREFIX="$pfx"
2509 export GIT_PREFIX
2511 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2512 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2513 else
2514 eval 'exec "$tgbin"' "$tgalias" '"$@"'
2516 die "alias execution failed for: $tgalias"
2518 unset_ TG_ALIAS_DEPTH
2520 showing_help=
2521 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2522 showing_help=1
2525 [ -n "$showing_help" ] || initial_setup
2526 [ -z "$noremote" ] || unset_ base_remote
2528 nomergesetup="$showing_help"
2529 case "$cmd" in base|contains|files|info|log|mail|next|patch|prev|rebase|revert|summary|tag)
2530 # avoid merge setup where not necessary
2532 nomergesetup=1
2533 esac
2535 if [ -z "$nomergesetup" ]; then
2536 # make sure merging the .top* files will always behave sanely
2538 setup_ours
2539 setup_hook "pre-commit"
2542 # everything but rebase needs topbases set
2543 carefully="$showing_help"
2544 [ "$cmd" != "migrate-bases" ] || carefully=1
2545 [ "$cmd" = "rebase" ] || set_topbases $carefully
2547 _use_ref_cache=
2548 tg_read_only=1
2549 _suppress_alt=
2550 case "$cmd$showing_help" in
2551 contains|info|summary|tag)
2552 _use_ref_cache=1;;
2553 "export")
2554 _use_ref_cache=1
2555 _suppress_alt=1;;
2556 annihilate|create|delete|depend|import|update)
2557 tg_read_only=
2558 _suppress_alt=1;;
2559 esac
2560 [ -z "$_suppress_alt" ] || noalt_setup
2561 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2563 fullcmd="${tgname:-tg} $cmd $*"
2564 if [ z"$forcepager" = z"1" ]; then
2565 page '. "$TG_INST_CMDDIR"/tg-$isutil$cmd' "$@"
2566 else
2567 . "$TG_INST_CMDDIR"/tg-$isutil$cmd
2568 fi;;
2569 esac