tg-info.sh: support --deps and --dependents options
[topgit/pro.git] / tg.sh
blob8bce289ae3406b25ca94e86378801d6e650d6ff2
1 #!/bin/sh
2 # TopGit - A different patch queue manager
3 # Copyright (C) Petr Baudis <pasky@suse.cz> 2008
4 # Copyright (C) Kyle J. McKay <mackyle@gmail.com> 2014,2015,2016
5 # All rights reserved.
6 # GPLv2
8 TG_VERSION=0.19.7
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"
20 mtblob="e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
21 tab=' '
22 lf='
25 ## Auxiliary functions
27 # Preserves current $? value while triggering a non-zero set -e exit if active
28 # This works even for shells that sometimes fail to correctly trigger a -e exit
29 check_exit_code()
31 return $?
34 # This is the POSIX equivalent of which
35 cmd_path()
37 { "unset" -f command unset unalias "$1"; } >/dev/null 2>&1 || :
38 { "unalias" -a; } >/dev/null 2>&1 || :
39 command -v "$1"
42 # helper for wrappers
43 # note deliberate use of '(' ... ')' rather than '{' ... '}'
44 exec_lc_all_c()
46 LC_ALL="C" &&
47 export LC_ALL &&
48 exec "$@"
51 # These tools work better for us with LC_ALL=C and by using these little
52 # convenience functions LC_ALL=C does not have to appear in the code but
53 # any Git translations will still appear for Git commands
54 awk() { exec_lc_all_c @AWK_PATH@ "$@"; }
55 cat() { exec_lc_all_c cat "$@"; }
56 cut() { exec_lc_all_c cut "$@"; }
57 find() { exec_lc_all_c find "$@"; }
58 grep() { exec_lc_all_c grep "$@"; }
59 join() { exec_lc_all_c join "$@"; }
60 paste() { exec_lc_all_c paste "$@"; }
61 sed() { exec_lc_all_c sed "$@"; }
62 sort() { exec_lc_all_c sort "$@"; }
63 tr() { exec_lc_all_c tr "$@"; }
64 wc() { exec_lc_all_c wc "$@"; }
65 xargs() { exec_lc_all_c xargs "$@"; }
67 # Output arguments without any possible interpretation
68 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
69 echol()
71 printf '%s\n' "$*"
74 info()
76 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
79 warn()
81 info "warning: $*" >&2
84 err()
86 info "error: $*" >&2
89 die()
91 info "fatal: $*" >&2
92 exit 1
95 # shift off first arg then return "$*" properly quoted in single-quotes
96 # if $1 was '' output goes to stdout otherwise it's assigned to $1
97 # the final \n, if any, is omitted from the result but any others are included
98 v_quotearg()
100 _quotearg_v="$1"
101 shift
102 set -- "$_quotearg_v" \
103 "sed \"s/'/'\\\\\\''/g;1s/^/'/;\\\$s/\\\$/'/;s/'''/'/g;1s/^''\\(.\\)/\\1/\"" "$*"
104 unset _quotearg_v
105 if [ -z "$3" ]; then
106 if [ -z "$1" ]; then
107 echo "''"
108 else
109 eval "$1=\"''\""
111 else
112 if [ -z "$1" ]; then
113 printf "%s$4" "$3" | eval "$2"
114 else
115 eval "$1="'"$(printf "%s$4" "$3" | eval "$2")"'
120 # same as v_quotearg except there's no extra $1 so output always goes to stdout
121 quotearg()
123 v_quotearg '' "$@"
126 vcmp()
128 # Compare $1 to $3 each of which must match ^[^0-9]*\d*(\.\d*)*.*$
129 # where only the "\d*" parts in the regex participate in the comparison
130 # Since EVERY string matches that regex this function is easy to use
131 # An empty string ('') for $1 or $3 or any "\d*" part is treated as 0
132 # $2 is a compare op '<', '<=', '=', '==', '!=', '>=', '>'
133 # Return code is 0 for true, 1 for false (or unknown compare op)
134 # There is NO difference in behavior between '=' and '=='
135 # Note that "vcmp 1.8 == 1.8.0.0.0.0" correctly returns 0
136 set -- "$1" "$2" "$3" "${1%%[0-9]*}" "${3%%[0-9]*}"
137 set -- "${1#"$4"}" "$2" "${3#"$5"}"
138 set -- "${1%%[!0-9.]*}" "$2" "${3%%[!0-9.]*}"
139 while
140 vcmp_a_="${1%%.*}"
141 vcmp_b_="${3%%.*}"
142 [ "z$vcmp_a_" != "z" -o "z$vcmp_b_" != "z" ]
144 if [ "${vcmp_a_:-0}" -lt "${vcmp_b_:-0}" ]; then
145 unset vcmp_a_ vcmp_b_
146 case "$2" in "<"|"<="|"!=") return 0; esac
147 return 1
148 elif [ "${vcmp_a_:-0}" -gt "${vcmp_b_:-0}" ]; then
149 unset vcmp_a_ vcmp_b_
150 case "$2" in ">"|">="|"!=") return 0; esac
151 return 1;
153 vcmp_a_="${1#$vcmp_a_}"
154 vcmp_b_="${3#$vcmp_b_}"
155 set -- "${vcmp_a_#.}" "$2" "${vcmp_b_#.}"
156 done
157 unset vcmp_a_ vcmp_b_
158 case "$2" in "="|"=="|"<="|">=") return 0; esac
159 return 1
162 precheck() {
163 if ! git_version="$(git version)"; then
164 die "'git version' failed"
166 case "$git_version" in [Gg]"it version "*);;*)
167 die "'git version' output does not start with 'git version '"
168 esac
170 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
171 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
174 case "$1" in version|--version|-V)
175 echo "TopGit version $TG_VERSION"
176 exit 0
177 esac
179 precheck
180 [ "$1" = "precheck" ] && exit 0
183 cat_depsmsg_internal()
185 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
186 if [ -s "$tg_cache_dir/refs/heads/$1/.$2" ]; then
187 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
188 _line=
189 while IFS= read -r _line || [ -n "$_line" ]; do
190 printf '%s\n' "$_line"
191 done
192 return 0
193 fi <"$tg_cache_dir/refs/heads/$1/.$2"
195 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null || :
196 if [ -d "$tg_cache_dir/refs/heads/$1" ]; then
197 printf '%s\n' "$_rev" >"$tg_cache_dir/refs/heads/$1/.$2"
198 _line=
199 git cat-file blob "$_rev:.$2" 2>/dev/null |
200 while IFS= read -r _line || [ -n "$_line" ]; do
201 printf '%s\n' "$_line" >&3
202 printf '%s\n' "$_line"
203 done 3>>"$tg_cache_dir/refs/heads/$1/.$2"
204 else
205 git cat-file blob "$_rev:.$2" 2>/dev/null
209 # cat_deps BRANCHNAME
210 # Caches result
211 cat_deps()
213 cat_depsmsg_internal "$1" topdeps
216 # cat_msg BRANCHNAME
217 # Caches result
218 cat_msg()
220 cat_depsmsg_internal "$1" topmsg
223 # cat_file TOPIC:PATH [FROM]
224 # cat the file PATH from branch TOPIC when FROM is empty.
225 # FROM can be -i or -w, than the file will be from the index or worktree,
226 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
227 cat_file()
229 path="$1"
230 case "$2" in
232 cat "$root_dir/${path#*:}"
235 # ':file' means cat from index
236 git cat-file blob ":${path#*:}" 2>/dev/null
239 case "$path" in
240 refs/heads/*:.topdeps)
241 _temp="${path%:.topdeps}"
242 cat_deps "${_temp#refs/heads/}"
244 refs/heads/*:.topmsg)
245 _temp="${path%:.topmsg}"
246 cat_msg "${_temp#refs/heads/}"
249 git cat-file blob "$path" 2>/dev/null
251 esac
254 die "Wrong argument to cat_file: '$2'"
256 esac
259 # if use_alt_temp_odb and tg_use_alt_odb are true try to write the object(s)
260 # into the temporary alt odb area instead of the usual location
261 git_temp_alt_odb_cmd()
263 if [ -n "$use_alt_temp_odb" ] && [ -n "$tg_use_alt_odb" ] &&
264 [ -n "$TG_OBJECT_DIRECTORY" ] &&
265 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
267 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
268 GIT_OBJECT_DIRECTORY="$TG_OBJECT_DIRECTORY"
269 unset TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES
270 export GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
271 git "$@"
273 else
274 git "$@"
278 git_write_tree() { git_temp_alt_odb_cmd write-tree "$@"; }
279 git_mktree() { git_temp_alt_odb_cmd mktree "$@"; }
281 # get tree for the committed topic
282 get_tree_()
284 echo "refs/heads/$1"
287 # get tree for the base
288 get_tree_b()
290 echo "refs/$topbases/$1"
293 # get tree for the index
294 get_tree_i()
296 git_write_tree
299 # get tree for the worktree
300 get_tree_w()
302 i_tree=$(git_write_tree)
304 # the file for --index-output needs to sit next to the
305 # current index file
306 cd "$root_dir"
307 : ${GIT_INDEX_FILE:="$git_dir/index"}
308 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
309 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
310 GIT_INDEX_FILE="$TMP_INDEX" &&
311 export GIT_INDEX_FILE &&
312 git diff --name-only -z HEAD |
313 git update-index -z --add --remove --stdin &&
314 git_write_tree &&
315 rm -f "$TMP_INDEX"
319 # get tree for arbitrary ref
320 get_tree_r()
322 echo "$1"
325 # strip_ref "$(git symbolic-ref HEAD)"
326 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
327 strip_ref()
329 case "$1" in
330 refs/"$topbases"/*)
331 echol "${1#refs/$topbases/}"
333 refs/heads/*)
334 echol "${1#refs/heads/}"
337 echol "$1"
338 esac
341 # pretty_tree [-t] NAME [-b | -i | -w | -r]
342 # Output tree ID of a cleaned-up tree without tg's artifacts.
343 # NAME will be ignored for -i and -w, but needs to be present
344 # With -r NAME must be a full ref name to a treeish (it's used as-is)
345 # If -t is used the tree is written into the alternate temporary objects area
346 pretty_tree()
348 use_alt_temp_odb=
349 [ "$1" != "-t" ] || { shift; use_alt_temp_odb=1; }
350 name="$1"
351 source="${2#?}"
352 git ls-tree --full-tree "$(get_tree_$source "$name")" |
353 sed -ne '/ \.top.*$/!p' |
354 git_mktree
357 # return an empty-tree root commit -- date is either passed in or current
358 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
359 # An invalid secs causes the current date to be used, an invalid zone offset
360 # causes +0000 to be used
361 make_empty_commit()
363 # the empty tree is guaranteed to always be there even in a repo with
364 # zero objects, but for completeness we force it to exist as a real object
365 SECS=
366 read -r SECS ZONE JUNK <<-EOT || :
369 case "$SECS" in *[!0-9]*) SECS=; esac
370 if [ -z "$SECS" ]; then
371 MTDATE="$(date '+%s %z')"
372 else
373 case "$ZONE" in
374 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
376 [01][0-9][0-5][0-9])
377 ZONE="+$ZONE"
380 ZONE="+0000"
381 esac
382 MTDATE="$SECS $ZONE"
384 EMPTYID="- <-> $MTDATE"
385 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
386 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
387 git hash-object -t commit -w --stdin
390 # standard input is a diff
391 # standard output is the "+" lines with leading "+ " removed
392 diff_added_lines()
394 awk '
395 BEGIN { in_hunk = 0; }
396 /^@@ / { in_hunk = 1; }
397 /^\+/ { if (in_hunk == 1) printf("%s\n", substr($0, 2)); }
398 /^[^@ +-]/ { in_hunk = 0; }
402 # $1 is name of new branch to create locally if all of these are true:
403 # a) exists as a remote TopGit branch for "$base_remote"
404 # b) the branch "name" does not have any invalid characters in it
405 # c) neither of the two branch refs (branch or base) exist locally
406 # returns success only if a new local branch was created (and dumps message)
407 auto_create_local_remote()
409 case "$1" in ""|*[" $tab$lf~^:\\*?["]*|.*|*/.*|*.|*./|/*|*/|*//*) return 1; esac
410 [ -n "$base_remote" ] &&
411 git update-ref --stdin <<-EOT >/dev/null 2>&1 &&
412 verify refs/remotes/$base_remote/${topbases#heads/}/$1 refs/remotes/$base_remote/${topbases#heads/}/$1
413 verify refs/remotes/$base_remote/$1 refs/remotes/$base_remote/$1
414 create refs/$topbases/$1 refs/remotes/$base_remote/${topbases#heads/}/$1^0
415 create refs/heads/$1 refs/remotes/$base_remote/$1^0
417 { init_reflog "refs/$topbases/$1" || :; } &&
418 info "topic branch '$1' automatically set up from remote '$base_remote'"
421 # setup_hook NAME
422 setup_hook()
424 tgname="${0##*/}"
425 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
426 if [ -f "$git_hooks_dir/$1" ] && grep -Fq "$hook_call" "$git_hooks_dir/$1"; then
427 # Another job well done!
428 return
430 # Prepare incantation
431 hook_chain=
432 if [ -s "$git_hooks_dir/$1" -a -x "$git_hooks_dir/$1" ]; then
433 hook_call="$hook_call"' || exit $?'
434 if [ -L "$git_hooks_dir/$1" ] || ! sed -n 1p <"$git_hooks_dir/$1" | grep -Fqx "#!@SHELL_PATH@"; then
435 chain_num=
436 while [ -e "$git_hooks_dir/$1-chain$chain_num" ]; do
437 chain_num=$(( $chain_num + 1 ))
438 done
439 mv -f "$git_hooks_dir/$1" "$git_hooks_dir/$1-chain$chain_num"
440 hook_chain=1
442 else
443 hook_call="exec $hook_call"
444 [ -d "$git_hooks_dir" ] || mkdir -p "$git_hooks_dir" || :
446 # Don't call hook if tg is not installed
447 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
448 # Insert call into the hook
450 echol "#!@SHELL_PATH@"
451 echol "$hook_call"
452 if [ -n "$hook_chain" ]; then
453 echol "exec \"\$0-chain$chain_num\" \"\$@\""
454 else
455 [ ! -s "$git_hooks_dir/$1" ] || cat "$git_hooks_dir/$1"
457 } >"$git_hooks_dir/$1+"
458 chmod a+x "$git_hooks_dir/$1+"
459 mv "$git_hooks_dir/$1+" "$git_hooks_dir/$1"
462 # setup_ours (no arguments)
463 setup_ours()
465 if [ ! -s "$git_common_dir/info/attributes" ] || ! grep -q topmsg "$git_common_dir/info/attributes"; then
466 [ -d "$git_common_dir/info" ] || mkdir "$git_common_dir/info"
468 echo ".topmsg merge=ours"
469 echo ".topdeps merge=ours"
470 } >>"$git_common_dir/info/attributes"
472 if ! git config merge.ours.driver >/dev/null; then
473 git config merge.ours.name '"always keep ours" merge driver'
474 git config merge.ours.driver 'touch %A'
478 # measure_branch NAME [BASE] [EXTRAHEAD...]
479 measure_branch()
481 _bname="$1"; _base="$2"
482 shift; shift
483 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
484 # The caller should've verified $name is valid
485 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
486 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
487 if [ $_commits -ne 1 ]; then
488 _suffix="commits"
489 else
490 _suffix="commit"
492 echo "$_commits/$_nmcommits $_suffix"
495 # true if $1 is contained by (or the same as) $2
496 # this is never slower than merge-base --is-ancestor and is often slightly faster
497 contained_by()
499 [ "$(git rev-list --count --max-count=1 "$1" --not "$2" --)" = "0" ]
502 # branch_contains B1 B2
503 # Whether B1 is a superset of B2.
504 branch_contains()
506 _revb1="$(ref_exists_rev "$1")" || return 0
507 _revb2="$(ref_exists_rev "$2")" || return 0
508 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
509 if read _result _rev_matchb1 _rev_matchb2 &&
510 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
511 return $_result
512 fi <"$tg_cache_dir/$1/.bc/$2/.d"
514 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
515 _result=0
516 contained_by "$_revb2" "$_revb1" || _result=1
517 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
518 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
520 return $_result
523 create_ref_dirs()
525 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
526 awk -v p="$tg_tmp_dir/cached/" '{print p $1}' <"$tg_ref_cache" | tr '\n' '\0' | xargs -0 mkdir -p
527 awk -v p="$tg_tmp_dir/cached/" '
528 NF == 2 && $1 ~ /^refs\/./ && $2 ~ /^[0-9a-fA-F]{4,}$/ {
529 fn = p $1 "/.ref"
530 print "0 " $2 >fn
531 close fn
533 ' <"$tg_ref_cache"
534 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
537 # If the first argument is non-empty, stores "1" there if this call created the cache
538 v_create_ref_cache()
540 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
541 _remotespec=
542 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
543 [ -z "$1" ] || eval "$1=1"
544 git for-each-ref --format='%(refname) %(objectname)' \
545 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
546 create_ref_dirs
549 remove_ref_cache()
551 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
552 >"$tg_ref_cache"
553 >"$tg_ref_cache_br"
554 >"$tg_ref_cache_rbr"
555 >"$tg_ref_cache_ann"
556 >"$tg_ref_cache_dep"
559 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
560 rev_parse()
562 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
563 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
564 else
565 [ -z "$tg_ref_cache_only" ] || return 1
566 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
570 # ref_exists_rev REF
571 # Whether REF is a valid ref name
572 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
573 # or, if $base_remote is set, refs/remotes/$base_remote/
574 # Caches result if $tg_read_only and outputs HASH on success
575 ref_exists_rev()
577 case "$1" in
578 refs/*)
580 $octet20)
581 printf '%s' "$1"
582 return;;
584 die "ref_exists_rev requires fully-qualified ref name (given: $1)"
585 esac
586 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
587 _result=
588 _result_rev=
589 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
590 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
591 _result_rev="$(rev_parse "$1")"
592 _result=$?
593 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
594 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
595 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
596 printf '%s' "$_result_rev"
597 return $_result
600 # Same as ref_exists_rev but output is abbreviated hash
601 # Optional second argument defaults to --short but may be any --short=.../--no-short option
602 ref_exists_rev_short()
604 case "$1" in
605 refs/*)
607 $octet20)
610 die "ref_exists_rev_short requires fully-qualified ref name"
611 esac
612 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
613 _result=
614 _result_rev=
615 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
616 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
617 _result_rev="$(rev_parse "$1")"
618 _result=$?
619 if [ $_result -eq 0 ]; then
620 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev" --)"
621 _result=$?
623 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
624 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
625 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
626 printf '%s' "$_result_rev"
627 return $_result
630 # ref_exists REF
631 # Whether REF is a valid ref name
632 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
633 # or, if $base_remote is set, refs/remotes/$base_remote/
634 # Caches result
635 ref_exists()
637 ref_exists_rev "$1" >/dev/null
640 # rev_parse_tree REF
641 # Runs git rev-parse REF^{tree}
642 # Caches result if $tg_read_only
643 rev_parse_tree()
645 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
646 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
647 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
648 printf '%s\n' "$_result"
649 return 0
651 return 1
653 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
654 if [ -d "$tg_tmp_dir/cached/$1" ]; then
655 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
656 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
657 printf '%s\n' "$_result"
658 return 0
660 return 1
662 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
665 # has_remote BRANCH
666 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
667 has_remote()
669 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
672 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
673 # If -z "$1" still set return code but do not return result
674 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
675 # refs/heads/... then ... will be verified instead.
676 # if "$3" = "-f" (for fail) then return an error rather than dying.
677 v_verify_topgit_branch()
679 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
680 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
681 [ -n "$_verifyname" -o "$3" = "-f" ] || die "HEAD is not a symbolic ref"
682 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
683 [ "$3" != "-f" ] || return 1
684 die "HEAD is not a symbolic ref to the refs/heads namespace"
685 esac
686 set -- "$1" "$_verifyname" "$3"
688 case "$2" in
689 refs/"$topbases"/*)
690 _verifyname="${2#refs/$topbases/}"
692 refs/heads/*)
693 _verifyname="${2#refs/heads/}"
696 _verifyname="$2"
698 esac
699 if ! ref_exists "refs/heads/$_verifyname"; then
700 [ "$3" != "-f" ] || return 1
701 die "no such branch: $_verifyname"
703 if ! ref_exists "refs/$topbases/$_verifyname"; then
704 [ "$3" != "-f" ] || return 1
705 die "not a TopGit-controlled branch: $_verifyname"
707 [ -z "$1" ] || eval "$1="'"$_verifyname"'
710 # Return the verified TopGit branch name or die with an error.
711 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
712 # refs/heads/... then ... will be verified instead.
713 # if "$2" = "-f" (for fail) then return an error rather than dying.
714 verify_topgit_branch()
716 v_verify_topgit_branch _verifyname "$@" || return
717 printf '%s' "$_verifyname"
720 # Caches result
721 # $1 = branch name (i.e. "t/foo/bar")
722 # $2 = optional result of rev-parse "refs/heads/$1"
723 # $3 = optional result of rev-parse "refs/$topbases/$1"
724 branch_annihilated()
726 _branch_name="$1"
727 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
728 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
730 _result=
731 _result_rev=
732 _result_rev_base=
733 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/refs/heads/$_branch_name/.ann"; } 2>/dev/null || :
734 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
736 # use the merge base in case the base is ahead.
737 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
739 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
740 _result=$?
741 [ -d "$tg_cache_dir/refs/heads/$_branch_name" ] || mkdir -p "$tg_cache_dir/refs/heads/$_branch_name" 2>/dev/null
742 [ ! -d "$tg_cache_dir/refs/heads/$_branch_name" ] ||
743 echo $_result $_rev $_rev_base >"$tg_cache_dir/refs/heads/$_branch_name/.ann" 2>/dev/null || :
744 return $_result
747 non_annihilated_branches()
749 refscacheopt=
750 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
751 refscacheopt='-r="$tg_ref_cache" "refs/$topbases"'
753 eval run_awk_topgit_branches -n "$refscacheopt" '"refs/$topbases" "$@"'
756 # Make sure our tree is clean
757 # if optional "$1" given also verify that a checkout to "$1" would succeed
758 ensure_clean_tree()
760 check_status
761 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
762 git update-index --ignore-submodules --refresh ||
763 die "the working directory has uncommitted changes (see above) - first commit or reset them"
764 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
765 die "the index has uncommited changes"
766 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
767 die "git checkout \"$1\" would fail"
770 # Make sure .topdeps and .topmsg are "clean"
771 # They are considered "clean" if each is identical in worktree, index and HEAD
772 # With "-u" as the argument skip the HEAD check (-u => unborn)
773 # untracked .topdeps and/or .topmsg files are always considered "dirty" as well
774 # with -u them just existing constitutes "dirty"
775 ensure_clean_topfiles()
777 _dirtw=0
778 _dirti=0
779 _dirtu=0
780 _check="$(git diff-files --ignore-submodules --name-only -- :/.topdeps :/.topmsg)" &&
781 [ -z "$_check" ] || _dirtw=1
782 if [ "$1" != "-u" ]; then
783 _check="$(git diff-index --cached --ignore-submodules --name-only HEAD -- :/.topdeps :/.topmsg)" &&
784 [ -z "$_check" ] || _dirti=1
786 if [ "$_dirti$_dirtw" = "00" ]; then
787 v_get_show_cdup
788 if [ -e "${git_cdup_result}.topdeps" ] || [ -e "${git_cdup_result}.topmsg" ]; then
789 [ "$1" != "-u" ] &&
790 _check="$(git status --porcelain --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg)" &&
791 [ -z "$_check" ] || _dirtu=1
794 if [ "$_dirtu$_dirti$_dirtw" != "000" ]; then
795 git status --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg || :
796 case "$_dirtu$_dirti$_dirtw" in
797 001) die "the working directory has uncommitted changes (see above) - first commit or reset them";;
798 010) die "the index has uncommited changes (see above)";;
799 011) die "the working directory and index have uncommitted changes (see above) - first commit or reset them";;
800 100) die "the working directory has untracked files that would be overwritten (see above)";;
801 esac
805 # is_sha1 REF
806 # Whether REF is a SHA1 (compared to a symbolic name).
807 is_sha1()
809 case "$1" in $octet20) return 0;; esac
810 return 1
813 # navigate_deps <run_awk_topgit_navigate options and arguments>
814 # all options and arguments are passed through to run_awk_topgit_navigate
815 # except for a leading -td= option, if any, which is picked off for deps
816 # after arranging to feed it a suitable deps list
817 navigate_deps()
819 dogfer=
820 dorad=1
821 userc=
822 tmpdep=
823 ratd_opts=
824 ratn_opts=
825 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
826 userc=1
827 tmprfs="$tg_ref_cache"
828 tmptgbr="$tg_ref_cache_br"
829 tmpann="$tg_ref_cache_ann"
830 tmpdep="$tg_ref_cache_dep"
831 [ -s "$tg_ref_cache" ] || dogfer=1
832 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
833 else
834 ratd_opts="-rmr"
835 ratn_opts="-rma -rmb"
836 tmprfs="$tg_tmp_dir/refs.$$"
837 tmpann="$tg_tmp_dir/ann.$$"
838 tmptgbr="$tg_tmp_dir/tgbr.$$"
839 dogfer=1
841 refpats="\"refs/heads\" \"refs/\$topbases\""
842 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
843 [ -z "$dogfer" ] ||
844 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
845 depscmd="run_awk_topgit_deps $ratd_opts"
846 case "$1" in -td=*)
847 userc=
848 depscmd="$depscmd $1"
849 shift
850 esac
851 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -m="$mtblob" -s "refs/$topbases"'
852 if [ -n "$userc" ]; then
853 if [ -n "$dorad" ]; then
854 eval "$depscmd" >"$tmpdep"
856 depscmd='<"$tmpdep" '
857 else
858 depscmd="$depscmd |"
860 eval "$depscmd" run_awk_topgit_navigate '-a="$tmpann" -b="$tmptgbr"' "$ratn_opts" '"$@"'
863 # recurse_deps_internal NAME [BRANCHPATH...]
864 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
865 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
866 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
867 # but missing and remotes are always "0"
868 # then the branch name followed by its depedency chain (which might be empty)
869 # An output line might look like this:
870 # 0 1 1 t/foo/leaf t/foo/int t/stage
871 # If no_remotes is non-empty, exclude remotes
872 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
873 # If with_top_level is non-empty, include the top-level that's normally omitted
874 # any branch names in the space-separated recurse_deps_exclude variable
875 # are skipped (along with their dependencies)
876 recurse_deps_internal()
878 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
879 ratr_opts="${recurse_preorder:+-f} ${with_top_level:+-s}"
880 dogfer=
881 dorad=1
882 userc=
883 tmpdep=
884 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
885 userc=1
886 tmprfs="$tg_ref_cache"
887 tmptgbr="$tg_ref_cache_br"
888 tmpann="$tg_ref_cache_ann"
889 tmpdep="$tg_ref_cache_dep"
890 [ -s "$tg_ref_cache" ] || dogfer=1
891 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
892 else
893 ratr_opts="$ratr_opts -rmh -rma -rmb"
894 tmprfs="$tg_tmp_dir/refs.$$"
895 tmpann="$tg_tmp_dir/ann.$$"
896 tmptgbr="$tg_tmp_dir/tgbr.$$"
897 dogfer=1
899 refpats="\"refs/heads\" \"refs/\$topbases\""
900 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
901 tmptgrmtbr=
902 dorab=1
903 if [ -z "$no_remotes" ] && [ -n "$base_remote" ]; then
904 if [ -n "$userc" ]; then
905 tmptgrmtbr="$tg_ref_cache_rbr"
906 [ -n "$dogfer" ] || ! [ -s "$tmptgrmtbr" ] || dorab=
907 else
908 tmptgrmtbr="$tg_tmp_dir/tgrmtbr.$$"
909 ratr_opts="$ratr_opts -rmr"
911 ratr_opts="$ratr_opts -r=\"\$tmptgbr\" -u=\"refs/remotes/\$base_remote/\${topbases#heads/}\""
913 [ -z "$dogfer" ] ||
914 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
915 if [ -n "$tmptgrmtbr" ] && [ -n "$dorab" ]; then
916 run_awk_topgit_branches -n -h="refs/remotes/$base_remote" -r="$tmprfs" \
917 "refs/remotes/$base_remote/${topbases#heads/}" >"$tmptgrmtbr"
919 depscmd='run_awk_topgit_deps -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -m="$mtblob" "refs/$topbases"'
920 if [ -n "$userc" ]; then
921 if [ -n "$dorad" ]; then
922 eval "$depscmd" >"$tmpdep"
924 depscmd='<"$tmpdep" '
925 else
926 depscmd="$depscmd |"
928 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
929 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
932 # do_eval CMD
933 # helper for recurse_deps so that a return statement executed inside CMD
934 # does not return from recurse_deps. This shouldn't be necessary, but it
935 # seems that it actually is.
936 do_eval()
938 eval "$@"
941 # becomes read-only for caching purposes
942 # assigns new value to tg_read_only
943 # become_cacheable/undo_become_cacheable calls may be nested
944 become_cacheable()
946 _old_tg_read_only="$tg_read_only"
947 if [ -z "$tg_read_only" ]; then
948 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
949 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
950 tg_read_only=1
952 _my_ref_cache=
953 v_create_ref_cache _my_ref_cache
954 _my_ref_cache="${_my_ref_cache:+1}"
955 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
958 # restores tg_read_only and ref_cache to state before become_cacheable call
959 # become_cacheable/undo_bocome_cacheable calls may be nested
960 undo_become_cacheable()
962 case "$tg_read_only" in
963 "undo"[01]"-"*)
964 _suffix="${tg_read_only#undo?-}"
965 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
966 tg_read_only="$_suffix"
967 esac
970 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
971 become_non_cacheable()
973 remove_ref_cache
974 tg_read_only=
975 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
976 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
979 # call this to make sure Git will not complain about a missing user/email
980 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
981 ensure_ident_available()
983 [ -z "$TG_IDENT_CHECKED" ] || return 0
984 git var GIT_AUTHOR_IDENT >/dev/null &&
985 git var GIT_COMMITTER_IDENT >/dev/null || exit
986 TG_IDENT_CHECKED=1
987 export TG_IDENT_CHECKED
988 return 0
991 # recurse_deps [-o=<options string>] CMD NAME [BRANCHPATH...]
992 # Recursively eval CMD on all dependencies of NAME.
993 # Dependencies are visited in topological order.
994 # If <options string> is given, it's eval'd into the recurse_deps_internal
995 # call just before the "--" that's passed just before NAME
996 # CMD can refer to the following variables:
998 # _ret starts as 0; CMD can change; will be final return result
999 # _dep bare branch name or "refs/remotes/..." for a remote base
1000 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
1001 # _depchain 0+ space-separated branch names forming a path to top
1002 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
1003 # _dep_is_leaf boolean "1" if leaf; "" if not
1004 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
1005 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
1006 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
1008 # CMD may use a "return" statement without issue; its return value is ignored,
1009 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
1010 # will stop immediately and the value with the leading "-" stripped off will
1011 # be the final result code
1013 # CMD can refer to $_name for queried branch name,
1014 # $_dep for dependency name,
1015 # $_depchain for space-seperated branch backtrace,
1016 # $_dep_missing boolean to check whether $_dep is present
1017 # and the $_dep_is_tgish and $_dep_annihilated booleans.
1018 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
1019 # It can modify $_ret to affect the return value
1020 # of the whole function.
1021 # If recurse_deps() hits missing dependencies, it will append
1022 # them to space-separated $missing_deps list and skip them
1023 # after calling CMD with _dep_missing set.
1024 # remote dependencies are processed if no_remotes is unset.
1025 # any branch names in the space-separated recurse_deps_exclude variable
1026 # are skipped (along with their dependencies)
1028 # If no_remotes is non-empty, exclude remotes
1029 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1030 # If with_top_level is non-empty, include the top-level that's normally omitted
1031 # any branch names in the space-separated recurse_deps_exclude variable
1032 # are skipped (along with their dependencies)
1033 recurse_deps()
1035 _opts=
1036 case "$1" in -o=*) _opts="${1#-o=}"; shift; esac
1037 _cmd="$1"; shift
1039 _depsfile="$(get_temp tg-depsfile)"
1040 eval recurse_deps_internal "$_opts" -- '"$@"' >"$_depsfile" || :
1042 _ret=0
1043 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1044 _depchain="$_name${_deppath:+ $_deppath}"
1045 _dep_is_tgish=
1046 [ "$_istgish" = "0" ] || _dep_is_tgish=1
1047 _dep_has_remote=
1048 [ "$_istgish" != "2" ] || _dep_has_remote=1
1049 _dep_missing=
1050 if [ "$_ismissing" != "0" ]; then
1051 _dep_missing=1
1052 case " $missing_deps " in *" $_dep "*);;*)
1053 missing_deps="${missing_deps:+$missing_deps }$_dep"
1054 esac
1056 _dep_annihilated=
1057 _dep_is_leaf=
1058 if [ "$_isleaf" = "1" ]; then
1059 _dep_is_leaf=1
1060 elif [ "$_isleaf" = "2" ]; then
1061 _dep_annihilated=1
1063 do_eval "$_cmd" || :
1064 if [ "${_ret#-}" != "$_ret" ]; then
1065 _ret="${_ret#-}"
1066 break
1068 done <"$_depsfile"
1069 rm -f "$_depsfile"
1070 return ${_ret:-0}
1073 # find_leaves NAME
1074 # output (one per line) the unique leaves of NAME
1075 # a leaf is either
1076 # 1) a non-tgish dependency
1077 # 2) the base of a tgish dependency with no non-annihilated dependencies
1078 # duplicates are suppressed (by commit rev) and remotes are always ignored
1079 # if a leaf has an exact tag match that will be output
1080 # note that recurse_deps_exclude IS honored for this operation
1081 find_leaves()
1083 no_remotes=1
1084 with_top_level=1
1085 recurse_preorder=
1086 seen_leaf_refs=
1087 seen_leaf_revs=
1088 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1089 [ "$_isleaf" = "1" ] && [ "$_ismissing" = "0" ] || continue
1090 if [ "$_istgish" != "0" ]; then
1091 fulldep="refs/$topbases/$_dep"
1092 else
1093 fulldep="refs/heads/$_dep"
1095 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1096 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1097 if fullrev="$(ref_exists_rev "$fulldep")"; then
1098 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1099 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1100 # See if Git knows it by another name
1101 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1102 echo "refs/tags/$tagname"
1103 else
1104 echo "$fulldep"
1106 esac
1108 esac
1109 done <<-EOT
1110 $(recurse_deps_internal -l -o=1 -- "$1")
1112 with_top_level=
1115 # branch_needs_update
1116 # This is a helper function for determining whether given branch
1117 # is up-to-date wrt. its dependencies. It expects input as if it
1118 # is called as a recurse_deps() helper.
1119 # In case the branch does need update, it will echo it together
1120 # with the branch backtrace on the output (see needs_update()
1121 # description for details) and set $_ret to non-zero.
1122 branch_needs_update()
1124 if [ -n "$_dep_missing" ]; then
1125 echo "! $_dep $_depchain"
1126 return 0
1129 if [ -n "$_dep_is_tgish" ]; then
1130 [ -z "$_dep_annihilated" ] || return 0
1132 if [ -n "$_dep_has_remote" ]; then
1133 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
1134 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
1136 # We want to sync with our base first and should output this before
1137 # the remote branch, but the order does not actually matter to tg-update
1138 # as it just recurses regardless, but it does matter for tg-info (which
1139 # treats out-of-date bases as though they were already merged in) so
1140 # we output the remote before the base.
1141 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1142 echo ": $_dep $_depchain"
1143 _ret=1
1144 return
1148 if [ -n "$_name" ]; then
1149 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
1150 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1151 # Some new commits in _dep
1152 echo "$_dep $_depchain"
1153 _ret=1
1158 # needs_update NAME
1159 # This function is recursive; it outputs reverse path from NAME
1160 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1161 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
1162 # if the head is not in sync with the <remote> branch <name>, ':' if
1163 # the head is not in sync with the base (in this order of priority)
1164 # or '!' if dependency is missing. Note that the remote branch, base
1165 # order is reversed from the order they will actually be updated in
1166 # order to accomodate tg info which treats out-of-date items that are
1167 # only in the base as already being in the head for status purposes.
1168 # It will also return non-zero status if NAME needs update.
1169 # If needs_update() hits missing dependencies, it will append
1170 # them to space-separated $missing_deps list and skip them.
1171 needs_update()
1173 recurse_deps branch_needs_update "$1"
1176 # branch_empty NAME [-i | -w]
1177 branch_empty()
1179 if [ -z "$2" ]; then
1180 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1181 _result=
1182 _result_rev=
1183 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1184 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
1185 _result=0
1186 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1187 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1188 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1189 return $_result
1190 else
1191 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1195 v_get_tdmopt_internal()
1197 [ -n "$1" ] && [ -n "$3" ] || return 0
1198 [ "$2" = "-i" ] || [ "$2" = "-w" ] || return 0
1199 _optval=
1200 if v_verify_topgit_branch _tghead "HEAD" -f; then
1201 if [ "$2" = "-w" ] && [ -f "$root_dir/$3" ] && [ -r "$root_dir/$3" ]; then
1202 _opthash=
1203 if _opthash="$(git hash-object -w -t blob --stdin <"$root_dir/$3")" && [ -n "$_opthash" ]; then
1204 _optval="$4\"$_tghead:$_opthash\""
1206 elif [ "$2" = "-i" ]; then
1207 if _opthash="$(git rev-parse --quiet --verify ":0:$3" --)" && [ -n "$_opthash" ]; then
1208 _optval="$4\"$_tghead:$_opthash\""
1212 eval "$1="'"$_optval"'
1215 # set var $1 to the correct -td= option for use in an eval for $2 -i or -w mode
1216 v_get_tdopt() { v_get_tdmopt_internal "$1" "$2" ".topdeps" "-td="; }
1218 # set var $1 to the correct -tm= option for use in an eval for $2 -i or -w mode
1219 v_get_tmopt() { v_get_tdmopt_internal "$1" "$2" ".topmsg" "-tm="; }
1221 # checkout_symref_full [-f] FULLREF [SEED]
1222 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1223 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1224 # MUST be a committish which if present will be used instead of current FULLREF
1225 # (and FULLREF will be updated to it as well in that case)
1226 # Any merge state is always cleared by this function
1227 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1228 # instead of -m) but it will clear out any unmerged entries
1229 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1230 checkout_symref_full()
1232 _mode=-m
1233 _head="HEAD"
1234 if [ "$1" = "-f" ]; then
1235 _mode="--reset"
1236 _head=
1237 shift
1239 _ishash=
1240 case "$1" in
1241 refs/?*)
1243 $octet20)
1244 _ishash=1
1245 [ -z "$2" ] || [ "$1" = "$2" ] ||
1246 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1247 set -- HEAD "$1"
1250 die "programmer error: invalid checkout_symref_full \"$1\""
1252 esac
1253 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1254 die "invalid committish: \"${2:-$1}\""
1255 # Clear out any MERGE_HEAD kruft
1256 rm -f "$git_dir/MERGE_HEAD" || :
1257 # We have to do all the hard work ourselves :/
1258 # This is like git checkout -b "$1" "$2"
1259 # (or just git checkout "$1"),
1260 # but never creates a detached HEAD (unless $1 is a hash)
1261 git read-tree -u $_mode $_head "$_seedrev" &&
1263 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1264 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1265 } && {
1266 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1270 # switch_to_base NAME [SEED]
1271 switch_to_base()
1273 checkout_symref_full "refs/$topbases/$1" "$2"
1276 # run editor with arguments
1277 # the editor setting will be cached in $tg_editor (which is eval'd)
1278 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1279 run_editor()
1281 tg_editor="$GIT_EDITOR"
1282 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1283 eval "$tg_editor" '"$@"'
1286 # Show the help messages.
1287 do_help()
1289 _www=
1290 if [ "$1" = "-w" ]; then
1291 _www=1
1292 shift
1294 if [ -z "$1" ] ; then
1295 # This is currently invoked in all kinds of circumstances,
1296 # including when the user made a usage error. Should we end up
1297 # providing more than a short help message, then we should
1298 # differentiate.
1299 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1301 ## Build available commands list for help output
1303 cmds=
1304 sep=
1305 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1306 ! [ -r "$cmd" ] && continue
1307 # strip directory part and "tg-" prefix
1308 cmd="${cmd##*/}"
1309 cmd="${cmd#tg-}"
1310 [ "$cmd" != "migrate-bases" ] || continue
1311 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1312 cmds="$cmds$sep$cmd"
1313 sep="|"
1314 done
1316 echo "TopGit version $TG_VERSION - A different patch queue manager"
1317 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u]" \
1318 "[-c <name>=<val>] [--no-pager] ($cmds) ..."
1319 echo " Or: $tgname help [-w] [<command>]"
1320 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1321 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1322 if [ -n "$_www" ]; then
1323 nohtml=
1324 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1325 echo "${0##*/}: missing html help file:" \
1326 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1327 nohtml=1
1329 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1330 echo "${0##*/}: missing html help file:" \
1331 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1332 nohtml=1
1334 if [ -n "$nohtml" ]; then
1335 echo "${0##*/}: use" \
1336 "\"${0##*/} help $1\" instead" 1>&2
1337 exit 1
1339 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1340 exit
1342 output()
1344 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1345 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1346 echo
1347 elif [ "$1" = "help" ]; then
1348 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1349 echo
1350 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1351 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1352 echo
1354 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1355 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1358 page output "$1"
1359 else
1360 echo "${0##*/}: no help for $1" 1>&2
1361 do_help
1362 exit 1
1366 check_status()
1368 git_state=
1369 git_remove=
1370 if [ -e "$git_dir/MERGE_HEAD" ]; then
1371 git_state="merge"
1372 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1373 git_state="am"
1374 git_remove="$git_dir/rebase-apply"
1375 elif [ -e "$git_dir/rebase-apply" ]; then
1376 git_state="rebase"
1377 git_remove="$git_dir/rebase-apply"
1378 elif [ -e "$git_dir/rebase-merge" ]; then
1379 git_state="rebase"
1380 git_remove="$git_dir/rebase-merge"
1381 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1382 git_state="cherry-pick"
1383 elif [ -e "$git_dir/BISECT_LOG" ]; then
1384 git_state="bisect"
1385 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1386 git_state="revert"
1388 git_remove="${git_remove#./}"
1390 tg_state=
1391 tg_remove=
1392 tg_topmerge=
1393 if [ -e "$git_dir/tg-update" ]; then
1394 tg_state="update"
1395 tg_remove="$git_dir/tg-update"
1396 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1398 tg_remove="${tg_remove#./}"
1401 # Show status information
1402 do_status()
1404 do_status_result=0
1405 do_status_verbose=
1406 do_status_help=
1407 abbrev=refs
1408 pfx=
1409 while [ $# -gt 0 ] && case "$1" in
1410 --help|-h)
1411 do_status_help=1
1412 break;;
1413 -vv)
1414 # kludge in this common bundling option
1415 abbrev=
1416 do_status_verbose=1
1417 pfx="## "
1419 --verbose|-v)
1420 [ -z "$do_status_verbose" ] || abbrev=
1421 do_status_verbose=1
1422 pfx="## "
1424 --exit-code)
1425 do_status_result=2
1428 die "unknown status argument: $1"
1430 esac; do shift; done
1431 if [ -n "$do_status_help" ]; then
1432 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1433 return
1435 check_status
1436 symref="$(git symbolic-ref --quiet HEAD)" || :
1437 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1438 if [ -n "$symref" ]; then
1439 uprefpart=
1440 if [ -n "$headrv" ]; then
1441 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1442 if [ -n "$upref" ]; then
1443 uprefpart=" ... ${upref#$abbrev/remotes/}"
1444 mbase="$(git merge-base HEAD "$upref")" || :
1445 ahead="$(git rev-list --count HEAD ${mbase:+--not $mbase})" || ahead=0
1446 behind="$(git rev-list --count "$upref" ${mbase:+--not $mbase})" || behind=0
1447 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1448 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1449 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1450 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1451 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1454 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1455 else
1456 echol "${pfx}HEAD -> ${headrv:-?}"
1458 if [ -n "$tg_state" ]; then
1459 extra=
1460 if [ "$tg_state" = "update" ]; then
1461 IFS= read -r uname <"$git_dir/tg-update/name" || :
1462 [ -z "$uname" ] ||
1463 extra="; currently updating branch '$uname'"
1465 echol "${pfx}tg $tg_state in progress$extra"
1466 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1467 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1468 cat "$git_dir/tg-update/fullcmd"
1469 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1470 if [ $bcnt -gt 1 ]; then
1471 pcnt=0
1472 ! [ -s "$git_dir/tg-update/processed" ] ||
1473 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1474 echo "${pfx}$pcnt of $bcnt branches updated so far"
1477 if [ "$tg_state" = "update" ]; then
1478 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1479 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1480 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1481 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1484 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1485 if [ "$git_state" = "merge" ]; then
1486 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1487 if [ $ucnt -gt 0 ]; then
1488 echo "${pfx}"'fix conflicts and then "git commit" the result'
1489 else
1490 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1493 if [ -z "$git_state" ]; then
1494 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository
1495 gspcnt=0
1496 [ -z "$gsp" ] ||
1497 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1498 untr=
1499 if [ "$gspcnt" -eq 0 ]; then
1500 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1501 echo "${pfx}working directory is clean$untr"
1502 [ -n "$tg_state" ] || do_status_result=0
1503 else
1504 echo "${pfx}working directory is DIRTY"
1505 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1510 ## Pager stuff
1512 # isatty FD
1513 isatty()
1515 test -t $1
1518 # pass "diff" to get pager.diff
1519 # if pager.$1 is a boolean false returns cat
1520 # if set to true or unset fails
1521 # otherwise succeeds and returns the value
1522 get_pager()
1524 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1525 [ "$_x" != "true" ] || return 1
1526 echo "cat"
1527 return 0
1529 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1530 echol "$_x"
1531 return 0
1533 return 1
1536 # setup_pager
1537 # Set TG_PAGER to a valid executable
1538 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1539 # See also the following "page" function for ease of use
1540 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1541 # Preference is (same as Git):
1542 # 1. GIT_PAGER
1543 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1544 # 3. core.pager (only if set)
1545 # 4. PAGER
1546 # 5. git var GIT_PAGER
1547 # 6. less
1548 setup_pager()
1550 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1552 emptypager=
1553 if [ -z "$TG_PAGER_IN_USE" ]; then
1554 # TG_PAGER = GIT_PAGER | PAGER | less
1555 # NOTE: GIT_PAGER='' is significant
1556 if [ -n "${GIT_PAGER+set}" ]; then
1557 TG_PAGER="$GIT_PAGER"
1558 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1559 TG_PAGER="$_dp"
1560 elif _cp="$(git config core.pager 2>/dev/null)"; then
1561 TG_PAGER="$_cp"
1562 elif [ -n "${PAGER+set}" ]; then
1563 TG_PAGER="$PAGER"
1564 else
1565 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1566 [ "$_gp" != ":" ] || _gp=
1567 TG_PAGER="${_gp:-less}"
1569 if [ -z "$TG_PAGER" ]; then
1570 emptypager=1
1571 TG_PAGER=cat
1573 else
1574 emptypager=1
1575 TG_PAGER=cat
1578 # Set pager default environment variables
1579 # see pager.c:setup_pager
1580 if [ -z "${LESS+set}" ]; then
1581 LESS="-FRX"
1582 export LESS
1584 if [ -z "${LV+set}" ]; then
1585 LV="-c"
1586 export LV
1589 # this is needed so e.g. $(git diff) will still colorize it's output if
1590 # requested in ~/.gitconfig with color.diff=auto
1591 GIT_PAGER_IN_USE=1
1592 export GIT_PAGER_IN_USE
1594 # this is needed so we don't get nested pagers
1595 TG_PAGER_IN_USE=1
1596 export TG_PAGER_IN_USE
1599 # page eval_arg [arg ...]
1601 # Calls setup_pager then evals the first argument passing it all the rest
1602 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1603 # by setup_pager (in which case the output is left as-is).
1605 # To handle arbitrary paging duties, collect lines to be paged into a
1606 # function and then call page with the function name or perhaps func_name "$@".
1608 # If no arguments at all are passed in do nothing (return with success).
1609 page()
1611 [ $# -gt 0 ] || return 0
1612 setup_pager
1613 _evalarg="$1"; shift
1614 if [ -n "$emptypager" ]; then
1615 eval "$_evalarg" '"$@"'
1616 else
1617 { eval "$_evalarg" '"$@"';} | eval "$TG_PAGER"
1621 # get_temp NAME [-d]
1622 # creates a new temporary file (or directory with -d) in the global
1623 # temporary directory $tg_tmp_dir with pattern prefix NAME
1624 get_temp()
1626 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1629 # automatically called by strftime
1630 # does nothing if already setup
1631 # may be called explicitly if the first call would otherwise be in a subshell
1632 # so that the setup is only done once before subshells start being spawned
1633 setup_strftime()
1635 [ -z "$strftime_is_setup" ] || return 0
1637 # date option to format raw epoch seconds values
1638 daterawopt=
1639 _testes='951807788'
1640 _testdt='2000-02-29 07:03:08 UTC'
1641 _testfm='%Y-%m-%d %H:%M:%S %Z'
1642 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1643 daterawopt='-d@'
1644 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1645 daterawopt='-r'
1647 strftime_is_setup=1
1650 # $1 => strftime format string to use
1651 # $2 => raw timestamp as seconds since epoch
1652 # $3 => optional time zone string (empty/absent for local time zone)
1653 strftime()
1655 setup_strftime
1656 if [ -n "$daterawopt" ]; then
1657 if [ -n "$3" ]; then
1658 TZ="$3" date "$daterawopt$2" "+$1"
1659 else
1660 date "$daterawopt$2" "+$1"
1662 else
1663 if [ -n "$3" ]; then
1664 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1665 else
1666 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1671 got_cdup_result=
1672 git_cdup_result=
1673 v_get_show_cdup()
1675 if [ -z "$got_cdup_result" ]; then
1676 git_cdup_result="$(git rev-parse --show-cdup)"
1677 got_cdup_result=1
1679 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1682 setup_git_dirs()
1684 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1685 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1686 git_dir="$(cd "$git_dir" && pwd)"
1688 if [ -z "$git_common_dir" ]; then
1689 if vcmp "$git_version" '>=' "2.5"; then
1690 # rev-parse --git-common-dir is broken and may give
1691 # an incorrect result unless the current directory is
1692 # already set to the top level directory
1693 v_get_show_cdup
1694 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1695 else
1696 git_common_dir="$git_dir"
1699 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1700 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1701 git_hooks_dir="$git_common_dir/hooks"
1702 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1703 case "$gchp" in
1704 /[!/]*)
1705 git_hooks_dir="$gchp"
1708 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1710 esac
1711 unset gchp
1715 basic_setup()
1717 setup_git_dirs $1
1718 if [ -z "$base_remote" ]; then
1719 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
1720 base_remote="$TG_EXPLICIT_REMOTE"
1721 else
1722 base_remote="$(git config topgit.remote 2>/dev/null)" || :
1725 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1726 tgnosequester=
1727 [ "$tgsequester" != "false" ] || tgnosequester=1
1728 unset tgsequester
1730 # catch errors if topbases is used without being set
1731 unset tg_topbases_set
1732 topbases="programmer*:error"
1733 topbasesrx="programmer*:error}"
1734 oldbases="$topbases"
1737 ## Initial setup
1738 initial_setup()
1740 # suppress the merge log editor feature since git 1.7.10
1742 GIT_MERGE_AUTOEDIT=no
1743 export GIT_MERGE_AUTOEDIT
1745 basic_setup $1
1746 iowopt=
1747 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
1748 gcfbopt=
1749 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
1750 auhopt=
1751 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1752 v_get_show_cdup root_dir
1753 root_dir="${root_dir:-.}"
1754 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1755 [ "$logrefupdates" = "true" ] || logrefupdates=
1757 # make sure root_dir doesn't end with a trailing slash.
1759 root_dir="${root_dir%/}"
1761 # create global temporary directories, inside GIT_DIR
1763 tg_tmp_dir=
1764 trap 'rm -rf "$tg_tmp_dir"' EXIT
1765 trap 'exit 129' HUP
1766 trap 'exit 130' INT
1767 trap 'exit 131' QUIT
1768 trap 'exit 134' ABRT
1769 trap 'exit 143' TERM
1770 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1771 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1772 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1773 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1774 tg_ref_cache_br="$tg_ref_cache.br"
1775 tg_ref_cache_rbr="$tg_ref_cache.rbr"
1776 tg_ref_cache_ann="$tg_ref_cache.ann"
1777 tg_ref_cache_dep="$tg_ref_cache.dep"
1778 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_ref_cache"; } >/dev/null 2>&1 ||
1779 die "could not create a writable temporary directory"
1781 # make sure global cache directory exists inside GIT_DIR or $tg_tmp_dir
1783 user_id_no="$(id -u)" || :
1784 : "${user_id_no:=_99_}"
1785 tg_cache_dir="$git_common_dir/tg-cache"
1786 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1787 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
1788 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1789 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1790 if [ -z "$tg_cache_dir" ]; then
1791 tg_cache_dir="$tg_tmp_dir/tg-cache"
1792 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1793 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1795 [ -n "$tg_cache_dir" ] ||
1796 die "could not create a writable tg-cache directory (even a temporary one)"
1798 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
1799 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
1800 # so we avoid it if possible and require v2.11.1 to do it at all
1801 # otherwise just don't make an alternates temporary store in that case;
1802 # it's okay to not have one; everything will still work; the nicety of
1803 # making the temporary tree objects vanish when tg exits just won't
1804 # happen in that case but nothing will break also be sure to reuse
1805 # the parent's if we've been recursively invoked and it's for the
1806 # same repository we were invoked on
1808 tg_use_alt_odb=1
1809 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
1810 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] || tg_use_alt_odb=
1811 _fulltmpdir=
1812 [ -z "$tg_use_alt_odb" ] || _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
1813 case "$_fulltmpdir" in *[";:"]*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
1814 _fullodbdir=
1815 [ -z "$tg_use_alt_odb" ] || _fullodbdir="$(cd "$_odbdir" && pwd -P)"
1816 if [ -n "$tg_use_alt_odb" ] && [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
1817 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
1818 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
1819 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
1820 tg_use_alt_odb=2
1823 if [ "$tg_use_alt_odb" = "1" ]; then
1824 # create an alternate objects database to keep the ephemeral objects in
1825 mkdir -p "$tg_tmp_dir/objects/info"
1826 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
1827 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
1828 case "$TG_OBJECT_DIRECTORY" in
1829 *[";:"]*)
1830 # surround in "..." and backslash-escape internal '"' and '\\'
1831 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
1832 sed 's/\([""\\]\)/\\\1/g')\""
1835 _altodbdq="$TG_OBJECT_DIRECTORY"
1837 esac
1838 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1839 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
1840 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1841 else
1842 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
1844 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
1848 set_topbases()
1850 # refer to "top-bases" in a refname with $topbases
1852 [ -z "$tg_topbases_set" ] || return 0
1854 topbases_implicit_default=1
1855 # See if topgit.top-bases is set to heads or refs
1856 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
1857 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
1858 if [ -n "$1" ]; then
1859 # never die on the hook script
1860 unset tgtb
1861 else
1862 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
1865 if [ -n "$tgtb" ]; then
1866 case "$tgtb" in
1867 heads)
1868 topbases="heads/{top-bases}"
1869 topbasesrx="heads/[{]top-bases[}]"
1870 oldbases="top-bases";;
1871 refs)
1872 topbases="top-bases"
1873 topbasesrx="top-bases"
1874 oldbases="heads/{top-bases}";;
1875 esac
1876 # MUST NOT be exported
1877 unset tgtb tg_topbases_set topbases_implicit_default
1878 tg_topbases_set=1
1879 return 0
1881 unset tgtb
1883 # check heads and top-bases and see what state the current
1884 # repository is in. remotes are ignored.
1886 rc=0 activebases=
1887 activebases="$(
1888 git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null |
1889 run_awk_ref_prefixes ${1:+-e} -n -- "refs/heads/{top-bases}" "refs/top-bases" "refs/heads")" ||
1890 rc=$?
1891 if [ "$rc" = "65" ]; then
1892 # Complain and die
1893 err "repository contains existing TopGit branches"
1894 err "but some use refs/top-bases/... for the base"
1895 err "and some use refs/heads/{top-bases}/... for the base"
1896 err "with the latter being the new, preferred location"
1897 err "set \"topgit.top-bases\" to either \"heads\" to use"
1898 err "the new heads/{top-bases} location or \"refs\" to use"
1899 err "the old top-bases location."
1900 err "(the tg migrate-bases command can also resolve this issue)"
1901 die "schizophrenic repository requires topgit.top-bases setting"
1903 [ -z "$activebases" ] || unset topbases_implicit_default
1904 if [ "$activebases" = "refs/heads/{top-bases}" ]; then
1905 topbases="heads/{top-bases}"
1906 topbasesrx="heads/[{]top-bases[}]"
1907 oldbases="top-bases"
1908 else
1909 # default is still top-bases for now
1910 topbases="top-bases"
1911 topbasesrx="top-bases"
1912 oldbases="heads/{top-bases}"
1914 # MUST NOT be exported
1915 unset rc activebases tg_topases_set
1916 tg_topbases_set=1
1917 return 0
1920 # init_reflog "ref"
1921 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
1922 # an empty log file to exist so that ref changes will be logged
1923 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
1924 # However, if "$1" is "refs/tgstash" then always make the reflog
1925 # The only ref not under refs/ that Git will write a reflog for is HEAD;
1926 # no matter what, it will NOT update a reflog for any other bare refs so
1927 # just quietly succeed when passed TG_STASH without doing anything.
1928 init_reflog()
1930 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
1931 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
1932 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
1933 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
1934 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
1937 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
1938 # a symbolic link. The directory part must exist, but the basename need not.
1939 v_get_abs_path()
1941 [ -n "$1" ] && [ -n "$2" ] || return 1
1942 set -- "$1" "$2" "${2%/}"
1943 case "$3" in
1944 */*) set -- "$1" "$2" "${3%/*}";;
1945 * ) set -- "$1" "$2" ".";;
1946 esac
1947 case "$2" in */)
1948 set -- "$1" "${2%/}" "$3" "/"
1949 esac
1950 [ -d "$3" ] || return 1
1951 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
1954 ## Startup
1956 : "${TG_INST_CMDDIR:=@cmddir@}"
1957 : "${TG_INST_SHAREDIR:=@sharedir@}"
1958 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1960 [ -d "$TG_INST_CMDDIR" ] ||
1961 die "No command directory: '$TG_INST_CMDDIR'"
1963 ## Include awk scripts and their utility functions (separated for easier debugging)
1965 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
1966 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
1967 . "$TG_INST_CMDDIR/tg--awksome"
1969 if [ -n "$tg__include" ]; then
1971 # We were sourced from another script for our utility functions;
1972 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1973 # work as expected in every shell. See http://bugs.debian.org/516188
1975 # ensure setup happens
1977 initial_setup 1
1978 set_topbases 1
1980 else
1982 set -e
1984 tgbin="$0"
1985 tgdir="${tgbin%/}"
1986 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
1987 tgdir="${tgdir%/*}/"
1988 tgname="${tgbin##*/}"
1989 [ "$0" != "$tgname" ] || tgdir=""
1991 # If tg contains a '/' but does not start with one then replace it with an absolute path
1993 case "$0" in /*) ;; */*)
1994 tgdir="$(cd "${0%/*}" && pwd -P)/"
1995 tgbin="$tgdir$tgname"
1996 esac
1998 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
1999 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2001 tgdisplaydir="$tgdir"
2002 tgdisplay="$tgbin"
2003 tgdisplayac="$tgdisplay"
2005 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2006 _tgabs="$_tgnameabs" &&
2007 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2008 [ "$_tgabs" = "$_tgnameabs" ]
2009 then
2010 tgdisplaydir=""
2011 tgdisplay="$tgname"
2012 tgdisplayac="$tgdisplay"
2014 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2015 unset _tgabs _tgnameabs
2017 tg() { command "$tgbin" "$@"; }
2019 explicit_remote=
2020 explicit_dir=
2021 gitcdopt=
2022 noremote=
2024 cmd=
2025 while :; do case "$1" in
2027 help|--help|-h)
2028 cmd=help
2029 shift
2030 break;;
2032 status|--status)
2033 cmd=status
2034 shift
2035 break;;
2037 --hooks-path)
2038 cmd=hooks-path
2039 shift
2040 break;;
2042 --exec-path)
2043 cmd=exec-path
2044 shift
2045 break;;
2047 --top-bases)
2048 cmd=top-bases
2049 shift
2050 break;;
2052 --no-pager)
2053 GIT_PAGER_IN_USE=1 TG_PAGER_IN_USE=1 &&
2054 export GIT_PAGER_IN_USE TG_PAGER_IN_USE
2055 shift;;
2058 shift
2059 if [ -z "$1" ]; then
2060 echo "Option -r requires an argument." >&2
2061 do_help
2062 exit 1
2064 unset noremote
2065 base_remote="$1"
2066 explicit_remote="$base_remote"
2067 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2068 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2069 shift;;
2072 unset base_remote explicit_remote
2073 noremote=1
2074 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2075 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2076 shift;;
2079 shift
2080 if [ -z "$1" ]; then
2081 echo "Option -C requires an argument." >&2
2082 do_help
2083 exit 1
2085 cd "$1"
2086 unset GIT_DIR GIT_COMMON_DIR
2087 if [ -z "$explicit_dir" ]; then
2088 explicit_dir="$1"
2089 else
2090 explicit_dir="$PWD"
2092 gitcdopt=" -C \"$explicit_dir\""
2093 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2094 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2095 tgdisplayac="$tgdisplay"
2096 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2097 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2098 shift;;
2101 shift
2102 if [ -z "$1" ]; then
2103 echo "Option -c requires an argument." >&2
2104 do_help
2105 exit 1
2107 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2108 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2109 export GIT_CONFIG_PARAMETERS
2110 shift;;
2113 shift
2114 break;;
2117 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2118 do_help
2119 exit 1;;
2122 break;;
2124 esac; done
2126 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
2128 ## Dispatch
2130 [ -n "$cmd" ] || { do_help; exit 1; }
2132 case "$cmd" in
2134 help)
2135 do_help "$@"
2136 exit 0;;
2138 status|st)
2139 unset base_remote
2140 basic_setup
2141 set_topbases
2142 do_status "$@"
2143 exit ${do_status_result:-0};;
2145 hooks-path)
2146 # Internal command
2147 echol "$TG_INST_HOOKSDIR";;
2149 exec-path)
2150 # Internal command
2151 echol "$TG_INST_CMDDIR";;
2153 top-bases)
2154 # Maintenance command
2155 ! git rev-parse --git-dir >/dev/null 2>&1 || setup_git_dirs
2156 set_topbases
2157 echol "refs/$topbases";;
2160 isutil=
2161 case "$cmd" in index-merge-one-file)
2162 isutil="-"
2163 esac
2164 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2165 looplevel="$TG_ALIAS_DEPTH"
2166 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2167 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2168 looplevel=0
2169 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2170 [ -n "$tgalias" ] || {
2171 echo "Unknown subcommand: $cmd" >&2
2172 do_help
2173 exit 1
2175 looplevel=$(( $looplevel + 1 ))
2176 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2177 TG_ALIAS_DEPTH="$looplevel"
2178 export TG_ALIAS_DEPTH
2179 if [ "!${tgalias#?}" = "$tgalias" ]; then
2180 unset GIT_PREFIX
2181 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2182 GIT_PREFIX="$pfx"
2183 export GIT_PREFIX
2185 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2186 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2187 else
2188 eval 'exec "$tgbin"' "$tgalias" '"$@"'
2190 die "alias execution failed for: $tgalias"
2192 unset TG_ALIAS_DEPTH
2194 showing_help=
2195 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2196 showing_help=1
2199 [ -n "$showing_help" ] || initial_setup
2200 [ -z "$noremote" ] || unset base_remote
2202 nomergesetup="$showing_help"
2203 case "$cmd" in base|contains|info|log|rebase|revert|summary|tag)
2204 # avoid merge setup where not necessary
2206 nomergesetup=1
2207 esac
2209 if [ -z "$nomergesetup" ]; then
2210 # make sure merging the .top* files will always behave sanely
2212 setup_ours
2213 setup_hook "pre-commit"
2216 # everything but rebase needs topbases set
2217 carefully="$showing_help"
2218 [ "$cmd" != "migrate-bases" ] || carefully=1
2219 [ "$cmd" = "rebase" ] || set_topbases $carefully
2221 _use_ref_cache=
2222 tg_read_only=1
2223 case "$cmd$showing_help" in
2224 contains|export|info|summary|tag)
2225 _use_ref_cache=1;;
2226 annihilate|create|delete|depend|import|update)
2227 tg_use_alt_odb=
2228 tg_read_only=;;
2229 esac
2230 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2232 fullcmd="${tgname:-tg} $cmd $*"
2233 . "$TG_INST_CMDDIR"/tg-$isutil$cmd;;
2234 esac