tg.sh: add is_empty_dir function
[topgit/pro.git] / tg.sh
blob6cf51960184e56d84fa8b4619e78d35a98f3dda1
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 # true if "$1" is an existing dir and is empty except for
188 # any additional files given as extra arguments. If "$2"
189 # is the single character "." then all ".*" files will be
190 # ignored for the test (plus any further args, if any)
191 is_empty_dir() {
192 test -n "$1" && test -d "$1" || return 1
193 iedd_="$1"
194 shift
195 ieddnok_='\.?$'
196 if [ z"$1" = z"." ]; then
197 ieddnok_=
198 shift
199 while ! case "$1" in "."*) ! :; esac; do shift; done
201 if [ $# -eq 0 ]; then
202 ! \ls -a1 "$iedd_" | grep -q -E -v '^\.'"$ieddnok_"
203 else
204 # we only handle ".git" right now for efficiency
205 [ z"$*" = z".git" ] || {
206 fatal "[BUG] is_empty_dir not implemented for arguments: $*"
207 exit 70
209 ! \ls -a1 "$iedd_" | grep -q -E -v -i -e '^\.\.?$' -e '^\.git$'
213 precheck() {
214 if ! git_version="$(git version)"; then
215 die "'git version' failed"
217 case "$git_version" in [Gg]"it version "*);;*)
218 die "'git version' output does not start with 'git version '"
219 esac
221 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
222 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
225 case "$1" in version|--version|-V)
226 echo "TopGit version $TG_VERSION"
227 exit 0
228 esac
230 [ $# -eq 1 ] && [ "$1" = "--make-empty-blob" ] || precheck
231 [ $# -ne 1 ] || [ "$1" != "precheck" ] || exit 0
233 cat_depsmsg_internal()
235 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
236 if [ -s "$tg_cache_dir/refs/heads/$1/.$2" ]; then
237 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
238 _line=
239 while IFS= read -r _line || [ -n "$_line" ]; do
240 printf '%s\n' "$_line"
241 done
242 return 0
243 fi <"$tg_cache_dir/refs/heads/$1/.$2"
245 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null || :
246 if [ -d "$tg_cache_dir/refs/heads/$1" ]; then
247 printf '%s\n' "$_rev" >"$tg_cache_dir/refs/heads/$1/.$2"
248 _line=
249 git cat-file blob "$_rev:.$2" 2>/dev/null |
250 while IFS= read -r _line || [ -n "$_line" ]; do
251 printf '%s\n' "$_line" >&3
252 printf '%s\n' "$_line"
253 done 3>>"$tg_cache_dir/refs/heads/$1/.$2"
254 else
255 git cat-file blob "$_rev:.$2" 2>/dev/null
259 # cat_deps BRANCHNAME
260 # Caches result
261 cat_deps()
263 cat_depsmsg_internal "$1" topdeps
266 # cat_msg BRANCHNAME
267 # Caches result
268 cat_msg()
270 cat_depsmsg_internal "$1" topmsg
273 # cat_file TOPIC:PATH [FROM]
274 # cat the file PATH from branch TOPIC when FROM is empty.
275 # FROM can be -i or -w, than the file will be from the index or worktree,
276 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
277 cat_file()
279 path="$1"
280 case "$2" in
282 cat "$root_dir/${path#*:}"
285 # ':file' means cat from index
286 git cat-file blob ":${path#*:}" 2>/dev/null
289 case "$path" in
290 refs/heads/*:.topdeps)
291 _temp="${path%:.topdeps}"
292 cat_deps "${_temp#refs/heads/}"
294 refs/heads/*:.topmsg)
295 _temp="${path%:.topmsg}"
296 cat_msg "${_temp#refs/heads/}"
299 git cat-file blob "$path" 2>/dev/null
301 esac
304 die "Wrong argument to cat_file: '$2'"
306 esac
309 # if use_alt_temp_odb and tg_use_alt_odb are true try to write the object(s)
310 # into the temporary alt odb area instead of the usual location
311 git_temp_alt_odb_cmd()
313 if [ -n "$use_alt_temp_odb" ] && [ -n "$tg_use_alt_odb" ] &&
314 [ -n "$TG_OBJECT_DIRECTORY" ] &&
315 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
317 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
318 GIT_OBJECT_DIRECTORY="$TG_OBJECT_DIRECTORY"
319 unset_ TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES
320 export GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
321 git "$@"
323 else
324 git "$@"
328 git_write_tree() { git_temp_alt_odb_cmd write-tree "$@"; }
329 git_mktree() { git_temp_alt_odb_cmd mktree "$@"; }
331 make_mtblob() {
332 use_alt_temp_odb=1
333 tg_use_alt_odb=1
334 git_temp_alt_odb_cmd hash-object -t blob -w --stdin </dev/null >/dev/null 2>&1
336 # short-circuit this for speed
337 [ $# -eq 1 ] && [ "$1" = "--make-empty-blob" ] && { make_mtblob || :; exit 0; }
339 # get tree for the committed topic
340 get_tree_()
342 echo "refs/heads/$1"
345 # get tree for the base
346 get_tree_b()
348 echo "refs/$topbases/$1"
351 # get tree for the index
352 get_tree_i()
354 git_write_tree
357 # get tree for the worktree
358 get_tree_w()
360 i_tree=$(git_write_tree)
362 # the file for --index-output needs to sit next to the
363 # current index file
364 cd "$root_dir"
365 : ${GIT_INDEX_FILE:="$git_dir/index"}
366 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
367 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
368 GIT_INDEX_FILE="$TMP_INDEX" &&
369 export GIT_INDEX_FILE &&
370 git diff --name-only -z HEAD |
371 git update-index -z --add --remove --stdin &&
372 git_write_tree &&
373 rm -f "$TMP_INDEX"
377 # get tree for arbitrary ref
378 get_tree_r()
380 echo "$1"
383 # strip_ref "$(git symbolic-ref HEAD)"
384 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
385 strip_ref()
387 case "$1" in
388 refs/"$topbases"/*)
389 echol "${1#refs/$topbases/}"
391 refs/heads/*)
392 echol "${1#refs/heads/}"
395 echol "$1"
396 esac
399 # pretty_tree [-t] NAME [-b | -i | -w | -r]
400 # Output tree ID of a cleaned-up tree without tg's artifacts.
401 # NAME will be ignored for -i and -w, but needs to be present
402 # With -r NAME must be a full ref name to a treeish (it's used as-is)
403 # If -t is used the tree is written into the alternate temporary objects area
404 pretty_tree()
406 use_alt_temp_odb=
407 [ "$1" != "-t" ] || { shift; use_alt_temp_odb=1; }
408 name="$1"
409 source="${2#?}"
410 git ls-tree --full-tree "$(get_tree_$source "$name")" |
411 sed -ne '/ \.top.*$/!p' |
412 git_mktree
415 # return an empty-tree root commit -- date is either passed in or current
416 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
417 # An invalid secs causes the current date to be used, an invalid zone offset
418 # causes +0000 to be used
419 make_empty_commit()
421 # the empty tree is guaranteed to always be there even in a repo with
422 # zero objects, but for completeness we force it to exist as a real object
423 SECS=
424 read -r SECS ZONE JUNK <<-EOT || :
427 case "$SECS" in *[!0-9]*) SECS=; esac
428 if [ -z "$SECS" ]; then
429 MTDATE="$(date '+%s %z')"
430 else
431 case "$ZONE" in
432 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
434 [01][0-9][0-5][0-9])
435 ZONE="+$ZONE"
438 ZONE="+0000"
439 esac
440 MTDATE="$SECS $ZONE"
442 EMPTYID="- <-> $MTDATE"
443 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
444 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
445 git hash-object -t commit -w --stdin
448 # standard input is a diff
449 # standard output is the "+" lines with leading "+ " removed
450 # beware that old lines followed by the dreaded '\ No newline at end of file'
451 # will appear to be new lines if lines are added after them
452 # the git diff --ignore-space-at-eol option can be used to prevent this
453 diff_added_lines()
455 awk '
456 BEGIN { in_hunk = 0; }
457 /^@@ / { in_hunk = 1; }
458 /^\+/ { if (in_hunk == 1) printf("%s\n", substr($0, 2)); }
459 !/^\\ No newline at end of file/ &&
460 /^[^@ +-]/ { in_hunk = 0; }
464 # $1 is name of new branch to create locally if all of these are true:
465 # a) exists as a remote TopGit branch for "$base_remote"
466 # b) the branch "name" does not have any invalid characters in it
467 # c) neither of the two branch refs (branch or base) exist locally
468 # returns success only if a new local branch was created (and dumps message)
469 auto_create_local_remote()
471 case "$1" in ""|*[" $tab$lf~^:\\*?["]*|.*|*/.*|*.|*./|/*|*/|*//*) return 1; esac
472 [ -n "$base_remote" ] &&
473 git update-ref --stdin <<-EOT >/dev/null 2>&1 &&
474 verify refs/remotes/$base_remote/${topbases#heads/}/$1 refs/remotes/$base_remote/${topbases#heads/}/$1
475 verify refs/remotes/$base_remote/$1 refs/remotes/$base_remote/$1
476 create refs/$topbases/$1 refs/remotes/$base_remote/${topbases#heads/}/$1^0
477 create refs/heads/$1 refs/remotes/$base_remote/$1^0
479 { init_reflog "refs/$topbases/$1" || :; } &&
480 info "topic branch '$1' automatically set up from remote '$base_remote'"
483 # setup_hook NAME
484 setup_hook()
486 setup_git_dir_is_bare
487 [ -z "$git_dir_is_bare" ] || return 0
488 tgname="${0##*/}"
489 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
490 if [ -f "$git_hooks_dir/$1" ] && grep -Fq "$hook_call" "$git_hooks_dir/$1"; then
491 # Another job well done!
492 return
494 # Prepare incantation
495 hook_chain=
496 if [ -s "$git_hooks_dir/$1" -a -x "$git_hooks_dir/$1" ]; then
497 hook_call="$hook_call"' || exit $?'
498 if [ -L "$git_hooks_dir/$1" ] || ! sed -n 1p <"$git_hooks_dir/$1" | grep -Fqx "#!@SHELL_PATH@"; then
499 chain_num=
500 while [ -e "$git_hooks_dir/$1-chain$chain_num" ]; do
501 chain_num=$(( $chain_num + 1 ))
502 done
503 mv -f "$git_hooks_dir/$1" "$git_hooks_dir/$1-chain$chain_num"
504 hook_chain=1
506 else
507 hook_call="exec $hook_call"
508 [ -d "$git_hooks_dir" ] || mkdir -p "$git_hooks_dir" || :
510 # Don't call hook if tg is not installed
511 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
512 # Insert call into the hook
514 echol "#!@SHELL_PATH@"
515 echol "$hook_call"
516 if [ -n "$hook_chain" ]; then
517 echol "exec \"\$0-chain$chain_num\" \"\$@\""
518 else
519 [ ! -s "$git_hooks_dir/$1" ] || cat "$git_hooks_dir/$1"
521 } >"$git_hooks_dir/$1+"
522 chmod a+x "$git_hooks_dir/$1+"
523 mv "$git_hooks_dir/$1+" "$git_hooks_dir/$1"
526 # setup_ours (no arguments)
527 setup_ours()
529 setup_git_dir_is_bare
530 [ -z "$git_dir_is_bare" ] || return 0
531 if [ ! -s "$git_common_dir/info/attributes" ] || ! grep -q topmsg "$git_common_dir/info/attributes"; then
532 [ -d "$git_common_dir/info" ] || mkdir "$git_common_dir/info"
534 echo ".topmsg merge=ours"
535 echo ".topdeps merge=ours"
536 } >>"$git_common_dir/info/attributes"
538 if ! git config merge.ours.driver >/dev/null; then
539 git config merge.ours.name '"always keep ours" merge driver'
540 git config merge.ours.driver 'touch %A'
544 # measure_branch NAME [BASE] [EXTRAHEAD...]
545 measure_branch()
547 _bname="$1"; _base="$2"
548 shift; shift
549 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
550 # The caller should've verified $name is valid
551 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
552 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
553 if [ $_commits -ne 1 ]; then
554 _suffix="commits"
555 else
556 _suffix="commit"
558 echo "$_commits/$_nmcommits $_suffix"
561 # true if $1 is contained by (or the same as) $2
562 # this is never slower than merge-base --is-ancestor and is often slightly faster
563 contained_by()
565 [ "$(git rev-list --count --max-count=1 "$1" --not "$2" --)" = "0" ]
568 # branch_contains B1 B2
569 # Whether B1 is a superset of B2.
570 branch_contains()
572 _revb1="$(ref_exists_rev "$1")" || return 0
573 _revb2="$(ref_exists_rev "$2")" || return 0
574 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
575 if read _result _rev_matchb1 _rev_matchb2 &&
576 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
577 return $_result
578 fi <"$tg_cache_dir/$1/.bc/$2/.d"
580 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
581 _result=0
582 contained_by "$_revb2" "$_revb1" || _result=1
583 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
584 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
586 return $_result
589 create_ref_dirs()
591 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
592 mkdir -p "$tg_tmp_dir/cached/refs"
593 awk '{x = $1; sub(/^refs\//, "", x); if (x != "") print x}' <"$tg_ref_cache" | tr '\n' '\0' | {
594 cd "$tg_tmp_dir/cached/refs" &&
595 xargs -0 mkdir -p
597 awk -v p="$tg_tmp_dir/cached/" '
598 NF == 2 &&
599 $1 ~ /^refs\/./ &&
600 $2 ~ /^[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]+$/ {
601 fn = p $1 "/.ref"
602 print "0 " $2 >fn
603 close(fn)
605 ' <"$tg_ref_cache"
606 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
609 # If the first argument is non-empty, stores "1" there if this call created the cache
610 v_create_ref_cache()
612 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
613 _remotespec=
614 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
615 [ -z "$1" ] || eval "$1=1"
616 git for-each-ref --format='%(refname) %(objectname)' \
617 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
618 create_ref_dirs
621 remove_ref_cache()
623 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
624 >"$tg_ref_cache"
625 >"$tg_ref_cache_br"
626 >"$tg_ref_cache_rbr"
627 >"$tg_ref_cache_ann"
628 >"$tg_ref_cache_dep"
631 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
632 rev_parse()
634 rev_parse_code_=1
635 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
636 rev_parse_code_=0
637 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache" ||
638 rev_parse_code_=$?
640 [ $rev_parse_code_ -ne 0 ] && [ -z "$tg_ref_cache_only" ] || return $rev_parse_code_
641 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
644 # ref_exists_rev REF
645 # Whether REF is a valid ref name
646 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
647 # or, if $base_remote is set, refs/remotes/$base_remote/
648 # Caches result if $tg_read_only and outputs HASH on success
649 ref_exists_rev()
651 case "$1" in
652 refs/*)
654 $octet20)
655 printf '%s' "$1"
656 return;;
658 die "ref_exists_rev requires fully-qualified ref name (given: $1)"
659 esac
660 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
661 _result=
662 _result_rev=
663 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
664 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
665 _result=0
666 _result_rev="$(rev_parse "$1")" || _result=$?
667 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
668 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
669 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
670 printf '%s' "$_result_rev"
671 return $_result
674 # Same as ref_exists_rev but output is abbreviated hash
675 # Optional second argument defaults to --short but may be any --short=.../--no-short option
676 ref_exists_rev_short()
678 case "$1" in
679 refs/*)
681 $octet20)
684 die "ref_exists_rev_short requires fully-qualified ref name"
685 esac
686 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
687 _result=
688 _result_rev=
689 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
690 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
691 _result=0
692 _result_rev="$(rev_parse "$1")" || _result=$?
693 if [ $_result -eq 0 ]; then
694 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev^0" --)"
695 _result=$?
697 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
698 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
699 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
700 printf '%s' "$_result_rev"
701 return $_result
704 # ref_exists REF
705 # Whether REF is a valid ref name
706 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
707 # or, if $base_remote is set, refs/remotes/$base_remote/
708 # Caches result
709 ref_exists()
711 ref_exists_rev "$1" >/dev/null
714 # rev_parse_tree REF
715 # Runs git rev-parse REF^{tree}
716 # Caches result if $tg_read_only
717 rev_parse_tree()
719 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
720 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
721 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
722 printf '%s\n' "$_result"
723 return 0
725 return 1
727 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
728 if [ -d "$tg_tmp_dir/cached/$1" ]; then
729 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
730 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
731 printf '%s\n' "$_result"
732 return 0
734 return 1
736 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
739 # has_remote BRANCH
740 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
741 has_remote()
743 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
746 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
747 # If -z "$1" still set return code but do not return result
748 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
749 # refs/heads/... then ... will be verified instead.
750 # if "$3" = "-f" (for fail) then return an error rather than dying.
751 v_verify_topgit_branch()
753 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
754 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
755 [ -n "$_verifyname" -o "$3" = "-f" ] || die "HEAD is not a symbolic ref"
756 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
757 [ "$3" != "-f" ] || return 1
758 die "HEAD is not a symbolic ref to the refs/heads namespace"
759 esac
760 set -- "$1" "$_verifyname" "$3"
762 case "$2" in
763 refs/"$topbases"/*)
764 _verifyname="${2#refs/$topbases/}"
766 refs/heads/*)
767 _verifyname="${2#refs/heads/}"
770 _verifyname="$2"
772 esac
773 if ! ref_exists "refs/heads/$_verifyname"; then
774 [ "$3" != "-f" ] || return 1
775 die "no such branch: $_verifyname"
777 if ! ref_exists "refs/$topbases/$_verifyname"; then
778 [ "$3" != "-f" ] || return 1
779 die "not a TopGit-controlled branch: $_verifyname"
781 [ -z "$1" ] || eval "$1="'"$_verifyname"'
784 # Return the verified TopGit branch name or die with an error.
785 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
786 # refs/heads/... then ... will be verified instead.
787 # if "$2" = "-f" (for fail) then return an error rather than dying.
788 verify_topgit_branch()
790 v_verify_topgit_branch _verifyname "$@" || return
791 printf '%s' "$_verifyname"
794 # Caches result
795 # $1 = branch name (i.e. "t/foo/bar")
796 # $2 = optional result of rev-parse "refs/heads/$1"
797 # $3 = optional result of rev-parse "refs/$topbases/$1"
798 branch_annihilated()
800 _branch_name="$1"
801 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
802 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
804 _result=
805 _result_rev=
806 _result_rev_base=
807 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/refs/heads/$_branch_name/.ann"; } 2>/dev/null || :
808 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
810 # use the merge base in case the base is ahead.
811 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
813 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
814 _result=$?
815 [ -d "$tg_cache_dir/refs/heads/$_branch_name" ] || mkdir -p "$tg_cache_dir/refs/heads/$_branch_name" 2>/dev/null
816 [ ! -d "$tg_cache_dir/refs/heads/$_branch_name" ] ||
817 echo $_result $_rev $_rev_base >"$tg_cache_dir/refs/heads/$_branch_name/.ann" 2>/dev/null || :
818 return $_result
821 non_annihilated_branches()
823 refscacheopt="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
824 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
825 refscacheopt="$refscacheopt"'-r="$tg_ref_cache" "refs/$topbases"'
827 eval run_awk_topgit_branches -n "$refscacheopt" '"refs/$topbases" "$@"'
830 # Make sure our tree is clean
831 # if optional "$1" given also verify that a checkout to "$1" would succeed
832 ensure_clean_tree()
834 check_status
835 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
836 git update-index --ignore-submodules --refresh ||
837 die "the working directory has uncommitted changes (see above) - first commit or reset them"
838 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
839 die "the index has uncommited changes"
840 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
841 die "git checkout \"$1\" would fail"
844 # Make sure .topdeps and .topmsg are "clean"
845 # They are considered "clean" if each is identical in worktree, index and HEAD
846 # With "-u" as the argument skip the HEAD check (-u => unborn)
847 # untracked .topdeps and/or .topmsg files are always considered "dirty" as well
848 # with -u them just existing constitutes "dirty"
849 ensure_clean_topfiles()
851 _dirtw=0
852 _dirti=0
853 _dirtu=0
854 _check="$(git diff-files --ignore-submodules --name-only -- :/.topdeps :/.topmsg)" &&
855 [ -z "$_check" ] || _dirtw=1
856 if [ "$1" != "-u" ]; then
857 _check="$(git diff-index --cached --ignore-submodules --name-only HEAD -- :/.topdeps :/.topmsg)" &&
858 [ -z "$_check" ] || _dirti=1
860 if [ "$_dirti$_dirtw" = "00" ]; then
861 v_get_show_cdup
862 if [ -e "${git_cdup_result}.topdeps" ] || [ -e "${git_cdup_result}.topmsg" ]; then
863 [ "$1" != "-u" ] &&
864 _check="$(git status --porcelain --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg)" &&
865 [ -z "$_check" ] || _dirtu=1
868 if [ "$_dirtu$_dirti$_dirtw" != "000" ]; then
869 git status --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg || :
870 case "$_dirtu$_dirti$_dirtw" in
871 001) die "the working directory has uncommitted changes (see above) - first commit or reset them";;
872 010) die "the index has uncommited changes (see above)";;
873 011) die "the working directory and index have uncommitted changes (see above) - first commit or reset them";;
874 100) die "the working directory has untracked files that would be overwritten (see above)";;
875 esac
879 # is_sha1 REF
880 # Whether REF is a SHA1 (compared to a symbolic name).
881 is_sha1()
883 case "$1" in $octet20) return 0;; esac
884 return 1
887 # navigate_deps <run_awk_topgit_navigate options and arguments>
888 # all options and arguments are passed through to run_awk_topgit_navigate
889 # except for a leading -td= option, if any, which is picked off for deps
890 # after arranging to feed it a suitable deps list
891 navigate_deps()
893 dogfer=
894 dorad=1
895 userc=
896 tmpdep=
897 ratd_opts="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
898 ratn_opts=
899 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
900 userc=1
901 tmprfs="$tg_ref_cache"
902 tmptgbr="$tg_ref_cache_br"
903 tmpann="$tg_ref_cache_ann"
904 tmpdep="$tg_ref_cache_dep"
905 [ -s "$tg_ref_cache" ] || dogfer=1
906 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
907 else
908 ratd_opts="${ratd_opts}-rmr"
909 ratn_opts="-rma -rmb"
910 tmprfs="$tg_tmp_dir/refs.$$"
911 tmpann="$tg_tmp_dir/ann.$$"
912 tmptgbr="$tg_tmp_dir/tgbr.$$"
913 dogfer=1
915 refpats="\"refs/heads\" \"refs/\$topbases\""
916 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
917 [ -z "$dogfer" ] ||
918 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
919 depscmd="run_awk_topgit_deps $ratd_opts"
920 case "$1" in -td=*)
921 userc=
922 depscmd="$depscmd $1"
923 shift
924 esac
925 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -s "refs/$topbases"'
926 if [ -n "$userc" ]; then
927 if [ -n "$dorad" ]; then
928 eval "$depscmd" >"$tmpdep"
930 depscmd='<"$tmpdep" '
931 else
932 depscmd="$depscmd |"
934 eval "$depscmd" run_awk_topgit_navigate '-a="$tmpann" -b="$tmptgbr"' "$ratn_opts" '"$@"'
937 # recurse_deps_internal NAME [BRANCHPATH...]
938 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
939 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
940 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
941 # (but missing and remotes are always "0")
942 # followed by a 0 for no excess visits or a positive number of excess visits
943 # then the branch name followed by its depedency chain (which might be empty)
944 # An output line might look like this:
945 # 0 1 1 0 t/foo/leaf t/foo/int t/stage
946 # If no_remotes is non-empty, exclude remotes
947 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
948 # If with_top_level is non-empty, include the top-level that's normally omitted
949 # any branch names in the space-separated recurse_deps_exclude variable
950 # are skipped (along with their dependencies)
951 recurse_deps_internal()
953 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
954 ratr_opts="${recurse_preorder:+-f} ${with_top_level:+-s}"
955 dogfer=
956 dorad=1
957 userc=
958 tmpdep=
959 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
960 userc=1
961 tmprfs="$tg_ref_cache"
962 tmptgbr="$tg_ref_cache_br"
963 tmpann="$tg_ref_cache_ann"
964 tmpdep="$tg_ref_cache_dep"
965 [ -s "$tg_ref_cache" ] || dogfer=1
966 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
967 else
968 ratr_opts="$ratr_opts -rmh -rma -rmb"
969 tmprfs="$tg_tmp_dir/refs.$$"
970 tmpann="$tg_tmp_dir/ann.$$"
971 tmptgbr="$tg_tmp_dir/tgbr.$$"
972 dogfer=1
974 refpats="\"refs/heads\" \"refs/\$topbases\""
975 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
976 tmptgrmtbr=
977 dorab=1
978 if [ -z "$no_remotes" ] && [ -n "$base_remote" ]; then
979 if [ -n "$userc" ]; then
980 tmptgrmtbr="$tg_ref_cache_rbr"
981 [ -n "$dogfer" ] || ! [ -s "$tmptgrmtbr" ] || dorab=
982 else
983 tmptgrmtbr="$tg_tmp_dir/tgrmtbr.$$"
984 ratr_opts="$ratr_opts -rmr"
986 ratr_opts="$ratr_opts -r=\"\$tmptgrmtbr\" -u=\":refs/remotes/\$base_remote/\${topbases#heads/}\""
988 [ -z "$dogfer" ] ||
989 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
990 if [ -n "$tmptgrmtbr" ] && [ -n "$dorab" ]; then
991 run_awk_topgit_branches -n -h="refs/remotes/$base_remote" -r="$tmprfs" \
992 "refs/remotes/$base_remote/${topbases#heads/}" >"$tmptgrmtbr"
994 depscmd="run_awk_topgit_deps -s${TG_DEBUG:+ -p=\"\$tg_ref_cache.pre\"}"
995 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" "refs/$topbases"'
996 if [ -n "$userc" ]; then
997 if [ -n "$dorad" ]; then
998 eval "$depscmd" >"$tmpdep"
1000 depscmd='<"$tmpdep" '
1001 else
1002 depscmd="$depscmd |"
1004 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
1005 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
1008 # do_eval CMD
1009 # helper for recurse_deps so that a return statement executed inside CMD
1010 # does not return from recurse_deps. This shouldn't be necessary, but it
1011 # seems that it actually is.
1012 do_eval()
1014 eval "$@"
1017 # becomes read-only for caching purposes
1018 # assigns new value to tg_read_only
1019 # become_cacheable/undo_become_cacheable calls may be nested
1020 become_cacheable()
1022 _old_tg_read_only="$tg_read_only"
1023 if [ -z "$tg_read_only" ]; then
1024 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1025 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1026 tg_read_only=1
1028 _my_ref_cache=
1029 v_create_ref_cache _my_ref_cache
1030 _my_ref_cache="${_my_ref_cache:+1}"
1031 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
1034 # restores tg_read_only and ref_cache to state before become_cacheable call
1035 # become_cacheable/undo_bocome_cacheable calls may be nested
1036 undo_become_cacheable()
1038 case "$tg_read_only" in
1039 "undo"[01]"-"*)
1040 _suffix="${tg_read_only#undo?-}"
1041 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
1042 tg_read_only="$_suffix"
1043 esac
1046 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
1047 become_non_cacheable()
1049 remove_ref_cache
1050 tg_read_only=
1051 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
1052 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
1055 # call this to make sure the current Git repository has an associated work tree
1056 ensure_work_tree()
1058 setup_git_dir_is_bare
1059 [ -n "$git_dir_is_bare" ] || return 0
1060 die "This operation must be run in a work tree"
1063 # call this to make sure Git will not complain about a missing user/email
1064 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
1065 ensure_ident_available()
1067 [ -z "$TG_IDENT_CHECKED" ] || return 0
1068 git var GIT_AUTHOR_IDENT >/dev/null &&
1069 git var GIT_COMMITTER_IDENT >/dev/null || exit
1070 TG_IDENT_CHECKED=1
1071 export TG_IDENT_CHECKED
1072 return 0
1075 # recurse_deps [-o=<options string>] CMD NAME [BRANCHPATH...]
1076 # Recursively eval CMD on all dependencies of NAME.
1077 # Dependencies are visited in topological order.
1078 # If <options string> is given, it's eval'd into the recurse_deps_internal
1079 # call just before the "--" that's passed just before NAME
1080 # CMD can refer to the following variables:
1082 # _ret starts as 0; CMD can change; will be final return result
1083 # _dep bare branch name or ":refs/remotes/..." for a remote
1084 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
1085 # _depchain 0+ space-sep branch names (_name first) form a path to top
1086 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
1087 # _dep_is_leaf boolean "1" if leaf; "" if not
1088 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
1089 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
1090 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
1091 # _dep_xvisits non-negative integer number of excess visits (often 0)
1093 # CMD may use a "return" statement without issue; its return value is ignored,
1094 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
1095 # will stop immediately and the value with the leading "-" stripped off will
1096 # be the final result code
1098 # CMD can refer to $_name for queried branch name,
1099 # $_dep for dependency name,
1100 # $_depchain for space-seperated branch backtrace,
1101 # $_dep_missing boolean to check whether $_dep is present
1102 # and the $_dep_is_tgish and $_dep_annihilated booleans.
1103 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
1104 # It can modify $_ret to affect the return value
1105 # of the whole function.
1106 # If recurse_deps() hits missing dependencies, it will append
1107 # them to space-separated $missing_deps list and skip them
1108 # after calling CMD with _dep_missing set.
1109 # remote dependencies are processed if no_remotes is unset.
1110 # any branch names in the space-separated recurse_deps_exclude variable
1111 # are skipped (along with their dependencies)
1113 # If no_remotes is non-empty, exclude remotes
1114 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1115 # If with_top_level is non-empty, include the top-level that's normally omitted
1116 # any branch names in the space-separated recurse_deps_exclude variable
1117 # are skipped (along with their dependencies)
1118 recurse_deps()
1120 _opts=
1121 case "$1" in -o=*) _opts="${1#-o=}"; shift; esac
1122 _cmd="$1"; shift
1124 _depsfile="$(get_temp tg-depsfile)"
1125 eval recurse_deps_internal "$_opts" -- '"$@"' >"$_depsfile" || :
1127 _ret=0
1128 while read _ismissing _istgish _isleaf _dep_xvisits _dep _name _deppath; do
1129 _depchain="$_name${_deppath:+ $_deppath}"
1130 _dep_is_tgish=
1131 [ "$_istgish" = "0" ] || _dep_is_tgish=1
1132 _dep_has_remote=
1133 [ "$_istgish" != "2" ] || _dep_has_remote=1
1134 _dep_missing=
1135 if [ "$_ismissing" != "0" ]; then
1136 _dep_missing=1
1137 case " $missing_deps " in *" $_dep "*);;*)
1138 missing_deps="${missing_deps:+$missing_deps }$_dep"
1139 esac
1141 _dep_annihilated=
1142 _dep_is_leaf=
1143 if [ "$_isleaf" = "1" ]; then
1144 _dep_is_leaf=1
1145 elif [ "$_isleaf" = "2" ]; then
1146 _dep_annihilated=1
1148 do_eval "$_cmd" || :
1149 if [ "${_ret#-}" != "$_ret" ]; then
1150 _ret="${_ret#-}"
1151 break
1153 done <"$_depsfile"
1154 rm -f "$_depsfile"
1155 return ${_ret:-0}
1158 # find_leaves NAME
1159 # output (one per line) the unique leaves of NAME
1160 # a leaf is either
1161 # 1) a non-tgish dependency
1162 # 2) the base of a tgish dependency with no non-annihilated dependencies
1163 # duplicates are suppressed (by commit rev) and remotes are always ignored
1164 # if a leaf has an exact tag match that will be output
1165 # note that recurse_deps_exclude IS honored for this operation
1166 find_leaves()
1168 no_remotes=1
1169 with_top_level=1
1170 recurse_preorder=
1171 seen_leaf_refs=
1172 seen_leaf_revs=
1173 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1174 [ "$_isleaf" = "1" ] && [ "$_ismissing" = "0" ] || continue
1175 if [ "$_istgish" != "0" ]; then
1176 fulldep="refs/$topbases/$_dep"
1177 else
1178 fulldep="refs/heads/$_dep"
1180 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1181 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1182 if fullrev="$(ref_exists_rev "$fulldep")"; then
1183 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1184 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1185 # See if Git knows it by another name
1186 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1187 echo "refs/tags/$tagname"
1188 else
1189 echo "$fulldep"
1191 esac
1193 esac
1194 done <<-EOT
1195 $(recurse_deps_internal -l -o=1 -- "$1")
1197 with_top_level=
1200 # branch_needs_update
1201 # This is a helper function for determining whether given branch
1202 # is up-to-date wrt. its dependencies. It expects input as if it
1203 # is called as a recurse_deps() helper.
1204 # In case the branch does need update, it will echo it together
1205 # with the branch backtrace on the output (see needs_update()
1206 # description for details) and set $_ret to non-zero.
1207 branch_needs_update()
1209 if [ -n "$_dep_missing" ]; then
1210 echo "! $_dep $_depchain"
1211 return 0
1214 if [ -n "$_dep_is_tgish" ]; then
1215 [ -z "$_dep_annihilated" ] || return 0
1217 if [ -n "$_dep_has_remote" ]; then
1218 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" || {
1219 echo ":refs/remotes/$base_remote/$_dep $_dep $_depchain"
1220 _ret=1
1223 # We want to sync with our base first and should output this before
1224 # the remote branch, but the order does not actually matter to tg-update
1225 # as it just recurses regardless, but it does matter for tg-info (which
1226 # treats out-of-date bases as though they were already merged in) so
1227 # we output the remote before the base.
1228 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1229 echo ": $_dep $_depchain"
1230 _ret=1
1231 return
1235 if [ -n "$_name" ]; then
1236 case "$_dep" in :*) _fulldep="${_dep#:}";; *) _fulldep="refs/heads/$_dep";; esac
1237 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1238 # Some new commits in _dep
1239 echo "$_dep $_depchain"
1240 _ret=1
1245 # needs_update NAME
1246 # This function is recursive; it outputs reverse path from NAME
1247 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1248 # inner paths first. Innermost name can be :refs/remotes/<remote>/<name>
1249 # if the head is not in sync with the <remote> branch <name>, ':' if
1250 # the head is not in sync with the base (in this order of priority)
1251 # or '!' if dependency is missing. Note that the remote branch, base
1252 # order is reversed from the order they will actually be updated in
1253 # order to accomodate tg info which treats out-of-date items that are
1254 # only in the base as already being in the head for status purposes.
1255 # It will also return non-zero status if NAME needs update (seems backwards
1256 # but think of it as non-zero status if any non-missing output lines produced)
1257 # If needs_update() hits missing dependencies, it will append
1258 # them to space-separated $missing_deps list and skip them.
1259 needs_update()
1261 recurse_deps branch_needs_update "$1"
1264 # append second arg to first arg variable gluing with space if first already set
1265 vplus()
1267 eval "$1=\"\${$1:+\$$1 }\$2\""
1270 # true if whitespace separated first var name list contains second arg
1271 # use `vcontains 3 "value" "some list"` for a literal list
1272 vcontains()
1274 eval case "\" \${$1} \"" in '*" $2 "*) return 0; esac; return 1'
1277 # if the $1 var does not already contain $2 it's appended
1278 vsetadd()
1280 vcontains "$1" "$2" || vplus "$1" "$2"
1283 # reset needs_update_check results to empty
1284 needs_update_check_clear()
1286 unset_ needs_update_processed needs_update_behind needs_update_ahead needs_update_partial
1289 # needs_update_check NAME...
1291 # A faster version of needs_update that always succeeds
1292 # No output and unsuitable for actually performing updates themselves
1293 # If any of NAME... are NOT up-to-date AND they were not already processed
1294 # return status always will be zero however a simple check of
1295 # needs_update_behind after the call will answer the:
1296 # "are any out of date?": test -n "$needs_update_behind"
1297 # "is <x> out of date?": vcontains needs_update_behind "<x>"
1299 # Note that results are cumulative and "no_remotes" is honored as well as other
1300 # variables that modify recurse_deps_internal behavior. See the preceding
1301 # function to reset the results to empty when accumulation should start over.
1303 # Unlike needs_update, the branch names are themselves also checked to see if
1304 # they are out-of-date with respect to their bases or remote branches (not just
1305 # their remote bases). However, this can muddy some status results so this
1306 # can be disabled by setting needs_update_check_no_self to a non-empty value.
1308 # Unlike needs_update, here the remote base check is handled together with the
1309 # remote head check so if one is modified the other is too in the same way.
1311 # Dependencies are normally considered "behind" if they need an update from
1312 # their base or remote but this can be suppressed by setting the
1313 # needs_update_check_no_same to a non-empty value. This will NOT prevent
1314 # parents of those dependencies from still being considered behind in such a
1315 # case even though the dependency itself will not be. Note that setting
1316 # needs_update_check_no_same also implies needs_update_check_no_self.
1318 # The following whitespace-separated lists are updated with the results:
1320 # The "no_remotes" setting is obeyed but remote names themselves will never
1321 # appear in any of the lists
1323 # needs_update_processed
1324 # The branch names in here have been processed and will be skipped
1326 # needs_update_behind
1327 # Any branch named in here needs an update from one or more of its
1328 # direct or indirect dependencies (i.e. it's "out-of-date")
1330 # needs_update_ahead
1331 # Any branch named in here is NOT fully contained by at least one of
1332 # its dependents (i.e. it's a source of "out-of-date (aka dirty)"ness
1334 # needs_update_partial
1335 # Any branch names in here are either missing themselves or have one
1336 # or more detected missing dependencies (a completely missing remote
1337 # branch is never "detected")
1338 needs_update_check()
1340 # each head must be processed independently or else there will be
1341 # confusion about who's missing what and which branches actually are
1342 # out of date
1343 tmptgrdi="$tg_tmp_dir/tgrdi.$$"
1344 for nucname in "$@"; do
1345 ! vcontains needs_update_processed "$nucname" || continue
1346 # no need to fuss with recurse_deps, just use
1347 # recurse_deps_internal directly
1348 recurse_deps_internal -s -o=-1 "$nucname" >"$tmptgrdi"
1349 while read -r _rdi_m _rdi_t _rdi_l _rdi_v _rdi_node _rdi_parent _rdi_chain; do
1350 case "$_rdi_node" in ""|:*) continue; esac # empty or checked with remote
1351 vsetadd needs_update_processed "$_rdi_node"
1352 if [ "$_rdi_m" != "0" ]; then # missing
1353 vsetadd needs_update_partial "$_rdi_node"
1354 [ -z "$_rdi_parent" ] || vsetadd needs_update_partial "$_rdi_parent"
1355 continue
1357 [ "$_rdi_t$_rdi_l" != "12" ] || continue # always skip annihilated
1358 _rdi_dertee= # :)
1359 if [ -n "$_rdi_parent" ]; then # not a "self" line
1360 ! vcontains needs_update_partial "$_rdi_node" || vsetadd needs_update_partial "$_rdi_parent"
1361 ! vcontains needs_update_behind "$_rdi_node" || _rdi_dertee=2
1362 else
1363 [ -z "$needs_update_check_no_self$needs_update_check_no_same" ] || continue # skip self
1365 if [ -z "$_rdi_dertee" ]; then
1366 if [ "$_rdi_t" != "0" ]; then # tgish
1367 if branch_contains "refs/heads/$_rdi_node" "refs/$topbases/$_rdi_node"; then
1368 if [ "$_rdi_t" = "2" ]; then # will never be "2" when no_remotes is set
1369 branch_contains "refs/heads/$_rdi_node" "refs/remotes/$base_remote/$_rdi_node" &&
1370 branch_contains "refs/$topbases/$_rdi_node" "refs/remotes/$base_remote/${topbases#heads/}/$_rdi_node" ||
1371 _rdi_dertee=3
1373 else
1374 _rdi_dertee=3
1376 [ -z "$_rdi_dertee" ] || [ -n "$needs_update_check_no_same" ] || _rdi_dertee=1
1379 [ z"$_rdi_dertee" != z"1" ] || vsetadd needs_update_behind "$_rdi_node"
1380 [ -n "$_rdi_parent" ] || continue # self line
1381 if ! branch_contains "refs/$topbases/$_rdi_parent" "refs/heads/$_rdi_node"; then
1382 _rdi_dertee=1
1383 vsetadd needs_update_ahead "$_rdi_node"
1385 [ -z "$_rdi_dertee" ] || vsetadd needs_update_behind "$_rdi_parent"
1386 done <"$tmptgrdi"
1387 done
1390 # branch_empty NAME [-i | -w]
1391 branch_empty()
1393 if [ -z "$2" ]; then
1394 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1395 _result=
1396 _result_rev=
1397 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1398 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
1399 _result=0
1400 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1401 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1402 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1403 return $_result
1404 else
1405 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1409 v_get_tdmopt_internal()
1411 [ -n "$1" ] && [ -n "$3" ] || return 0
1412 [ "$2" = "-i" ] || [ "$2" = "-w" ] || return 0
1413 ensure_work_tree
1414 _optval=
1415 if v_verify_topgit_branch _tghead "HEAD" -f; then
1416 if [ "$2" = "-w" ] && [ -f "$root_dir/$3" ] && [ -r "$root_dir/$3" ]; then
1417 _opthash=
1418 if _opthash="$(git hash-object -w -t blob --stdin <"$root_dir/$3")" && [ -n "$_opthash" ]; then
1419 _optval="$4\"$_tghead:$_opthash\""
1421 elif [ "$2" = "-i" ]; then
1422 if _opthash="$(git rev-parse --quiet --verify ":0:$3" --)" && [ -n "$_opthash" ]; then
1423 _optval="$4\"$_tghead:$_opthash\""
1427 eval "$1="'"$_optval"'
1430 # set var $1 to the correct -td= option for use in an eval for $2 -i or -w mode
1431 v_get_tdopt() { v_get_tdmopt_internal "$1" "$2" ".topdeps" "-td="; }
1433 # set var $1 to the correct -tm= option for use in an eval for $2 -i or -w mode
1434 v_get_tmopt() { v_get_tdmopt_internal "$1" "$2" ".topmsg" "-tm="; }
1436 # checkout_symref_full [-f] FULLREF [SEED]
1437 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1438 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1439 # MUST be a committish which if present will be used instead of current FULLREF
1440 # (and FULLREF will be updated to it as well in that case)
1441 # Any merge state is always cleared by this function
1442 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1443 # instead of -m) but it will clear out any unmerged entries
1444 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1445 checkout_symref_full()
1447 _mode=-m
1448 _head="HEAD"
1449 if [ "$1" = "-f" ]; then
1450 _mode="--reset"
1451 _head=
1452 shift
1454 _ishash=
1455 case "$1" in
1456 refs/?*)
1458 $octet20)
1459 _ishash=1
1460 [ -z "$2" ] || [ "$1" = "$2" ] ||
1461 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1462 set -- HEAD "$1"
1465 die "programmer error: invalid checkout_symref_full \"$1\""
1467 esac
1468 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1469 die "invalid committish: \"${2:-$1}\""
1470 # Clear out any MERGE_HEAD kruft
1471 rm -f "$git_dir/MERGE_HEAD" || :
1472 # We have to do all the hard work ourselves :/
1473 # This is like git checkout -b "$1" "$2"
1474 # (or just git checkout "$1"),
1475 # but never creates a detached HEAD (unless $1 is a hash)
1476 git read-tree -u $_mode $_head "$_seedrev" &&
1478 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1479 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1480 } && {
1481 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1485 # switch_to_base NAME [SEED]
1486 switch_to_base()
1488 checkout_symref_full "refs/$topbases/$1" "$2"
1491 # run editor with arguments
1492 # the editor setting will be cached in $tg_editor (which is eval'd)
1493 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1494 # just in case, noalt_setup will be in effect while the editor is running
1495 run_editor()
1497 tg_editor="$GIT_EDITOR"
1498 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1500 noalt_setup
1501 eval "$tg_editor" '"$@"'
1505 # Show the help messages.
1506 do_help()
1508 _www=
1509 if [ "$1" = "-w" ]; then
1510 _www=1
1511 shift
1513 if [ -z "$1" ] ; then
1514 # This is currently invoked in all kinds of circumstances,
1515 # including when the user made a usage error. Should we end up
1516 # providing more than a short help message, then we should
1517 # differentiate.
1518 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1520 ## Build available commands list for help output
1522 cmds=
1523 sep=
1524 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1525 ! [ -r "$cmd" ] && continue
1526 # strip directory part and "tg-" prefix
1527 cmd="${cmd##*/}"
1528 cmd="${cmd#tg-}"
1529 [ "$cmd" != "migrate-bases" ] || continue
1530 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1531 cmds="$cmds$sep$cmd"
1532 sep="|"
1533 done
1535 echo "TopGit version $TG_VERSION - A different patch queue manager"
1536 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u]" \
1537 "[-c <name>=<val>] [--[no-]pager|-p] ($cmds) ..."
1538 echo " Or: $tgname help [-w] [<command>]"
1539 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1540 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1541 if [ -n "$_www" ]; then
1542 nohtml=
1543 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1544 echo "${0##*/}: missing html help file:" \
1545 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1546 nohtml=1
1548 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1549 echo "${0##*/}: missing html help file:" \
1550 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1551 nohtml=1
1553 if [ -n "$nohtml" ]; then
1554 echo "${0##*/}: use" \
1555 "\"${0##*/} help $1\" instead" 1>&2
1556 exit 1
1558 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1559 exit
1561 output()
1563 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1564 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1565 echo
1566 elif [ "$1" = "help" ]; then
1567 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1568 echo
1569 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1570 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1571 echo
1573 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1574 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1577 page output "$1"
1578 else
1579 echo "${0##*/}: no help for $1" 1>&2
1580 do_help
1581 exit 1
1585 check_status()
1587 git_state=
1588 git_remove=
1589 tg_state=
1590 tg_remove=
1591 tg_topmerge=
1592 setup_git_dir_is_bare
1593 [ -z "$git_dir_is_bare" ] || return 0
1595 if [ -e "$git_dir/MERGE_HEAD" ]; then
1596 git_state="merge"
1597 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1598 git_state="am"
1599 git_remove="$git_dir/rebase-apply"
1600 elif [ -e "$git_dir/rebase-apply" ]; then
1601 git_state="rebase"
1602 git_remove="$git_dir/rebase-apply"
1603 elif [ -e "$git_dir/rebase-merge" ]; then
1604 git_state="rebase"
1605 git_remove="$git_dir/rebase-merge"
1606 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1607 git_state="cherry-pick"
1608 elif [ -e "$git_dir/BISECT_LOG" ]; then
1609 git_state="bisect"
1610 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1611 git_state="revert"
1613 git_remove="${git_remove#./}"
1615 if [ -e "$git_dir/tg-update" ]; then
1616 tg_state="update"
1617 tg_remove="$git_dir/tg-update"
1618 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1620 tg_remove="${tg_remove#./}"
1623 # Show status information
1624 do_status()
1626 do_status_result=0
1627 do_status_verbose=
1628 do_status_help=
1629 abbrev=refs
1630 pfx=
1631 while [ $# -gt 0 ] && case "$1" in
1632 --help|-h)
1633 do_status_help=1
1634 break;;
1635 -vv)
1636 # kludge in this common bundling option
1637 abbrev=
1638 do_status_verbose=1
1639 pfx="## "
1641 --verbose|-v)
1642 [ -z "$do_status_verbose" ] || abbrev=
1643 do_status_verbose=1
1644 pfx="## "
1646 --exit-code)
1647 do_status_result=2
1650 die "unknown status argument: $1"
1652 esac; do shift; done
1653 if [ -n "$do_status_help" ]; then
1654 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1655 return
1657 check_status
1658 symref="$(git symbolic-ref --quiet HEAD)" || :
1659 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1660 if [ -n "$symref" ]; then
1661 uprefpart=
1662 if [ -n "$headrv" ]; then
1663 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1664 if [ -n "$upref" ]; then
1665 uprefpart=" ... ${upref#$abbrev/remotes/}"
1666 mbase="$(git merge-base HEAD "$upref")" || :
1667 ahead="$(git rev-list --count HEAD ${mbase:+--not $mbase})" || ahead=0
1668 behind="$(git rev-list --count "$upref" ${mbase:+--not $mbase})" || behind=0
1669 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1670 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1671 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1672 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1673 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1676 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1677 else
1678 echol "${pfx}HEAD -> ${headrv:-?}"
1680 if [ -n "$tg_state" ]; then
1681 extra=
1682 if [ "$tg_state" = "update" ]; then
1683 IFS= read -r uname <"$git_dir/tg-update/name" || :
1684 [ -z "$uname" ] ||
1685 extra="; currently updating branch '$uname'"
1687 echol "${pfx}tg $tg_state in progress$extra"
1688 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1689 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1690 cat "$git_dir/tg-update/fullcmd"
1691 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1692 if [ $bcnt -gt 1 ]; then
1693 pcnt=0
1694 ! [ -s "$git_dir/tg-update/processed" ] ||
1695 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1696 echo "${pfx}$pcnt of $bcnt branches updated so far"
1699 if [ "$tg_state" = "update" ]; then
1700 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1701 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1702 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1703 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1706 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1707 if [ "$git_state" = "merge" ]; then
1708 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1709 if [ $ucnt -gt 0 ]; then
1710 echo "${pfx}"'fix conflicts and then "git commit" the result'
1711 else
1712 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1715 if [ -z "$git_state" ]; then
1716 setup_git_dir_is_bare
1717 [ -z "$git_dir_is_bare" ] || return 0
1718 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository???
1719 gspcnt=0
1720 [ -z "$gsp" ] ||
1721 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1722 untr=
1723 if [ "$gspcnt" -eq 0 ]; then
1724 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1725 echo "${pfx}working directory is clean$untr"
1726 [ -n "$tg_state" ] || do_status_result=0
1727 else
1728 echo "${pfx}working directory is DIRTY"
1729 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1734 ## Pager stuff
1736 # isatty FD
1737 isatty()
1739 test -t $1
1742 # pass "diff" to get pager.diff
1743 # if pager.$1 is a boolean false returns cat
1744 # if set to true or unset fails
1745 # otherwise succeeds and returns the value
1746 get_pager()
1748 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1749 [ "$_x" != "true" ] || return 1
1750 echo "cat"
1751 return 0
1753 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1754 echol "$_x"
1755 return 0
1757 return 1
1760 # setup_pager
1761 # Set TG_PAGER to a valid executable
1762 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1763 # See also the following "page" function for ease of use
1764 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1765 # Preference is (same as Git):
1766 # 1. GIT_PAGER
1767 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1768 # 3. core.pager (only if set)
1769 # 4. PAGER
1770 # 5. git var GIT_PAGER
1771 # 6. less
1772 setup_pager()
1774 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1776 emptypager=
1777 if [ -z "$TG_PAGER_IN_USE" ]; then
1778 # TG_PAGER = GIT_PAGER | PAGER | less
1779 # NOTE: GIT_PAGER='' is significant
1780 if [ -n "${GIT_PAGER+set}" ]; then
1781 TG_PAGER="$GIT_PAGER"
1782 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1783 TG_PAGER="$_dp"
1784 elif _cp="$(git config core.pager 2>/dev/null)"; then
1785 TG_PAGER="$_cp"
1786 elif [ -n "${PAGER+set}" ]; then
1787 TG_PAGER="$PAGER"
1788 else
1789 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1790 [ "$_gp" != ":" ] || _gp=
1791 TG_PAGER="${_gp:-less}"
1793 if [ -z "$TG_PAGER" ]; then
1794 emptypager=1
1795 TG_PAGER=cat
1797 else
1798 emptypager=1
1799 TG_PAGER=cat
1802 # Set pager default environment variables
1803 # see pager.c:setup_pager
1804 if [ -z "${LESS+set}" ]; then
1805 LESS="-FRX"
1806 export LESS
1808 if [ -z "${LV+set}" ]; then
1809 LV="-c"
1810 export LV
1813 # this is needed so e.g. $(git diff) will still colorize it's output if
1814 # requested in ~/.gitconfig with color.diff=auto
1815 GIT_PAGER_IN_USE=1
1816 export GIT_PAGER_IN_USE
1818 # this is needed so we don't get nested pagers
1819 TG_PAGER_IN_USE=1
1820 export TG_PAGER_IN_USE
1823 # page eval_arg [arg ...]
1825 # Calls setup_pager then evals the first argument passing it all the rest
1826 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1827 # by setup_pager (in which case the output is left as-is).
1829 # To handle arbitrary paging duties, collect lines to be paged into a
1830 # function and then call page with the function name or perhaps func_name "$@".
1832 # If no arguments at all are passed in do nothing (return with success).
1833 page()
1835 [ $# -gt 0 ] || return 0
1836 setup_pager
1837 _evalarg="$1"; shift
1838 if [ -n "$emptypager" ]; then
1839 eval "$_evalarg" '"$@"'
1840 else
1841 { eval "$_evalarg" '"$@"';} | eval "$TG_PAGER"
1845 # get_temp NAME [-d]
1846 # creates a new temporary file (or directory with -d) in the global
1847 # temporary directory $tg_tmp_dir with pattern prefix NAME
1848 get_temp()
1850 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1853 # automatically called by strftime
1854 # does nothing if already setup
1855 # may be called explicitly if the first call would otherwise be in a subshell
1856 # so that the setup is only done once before subshells start being spawned
1857 setup_strftime()
1859 [ -z "$strftime_is_setup" ] || return 0
1861 # date option to format raw epoch seconds values
1862 daterawopt=
1863 _testes='951807788'
1864 _testdt='2000-02-29 07:03:08 UTC'
1865 _testfm='%Y-%m-%d %H:%M:%S %Z'
1866 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1867 daterawopt='-d@'
1868 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1869 daterawopt='-r'
1871 strftime_is_setup=1
1874 # $1 => strftime format string to use
1875 # $2 => raw timestamp as seconds since epoch
1876 # $3 => optional time zone string (empty/absent for local time zone)
1877 strftime()
1879 setup_strftime
1880 if [ -n "$daterawopt" ]; then
1881 if [ -n "$3" ]; then
1882 TZ="$3" date "$daterawopt$2" "+$1"
1883 else
1884 date "$daterawopt$2" "+$1"
1886 else
1887 if [ -n "$3" ]; then
1888 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1889 else
1890 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1895 got_cdup_result=
1896 git_cdup_result=
1897 v_get_show_cdup()
1899 if [ -z "$got_cdup_result" ]; then
1900 git_cdup_result="$(git rev-parse --show-cdup)"
1901 got_cdup_result=1
1903 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1906 setup_git_dir_is_bare()
1908 if [ -z "$git_dir_is_bare_setup" ]; then
1909 git_dir_is_bare="$(git rev-parse --is-bare-repository)"
1910 [ z"$git_dir_is_bare" = z"true" ] || git_dir_is_bare=
1911 git_dir_is_bare_setup=1
1915 setup_git_dirs()
1917 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1918 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1919 git_dir="$(cd "$git_dir" && pwd)"
1921 if [ -z "$git_common_dir" ]; then
1922 if vcmp "$git_version" '>=' "2.5"; then
1923 # rev-parse --git-common-dir is broken and may give
1924 # an incorrect result unless the current directory is
1925 # already set to the top level directory
1926 v_get_show_cdup
1927 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1928 else
1929 git_common_dir="$git_dir"
1932 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1933 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1934 git_hooks_dir="$git_common_dir/hooks"
1935 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1936 case "$gchp" in
1937 /[!/]*)
1938 git_hooks_dir="$gchp"
1941 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1943 esac
1944 unset_ gchp
1948 basic_setup_remote()
1950 if [ -z "$base_remote" ]; then
1951 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
1952 base_remote="$TG_EXPLICIT_REMOTE"
1953 else
1954 base_remote="$(git config topgit.remote 2>/dev/null)" || :
1959 basic_setup()
1961 setup_git_dirs $1
1962 basic_setup_remote
1963 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1964 tgnosequester=
1965 [ "$tgsequester" != "false" ] || tgnosequester=1
1966 unset_ tgsequester
1968 # catch errors if topbases is used without being set
1969 unset_ tg_topbases_set
1970 topbases="programmer*:error"
1971 topbasesrx="programmer*:error}"
1972 oldbases="$topbases"
1975 ## Initial setup
1976 initial_setup()
1978 # suppress the merge log editor feature since git 1.7.10
1980 GIT_MERGE_AUTOEDIT=no
1981 export GIT_MERGE_AUTOEDIT
1983 basic_setup $1
1984 iowopt=
1985 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
1986 gcfbopt=
1987 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
1988 auhopt=
1989 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1990 v_get_show_cdup root_dir
1991 root_dir="${root_dir:-.}"
1992 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1993 [ "$logrefupdates" = "true" ] || logrefupdates=
1995 # make sure root_dir doesn't end with a trailing slash.
1997 root_dir="${root_dir%/}"
1999 # create global temporary directories, inside GIT_DIR
2001 if [ -n "$TG_TMPDIR" ] && [ -d "$TG_TMPDIR" ] && [ -w "$TG_TMPDIR" ] &&
2002 { >"$TG_TMPDIR/.check"; } >/dev/null 2>&1; then
2003 tg_tmp_dir="$TG_TMPDIR"
2004 else
2005 tg_tmp_dir=
2006 TRAPEXIT_='${TG_DEBUG:+echo} rm -rf "$tg_tmp_dir" >&2'
2007 trap 'trapexit_ 129' HUP
2008 trap 'trapexit_ 130' INT
2009 trap 'trapexit_ 131' QUIT
2010 trap 'trapexit_ 134' ABRT
2011 trap 'trapexit_ 141' PIPE
2012 trap 'trapexit_ 143' TERM
2013 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2014 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2015 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
2016 [ -z "$tg_tmp_dir" ] || tg_tmp_dir="$(cd "$tg_tmp_dir" && pwd -P)"
2018 unset_ TG_TMPDIR
2019 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
2020 tg_ref_cache_br="$tg_ref_cache.br"
2021 tg_ref_cache_rbr="$tg_ref_cache.rbr"
2022 tg_ref_cache_ann="$tg_ref_cache.ann"
2023 tg_ref_cache_dep="$tg_ref_cache.dep"
2024 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_ref_cache"; } >/dev/null 2>&1 ||
2025 die "could not create a writable temporary directory"
2027 # make sure global cache directory exists inside GIT_DIR or $tg_tmp_dir
2029 user_id_no="$(id -u)" || :
2030 : "${user_id_no:=_99_}"
2031 tg_cache_dir="$git_common_dir/tg-cache"
2032 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2033 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
2034 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2035 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2036 if [ -z "$tg_cache_dir" ]; then
2037 tg_cache_dir="$tg_tmp_dir/tg-cache"
2038 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
2039 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
2041 [ -n "$tg_cache_dir" ] ||
2042 die "could not create a writable tg-cache directory (even a temporary one)"
2044 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
2045 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
2046 # so we avoid it if possible and require v2.11.1 to do it at all
2047 # otherwise just don't make an alternates temporary store in that case;
2048 # it's okay to not have one; everything will still work; the nicety of
2049 # making the temporary tree objects vanish when tg exits just won't
2050 # happen in that case but nothing will break also be sure to reuse
2051 # the parent's if we've been recursively invoked and it's for the
2052 # same repository we were invoked on
2054 tg_use_alt_odb=1
2055 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
2056 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] || tg_use_alt_odb=
2057 _fulltmpdir=
2058 [ -z "$tg_use_alt_odb" ] || _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
2059 case "$_fulltmpdir" in *[";:"]*|'"'*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
2060 _fullodbdir=
2061 [ -z "$tg_use_alt_odb" ] || _fullodbdir="$(cd "$_odbdir" && pwd -P)"
2062 if [ -n "$tg_use_alt_odb" ] && [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
2063 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
2064 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
2065 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
2066 tg_use_alt_odb=2
2069 if [ "$tg_use_alt_odb" = "1" ]; then
2070 # create an alternate objects database to keep the ephemeral objects in
2071 mkdir -p "$tg_tmp_dir/objects/info"
2072 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
2073 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
2074 case "$TG_OBJECT_DIRECTORY" in
2075 *[";:"]*|'"'*)
2076 # surround in "..." and backslash-escape internal '"' and '\\'
2077 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
2078 sed 's/\([""\\]\)/\\\1/g')\""
2081 _altodbdq="$TG_OBJECT_DIRECTORY"
2083 esac
2084 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2085 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2086 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
2087 else
2088 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
2090 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
2091 if [ -n "$GIT_OBJECT_DIRECTORY" ]; then
2092 export GIT_OBJECT_DIRECTORY
2093 else
2094 unset_ GIT_OBJECT_DIRECTORY
2099 noalt_setup()
2101 if [ "${TG_PRESERVED_ALTERNATES+set}" = "set" ]; then
2102 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
2103 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
2104 export GIT_ALTERNATE_OBJECT_DIRECTORIES
2105 else
2106 unset_ GIT_ALTERNATE_OBJECT_DIRECTORIES
2109 unset_ TG_TMPDIR TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES tg_use_alt_odb
2112 set_topbases()
2114 # refer to "top-bases" in a refname with $topbases
2116 [ -z "$tg_topbases_set" ] || return 0
2118 topbases_implicit_default=1
2119 # See if topgit.top-bases is set to heads or refs
2120 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
2121 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
2122 if [ -n "$1" ]; then
2123 # never die on the hook script
2124 unset_ tgtb
2125 else
2126 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
2129 if [ -n "$tgtb" ]; then
2130 case "$tgtb" in
2131 heads)
2132 topbases="heads/{top-bases}"
2133 topbasesrx="heads/[{]top-bases[}]"
2134 oldbases="top-bases";;
2135 refs)
2136 topbases="top-bases"
2137 topbasesrx="top-bases"
2138 oldbases="heads/{top-bases}";;
2139 esac
2140 # MUST NOT be exported
2141 unset_ tgtb tg_topbases_set topbases_implicit_default
2142 tg_topbases_set=1
2143 return 0
2145 unset_ tgtb
2147 # check heads and top-bases and see what state the current
2148 # repository is in. remotes are ignored.
2150 rc=0 activebases=
2151 activebases="$(
2152 git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null |
2153 run_awk_ref_prefixes ${1:+-e} -n -- "refs/heads/{top-bases}" "refs/top-bases" "refs/heads")" ||
2154 rc=$?
2155 if [ "$rc" = "65" ]; then
2156 # Complain and die
2157 err "repository contains existing TopGit branches"
2158 err "but some use refs/top-bases/... for the base"
2159 err "and some use refs/heads/{top-bases}/... for the base"
2160 err "with the latter being the new, preferred location"
2161 err "set \"topgit.top-bases\" to either \"heads\" to use"
2162 err "the new heads/{top-bases} location or \"refs\" to use"
2163 err "the old top-bases location."
2164 err "(the tg migrate-bases command can also resolve this issue)"
2165 die "schizophrenic repository requires topgit.top-bases setting"
2167 [ -z "$activebases" ] || unset_ topbases_implicit_default
2168 if [ "$activebases" = "refs/heads/{top-bases}" ]; then
2169 topbases="heads/{top-bases}"
2170 topbasesrx="heads/[{]top-bases[}]"
2171 oldbases="top-bases"
2172 else
2173 # default is still top-bases for now
2174 topbases="top-bases"
2175 topbasesrx="top-bases"
2176 oldbases="heads/{top-bases}"
2178 # MUST NOT be exported
2179 unset_ rc activebases tg_topases_set
2180 tg_topbases_set=1
2181 return 0
2184 # $1 is remote name to check
2185 # $2 is optional variable name to set to result of check
2186 # $3 is optional command name to use in message (defaults to $cmd)
2187 # Fatal error if remote has schizophrenic top-bases
2188 # No error (and $2, if provided, will be set to empty) if remote has no top-bases at all
2189 check_remote_topbases()
2191 [ -n "$1" ] || die "programmer error: check_remote_topbases called with no remote argument"
2192 _crrc=0 _crremotebases=
2193 _crremotebases="$(
2194 git for-each-ref --format='%(refname)' "refs/remotes/$1" 2>/dev/null |
2195 run_awk_ref_prefixes -n -- "refs/remotes/$1/{top-bases}" "refs/remotes/$1/top-bases" "refs/remotes/$1")" ||
2196 _crrc=$?
2197 if [ "$_crrc" = "65" ]; then
2198 err "remote \"$1\" has top-bases in both locations:"
2199 err " refs/remotes/$1/{top-bases}/..."
2200 err " refs/remotes/$1/top-bases/..."
2201 err "set \"topgit.top-bases\" to \"heads\" for the first, preferred location"
2202 err "or set \"topgit.top-bases\" to \"refs\" for the second, old location"
2203 err "(the \"-c topgit.top-bases=<val>\" option can be used for this)"
2204 err "then re-run the tg ${3:-$cmd} command"
2205 err "(the tg migrate-bases command can also help with this problem)"
2206 die "schizophrenic remote \"$1\" requires topgit.top-bases setting"
2208 [ "$_crrc" != "66" ] || _crremotebases= # just to be sure
2209 [ -z "$2" ] || eval "$2="'"$_crremotebases"'
2210 unset _crrc _crremotebases
2211 return 0
2214 # init_reflog "ref"
2215 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
2216 # an empty log file to exist so that ref changes will be logged
2217 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
2218 # However, if "$1" is "refs/tgstash" then always make the reflog
2219 # The only ref not under refs/ that Git will write a reflog for is HEAD;
2220 # no matter what, it will NOT update a reflog for any other bare refs so
2221 # just quietly succeed when passed TG_STASH without doing anything.
2222 init_reflog()
2224 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
2225 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
2226 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
2227 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
2228 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
2231 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
2232 # a symbolic link. The directory part must exist, but the basename need not.
2233 v_get_abs_path()
2235 [ -n "$1" ] && [ -n "$2" ] || return 1
2236 set -- "$1" "$2" "${2%/}"
2237 case "$3" in
2238 */*) set -- "$1" "$2" "${3%/*}";;
2239 * ) set -- "$1" "$2" ".";;
2240 esac
2241 case "$2" in */)
2242 set -- "$1" "${2%/}" "$3" "/"
2243 esac
2244 [ -d "$3" ] || return 1
2245 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
2248 ## Startup
2250 : "${TG_INST_CMDDIR:=@cmddir@}"
2251 : "${TG_INST_SHAREDIR:=@sharedir@}"
2252 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
2254 [ -d "$TG_INST_CMDDIR" ] ||
2255 die "No command directory: '$TG_INST_CMDDIR'"
2257 ## Include awk scripts and their utility functions (separated for easier debugging)
2259 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
2260 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
2261 . "$TG_INST_CMDDIR/tg--awksome"
2263 if [ -n "$tg__include" ]; then
2265 # We were sourced from another script for our utility functions;
2266 # this is set by hooks. Skip the rest of the file. A simple return doesn't
2267 # work as expected in every shell. See http://bugs.debian.org/516188
2269 # ensure setup happens
2271 initial_setup 1
2272 set_topbases 1
2273 noalt_setup
2275 else
2277 set -e
2279 tgbin="$0"
2280 tgdir="${tgbin%/}"
2281 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
2282 tgdir="${tgdir%/*}/"
2283 tgname="${tgbin##*/}"
2284 [ "$0" != "$tgname" ] || tgdir=""
2286 # If tg contains a '/' but does not start with one then replace it with an absolute path
2288 case "$0" in /*) ;; */*)
2289 tgdir="$(cd "${0%/*}" && pwd -P)/"
2290 tgbin="$tgdir$tgname"
2291 esac
2293 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
2294 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2296 tgdisplaydir="$tgdir"
2297 tgdisplay="$tgbin"
2298 tgdisplayac="$tgdisplay"
2300 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2301 _tgabs="$_tgnameabs" &&
2302 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2303 [ "$_tgabs" = "$_tgnameabs" ]
2304 then
2305 tgdisplaydir=""
2306 tgdisplay="$tgname"
2307 tgdisplayac="$tgdisplay"
2309 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2310 unset_ _tgabs _tgnameabs
2312 tg() (
2313 TG_TMPDIR="$tg_tmp_dir" && export TG_TMPDIR &&
2314 exec "$tgbin" "$@"
2317 explicit_remote=
2318 explicit_dir=
2319 gitcdopt=
2320 noremote=
2321 forcepager=
2323 cmd=
2324 while :; do case "$1" in
2326 help|--help|-h)
2327 cmd=help
2328 shift
2329 break;;
2331 status|--status)
2332 cmd=status
2333 shift
2334 break;;
2336 --hooks-path)
2337 cmd=hooks-path
2338 shift
2339 break;;
2341 --exec-path)
2342 cmd=exec-path
2343 shift
2344 break;;
2346 --awk-path)
2347 cmd=awk-path
2348 shift
2349 break;;
2351 --top-bases)
2352 cmd=top-bases
2353 shift
2354 break;;
2356 --no-pager)
2357 forcepager=0
2358 shift;;
2360 --pager|-p)
2361 forcepager=1
2362 shift;;
2365 shift
2366 if [ -z "$1" ]; then
2367 echo "Option -r requires an argument." >&2
2368 do_help
2369 exit 1
2371 unset_ noremote
2372 base_remote="$1"
2373 explicit_remote="$base_remote"
2374 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2375 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2376 shift;;
2379 unset_ base_remote explicit_remote
2380 noremote=1
2381 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2382 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2383 shift;;
2386 shift
2387 if [ -z "$1" ]; then
2388 echo "Option -C requires an argument." >&2
2389 do_help
2390 exit 1
2392 cd "$1"
2393 unset_ GIT_DIR GIT_COMMON_DIR
2394 if [ -z "$explicit_dir" ]; then
2395 explicit_dir="$1"
2396 else
2397 explicit_dir="$PWD"
2399 gitcdopt=" -C \"$explicit_dir\""
2400 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2401 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2402 tgdisplayac="$tgdisplay"
2403 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2404 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2405 shift;;
2408 shift
2409 if [ -z "$1" ]; then
2410 echo "Option -c requires an argument." >&2
2411 do_help
2412 exit 1
2414 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2415 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2416 export GIT_CONFIG_PARAMETERS
2417 shift;;
2420 shift
2421 break;;
2424 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2425 do_help
2426 exit 1;;
2429 break;;
2431 esac; done
2432 if [ z"$forcepager" = z"0" ]; then
2433 GIT_PAGER_IN_USE=1 TG_PAGER_IN_USE=1 &&
2434 export GIT_PAGER_IN_USE TG_PAGER_IN_USE
2437 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
2439 ## Dispatch
2441 [ -n "$cmd" ] || { do_help; exit 1; }
2443 case "$cmd" in
2445 help)
2446 do_help "$@"
2447 exit 0;;
2449 status|st)
2450 unset_ base_remote
2451 basic_setup
2452 set_topbases
2453 do_status "$@"
2454 exit ${do_status_result:-0};;
2456 hooks-path)
2457 # Internal command
2458 echol "$TG_INST_HOOKSDIR";;
2460 exec-path)
2461 # Internal command
2462 echol "$TG_INST_CMDDIR";;
2464 awk-path)
2465 # Internal command
2466 echol "$TG_INST_CMDDIR/awk";;
2468 top-bases)
2469 # Maintenance command
2470 do_topbases_help=
2471 show_remote_topbases=
2472 case "$1" in
2473 --help|-h)
2474 do_topbases_help=0;;
2475 -r|--remote)
2476 if [ $# -eq 2 ] && [ -n "$2" ]; then
2477 # unadvertised, but make it work
2478 base_remote="$2"
2479 shift
2481 show_remote_topbases=1;;
2483 [ $# -eq 0 ] || do_topbases_help=1;;
2484 esac
2485 [ $# -le 1 ] || do_topbases_help=1
2486 if [ -n "$do_topbases_help" ]; then
2487 helpcmd='echo "Usage: ${tgname:-tg} [-r <remote>] --top-bases [-r]"'
2488 [ $do_topbases_help -eq 0 ] || helpcmd="$helpcmd >&2"
2489 eval "$helpcmd"
2490 exit $do_topbases_help
2492 git_dir=
2493 ! git_dir="$(git rev-parse --git-dir 2>&1)" || setup_git_dirs
2494 set_topbases
2495 if [ -n "$show_remote_topbases" ]; then
2496 basic_setup_remote
2497 [ -n "$base_remote" ] ||
2498 die "no remote location given. Either use -r <remote> option or set topgit.remote"
2499 rbases=
2500 [ -z "$topbases_implicit_default" ] ||
2501 check_remote_topbases "$base_remote" rbases "--top-bases"
2502 if [ -n "$rbases" ]; then
2503 echol "$rbases"
2504 else
2505 echol "refs/remotes/$base_remote/${topbases#heads/}"
2507 else
2508 echol "refs/$topbases"
2509 fi;;
2512 isutil=
2513 case "$cmd" in index-merge-one-file)
2514 isutil="-"
2515 esac
2516 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2517 looplevel="$TG_ALIAS_DEPTH"
2518 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2519 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2520 looplevel=0
2521 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2522 [ -n "$tgalias" ] || {
2523 echo "Unknown subcommand: $cmd" >&2
2524 do_help
2525 exit 1
2527 looplevel=$(( $looplevel + 1 ))
2528 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2529 TG_ALIAS_DEPTH="$looplevel"
2530 export TG_ALIAS_DEPTH
2531 if [ "!${tgalias#?}" = "$tgalias" ]; then
2532 unset_ GIT_PREFIX
2533 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2534 GIT_PREFIX="$pfx"
2535 export GIT_PREFIX
2537 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2538 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2539 else
2540 eval 'exec "$tgbin"' "$tgalias" '"$@"'
2542 die "alias execution failed for: $tgalias"
2544 unset_ TG_ALIAS_DEPTH
2546 showing_help=
2547 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2548 showing_help=1
2551 [ -n "$showing_help" ] || initial_setup
2552 [ -z "$noremote" ] || unset_ base_remote
2554 nomergesetup="$showing_help"
2555 case "$cmd" in base|contains|files|info|log|mail|next|patch|prev|rebase|revert|summary|tag)
2556 # avoid merge setup where not necessary
2558 nomergesetup=1
2559 esac
2561 if [ -z "$nomergesetup" ]; then
2562 # make sure merging the .top* files will always behave sanely
2564 setup_ours
2565 setup_hook "pre-commit"
2568 # everything but rebase needs topbases set
2569 carefully="$showing_help"
2570 [ "$cmd" != "migrate-bases" ] || carefully=1
2571 [ "$cmd" = "rebase" ] || set_topbases $carefully
2573 _use_ref_cache=
2574 tg_read_only=1
2575 _suppress_alt=
2576 case "$cmd$showing_help" in
2577 contains|info|summary|tag)
2578 _use_ref_cache=1;;
2579 "export")
2580 _use_ref_cache=1
2581 _suppress_alt=1;;
2582 annihilate|create|delete|depend|import|update)
2583 tg_read_only=
2584 _suppress_alt=1;;
2585 esac
2586 [ -z "$_suppress_alt" ] || noalt_setup
2587 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2589 fullcmd="${tgname:-tg} $cmd $*"
2590 if [ z"$forcepager" = z"1" ]; then
2591 page '. "$TG_INST_CMDDIR"/tg-$isutil$cmd' "$@"
2592 else
2593 . "$TG_INST_CMDDIR"/tg-$isutil$cmd
2594 fi;;
2595 esac