tg-annihilate.sh: autostash and support --stash and --no-stash
[topgit/pro.git] / tg.sh
blob34827844033d34624fc877976e608b3b0e199d68
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^0" --)"
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="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
750 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ] && [ -s "$tg_ref_cache" ]; then
751 refscacheopt="$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="${TG_DEBUG:+-p=\"\$tg_ref_cache.pre\" }"
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="${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${TG_DEBUG:+ -p=\"\$tg_ref_cache.pre\"}"
920 depscmd="$depscmd"' -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -m="$mtblob" "refs/$topbases"'
921 if [ -n "$userc" ]; then
922 if [ -n "$dorad" ]; then
923 eval "$depscmd" >"$tmpdep"
925 depscmd='<"$tmpdep" '
926 else
927 depscmd="$depscmd |"
929 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
930 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
933 # do_eval CMD
934 # helper for recurse_deps so that a return statement executed inside CMD
935 # does not return from recurse_deps. This shouldn't be necessary, but it
936 # seems that it actually is.
937 do_eval()
939 eval "$@"
942 # becomes read-only for caching purposes
943 # assigns new value to tg_read_only
944 # become_cacheable/undo_become_cacheable calls may be nested
945 become_cacheable()
947 _old_tg_read_only="$tg_read_only"
948 if [ -z "$tg_read_only" ]; then
949 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
950 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
951 tg_read_only=1
953 _my_ref_cache=
954 v_create_ref_cache _my_ref_cache
955 _my_ref_cache="${_my_ref_cache:+1}"
956 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
959 # restores tg_read_only and ref_cache to state before become_cacheable call
960 # become_cacheable/undo_bocome_cacheable calls may be nested
961 undo_become_cacheable()
963 case "$tg_read_only" in
964 "undo"[01]"-"*)
965 _suffix="${tg_read_only#undo?-}"
966 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
967 tg_read_only="$_suffix"
968 esac
971 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
972 become_non_cacheable()
974 remove_ref_cache
975 tg_read_only=
976 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
977 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
980 # call this to make sure Git will not complain about a missing user/email
981 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
982 ensure_ident_available()
984 [ -z "$TG_IDENT_CHECKED" ] || return 0
985 git var GIT_AUTHOR_IDENT >/dev/null &&
986 git var GIT_COMMITTER_IDENT >/dev/null || exit
987 TG_IDENT_CHECKED=1
988 export TG_IDENT_CHECKED
989 return 0
992 # recurse_deps [-o=<options string>] CMD NAME [BRANCHPATH...]
993 # Recursively eval CMD on all dependencies of NAME.
994 # Dependencies are visited in topological order.
995 # If <options string> is given, it's eval'd into the recurse_deps_internal
996 # call just before the "--" that's passed just before NAME
997 # CMD can refer to the following variables:
999 # _ret starts as 0; CMD can change; will be final return result
1000 # _dep bare branch name or "refs/remotes/..." for a remote base
1001 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
1002 # _depchain 0+ space-separated branch names forming a path to top
1003 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
1004 # _dep_is_leaf boolean "1" if leaf; "" if not
1005 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
1006 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
1007 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
1009 # CMD may use a "return" statement without issue; its return value is ignored,
1010 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
1011 # will stop immediately and the value with the leading "-" stripped off will
1012 # be the final result code
1014 # CMD can refer to $_name for queried branch name,
1015 # $_dep for dependency name,
1016 # $_depchain for space-seperated branch backtrace,
1017 # $_dep_missing boolean to check whether $_dep is present
1018 # and the $_dep_is_tgish and $_dep_annihilated booleans.
1019 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
1020 # It can modify $_ret to affect the return value
1021 # of the whole function.
1022 # If recurse_deps() hits missing dependencies, it will append
1023 # them to space-separated $missing_deps list and skip them
1024 # after calling CMD with _dep_missing set.
1025 # remote dependencies are processed if no_remotes is unset.
1026 # any branch names in the space-separated recurse_deps_exclude variable
1027 # are skipped (along with their dependencies)
1029 # If no_remotes is non-empty, exclude remotes
1030 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
1031 # If with_top_level is non-empty, include the top-level that's normally omitted
1032 # any branch names in the space-separated recurse_deps_exclude variable
1033 # are skipped (along with their dependencies)
1034 recurse_deps()
1036 _opts=
1037 case "$1" in -o=*) _opts="${1#-o=}"; shift; esac
1038 _cmd="$1"; shift
1040 _depsfile="$(get_temp tg-depsfile)"
1041 eval recurse_deps_internal "$_opts" -- '"$@"' >"$_depsfile" || :
1043 _ret=0
1044 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1045 _depchain="$_name${_deppath:+ $_deppath}"
1046 _dep_is_tgish=
1047 [ "$_istgish" = "0" ] || _dep_is_tgish=1
1048 _dep_has_remote=
1049 [ "$_istgish" != "2" ] || _dep_has_remote=1
1050 _dep_missing=
1051 if [ "$_ismissing" != "0" ]; then
1052 _dep_missing=1
1053 case " $missing_deps " in *" $_dep "*);;*)
1054 missing_deps="${missing_deps:+$missing_deps }$_dep"
1055 esac
1057 _dep_annihilated=
1058 _dep_is_leaf=
1059 if [ "$_isleaf" = "1" ]; then
1060 _dep_is_leaf=1
1061 elif [ "$_isleaf" = "2" ]; then
1062 _dep_annihilated=1
1064 do_eval "$_cmd" || :
1065 if [ "${_ret#-}" != "$_ret" ]; then
1066 _ret="${_ret#-}"
1067 break
1069 done <"$_depsfile"
1070 rm -f "$_depsfile"
1071 return ${_ret:-0}
1074 # find_leaves NAME
1075 # output (one per line) the unique leaves of NAME
1076 # a leaf is either
1077 # 1) a non-tgish dependency
1078 # 2) the base of a tgish dependency with no non-annihilated dependencies
1079 # duplicates are suppressed (by commit rev) and remotes are always ignored
1080 # if a leaf has an exact tag match that will be output
1081 # note that recurse_deps_exclude IS honored for this operation
1082 find_leaves()
1084 no_remotes=1
1085 with_top_level=1
1086 recurse_preorder=
1087 seen_leaf_refs=
1088 seen_leaf_revs=
1089 while read _ismissing _istgish _isleaf _dep _name _deppath; do
1090 [ "$_isleaf" = "1" ] && [ "$_ismissing" = "0" ] || continue
1091 if [ "$_istgish" != "0" ]; then
1092 fulldep="refs/$topbases/$_dep"
1093 else
1094 fulldep="refs/heads/$_dep"
1096 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1097 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1098 if fullrev="$(ref_exists_rev "$fulldep")"; then
1099 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1100 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1101 # See if Git knows it by another name
1102 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1103 echo "refs/tags/$tagname"
1104 else
1105 echo "$fulldep"
1107 esac
1109 esac
1110 done <<-EOT
1111 $(recurse_deps_internal -l -o=1 -- "$1")
1113 with_top_level=
1116 # branch_needs_update
1117 # This is a helper function for determining whether given branch
1118 # is up-to-date wrt. its dependencies. It expects input as if it
1119 # is called as a recurse_deps() helper.
1120 # In case the branch does need update, it will echo it together
1121 # with the branch backtrace on the output (see needs_update()
1122 # description for details) and set $_ret to non-zero.
1123 branch_needs_update()
1125 if [ -n "$_dep_missing" ]; then
1126 echo "! $_dep $_depchain"
1127 return 0
1130 if [ -n "$_dep_is_tgish" ]; then
1131 [ -z "$_dep_annihilated" ] || return 0
1133 if [ -n "$_dep_has_remote" ]; then
1134 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
1135 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
1137 # We want to sync with our base first and should output this before
1138 # the remote branch, but the order does not actually matter to tg-update
1139 # as it just recurses regardless, but it does matter for tg-info (which
1140 # treats out-of-date bases as though they were already merged in) so
1141 # we output the remote before the base.
1142 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1143 echo ": $_dep $_depchain"
1144 _ret=1
1145 return
1149 if [ -n "$_name" ]; then
1150 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
1151 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1152 # Some new commits in _dep
1153 echo "$_dep $_depchain"
1154 _ret=1
1159 # needs_update NAME
1160 # This function is recursive; it outputs reverse path from NAME
1161 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1162 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
1163 # if the head is not in sync with the <remote> branch <name>, ':' if
1164 # the head is not in sync with the base (in this order of priority)
1165 # or '!' if dependency is missing. Note that the remote branch, base
1166 # order is reversed from the order they will actually be updated in
1167 # order to accomodate tg info which treats out-of-date items that are
1168 # only in the base as already being in the head for status purposes.
1169 # It will also return non-zero status if NAME needs update.
1170 # If needs_update() hits missing dependencies, it will append
1171 # them to space-separated $missing_deps list and skip them.
1172 needs_update()
1174 recurse_deps branch_needs_update "$1"
1177 # branch_empty NAME [-i | -w]
1178 branch_empty()
1180 if [ -z "$2" ]; then
1181 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1182 _result=
1183 _result_rev=
1184 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1185 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
1186 _result=0
1187 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1188 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1189 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1190 return $_result
1191 else
1192 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1196 v_get_tdmopt_internal()
1198 [ -n "$1" ] && [ -n "$3" ] || return 0
1199 [ "$2" = "-i" ] || [ "$2" = "-w" ] || return 0
1200 _optval=
1201 if v_verify_topgit_branch _tghead "HEAD" -f; then
1202 if [ "$2" = "-w" ] && [ -f "$root_dir/$3" ] && [ -r "$root_dir/$3" ]; then
1203 _opthash=
1204 if _opthash="$(git hash-object -w -t blob --stdin <"$root_dir/$3")" && [ -n "$_opthash" ]; then
1205 _optval="$4\"$_tghead:$_opthash\""
1207 elif [ "$2" = "-i" ]; then
1208 if _opthash="$(git rev-parse --quiet --verify ":0:$3" --)" && [ -n "$_opthash" ]; then
1209 _optval="$4\"$_tghead:$_opthash\""
1213 eval "$1="'"$_optval"'
1216 # set var $1 to the correct -td= option for use in an eval for $2 -i or -w mode
1217 v_get_tdopt() { v_get_tdmopt_internal "$1" "$2" ".topdeps" "-td="; }
1219 # set var $1 to the correct -tm= option for use in an eval for $2 -i or -w mode
1220 v_get_tmopt() { v_get_tdmopt_internal "$1" "$2" ".topmsg" "-tm="; }
1222 # checkout_symref_full [-f] FULLREF [SEED]
1223 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1224 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1225 # MUST be a committish which if present will be used instead of current FULLREF
1226 # (and FULLREF will be updated to it as well in that case)
1227 # Any merge state is always cleared by this function
1228 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1229 # instead of -m) but it will clear out any unmerged entries
1230 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1231 checkout_symref_full()
1233 _mode=-m
1234 _head="HEAD"
1235 if [ "$1" = "-f" ]; then
1236 _mode="--reset"
1237 _head=
1238 shift
1240 _ishash=
1241 case "$1" in
1242 refs/?*)
1244 $octet20)
1245 _ishash=1
1246 [ -z "$2" ] || [ "$1" = "$2" ] ||
1247 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1248 set -- HEAD "$1"
1251 die "programmer error: invalid checkout_symref_full \"$1\""
1253 esac
1254 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1255 die "invalid committish: \"${2:-$1}\""
1256 # Clear out any MERGE_HEAD kruft
1257 rm -f "$git_dir/MERGE_HEAD" || :
1258 # We have to do all the hard work ourselves :/
1259 # This is like git checkout -b "$1" "$2"
1260 # (or just git checkout "$1"),
1261 # but never creates a detached HEAD (unless $1 is a hash)
1262 git read-tree -u $_mode $_head "$_seedrev" &&
1264 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1265 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1266 } && {
1267 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1271 # switch_to_base NAME [SEED]
1272 switch_to_base()
1274 checkout_symref_full "refs/$topbases/$1" "$2"
1277 # run editor with arguments
1278 # the editor setting will be cached in $tg_editor (which is eval'd)
1279 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1280 # just in case, noalt_setup will be in effect while the editor is running
1281 run_editor()
1283 tg_editor="$GIT_EDITOR"
1284 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1286 noalt_setup
1287 eval "$tg_editor" '"$@"'
1291 # Show the help messages.
1292 do_help()
1294 _www=
1295 if [ "$1" = "-w" ]; then
1296 _www=1
1297 shift
1299 if [ -z "$1" ] ; then
1300 # This is currently invoked in all kinds of circumstances,
1301 # including when the user made a usage error. Should we end up
1302 # providing more than a short help message, then we should
1303 # differentiate.
1304 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1306 ## Build available commands list for help output
1308 cmds=
1309 sep=
1310 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1311 ! [ -r "$cmd" ] && continue
1312 # strip directory part and "tg-" prefix
1313 cmd="${cmd##*/}"
1314 cmd="${cmd#tg-}"
1315 [ "$cmd" != "migrate-bases" ] || continue
1316 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1317 cmds="$cmds$sep$cmd"
1318 sep="|"
1319 done
1321 echo "TopGit version $TG_VERSION - A different patch queue manager"
1322 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u]" \
1323 "[-c <name>=<val>] [--no-pager] ($cmds) ..."
1324 echo " Or: $tgname help [-w] [<command>]"
1325 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1326 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1327 if [ -n "$_www" ]; then
1328 nohtml=
1329 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1330 echo "${0##*/}: missing html help file:" \
1331 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1332 nohtml=1
1334 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1335 echo "${0##*/}: missing html help file:" \
1336 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1337 nohtml=1
1339 if [ -n "$nohtml" ]; then
1340 echo "${0##*/}: use" \
1341 "\"${0##*/} help $1\" instead" 1>&2
1342 exit 1
1344 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1345 exit
1347 output()
1349 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1350 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1351 echo
1352 elif [ "$1" = "help" ]; then
1353 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1354 echo
1355 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1356 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1357 echo
1359 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1360 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1363 page output "$1"
1364 else
1365 echo "${0##*/}: no help for $1" 1>&2
1366 do_help
1367 exit 1
1371 check_status()
1373 git_state=
1374 git_remove=
1375 if [ -e "$git_dir/MERGE_HEAD" ]; then
1376 git_state="merge"
1377 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1378 git_state="am"
1379 git_remove="$git_dir/rebase-apply"
1380 elif [ -e "$git_dir/rebase-apply" ]; then
1381 git_state="rebase"
1382 git_remove="$git_dir/rebase-apply"
1383 elif [ -e "$git_dir/rebase-merge" ]; then
1384 git_state="rebase"
1385 git_remove="$git_dir/rebase-merge"
1386 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1387 git_state="cherry-pick"
1388 elif [ -e "$git_dir/BISECT_LOG" ]; then
1389 git_state="bisect"
1390 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1391 git_state="revert"
1393 git_remove="${git_remove#./}"
1395 tg_state=
1396 tg_remove=
1397 tg_topmerge=
1398 if [ -e "$git_dir/tg-update" ]; then
1399 tg_state="update"
1400 tg_remove="$git_dir/tg-update"
1401 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1403 tg_remove="${tg_remove#./}"
1406 # Show status information
1407 do_status()
1409 do_status_result=0
1410 do_status_verbose=
1411 do_status_help=
1412 abbrev=refs
1413 pfx=
1414 while [ $# -gt 0 ] && case "$1" in
1415 --help|-h)
1416 do_status_help=1
1417 break;;
1418 -vv)
1419 # kludge in this common bundling option
1420 abbrev=
1421 do_status_verbose=1
1422 pfx="## "
1424 --verbose|-v)
1425 [ -z "$do_status_verbose" ] || abbrev=
1426 do_status_verbose=1
1427 pfx="## "
1429 --exit-code)
1430 do_status_result=2
1433 die "unknown status argument: $1"
1435 esac; do shift; done
1436 if [ -n "$do_status_help" ]; then
1437 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1438 return
1440 check_status
1441 symref="$(git symbolic-ref --quiet HEAD)" || :
1442 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1443 if [ -n "$symref" ]; then
1444 uprefpart=
1445 if [ -n "$headrv" ]; then
1446 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1447 if [ -n "$upref" ]; then
1448 uprefpart=" ... ${upref#$abbrev/remotes/}"
1449 mbase="$(git merge-base HEAD "$upref")" || :
1450 ahead="$(git rev-list --count HEAD ${mbase:+--not $mbase})" || ahead=0
1451 behind="$(git rev-list --count "$upref" ${mbase:+--not $mbase})" || behind=0
1452 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1453 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1454 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1455 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1456 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1459 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1460 else
1461 echol "${pfx}HEAD -> ${headrv:-?}"
1463 if [ -n "$tg_state" ]; then
1464 extra=
1465 if [ "$tg_state" = "update" ]; then
1466 IFS= read -r uname <"$git_dir/tg-update/name" || :
1467 [ -z "$uname" ] ||
1468 extra="; currently updating branch '$uname'"
1470 echol "${pfx}tg $tg_state in progress$extra"
1471 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1472 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1473 cat "$git_dir/tg-update/fullcmd"
1474 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1475 if [ $bcnt -gt 1 ]; then
1476 pcnt=0
1477 ! [ -s "$git_dir/tg-update/processed" ] ||
1478 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1479 echo "${pfx}$pcnt of $bcnt branches updated so far"
1482 if [ "$tg_state" = "update" ]; then
1483 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1484 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1485 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1486 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1489 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1490 if [ "$git_state" = "merge" ]; then
1491 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1492 if [ $ucnt -gt 0 ]; then
1493 echo "${pfx}"'fix conflicts and then "git commit" the result'
1494 else
1495 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1498 if [ -z "$git_state" ]; then
1499 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository
1500 gspcnt=0
1501 [ -z "$gsp" ] ||
1502 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1503 untr=
1504 if [ "$gspcnt" -eq 0 ]; then
1505 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1506 echo "${pfx}working directory is clean$untr"
1507 [ -n "$tg_state" ] || do_status_result=0
1508 else
1509 echo "${pfx}working directory is DIRTY"
1510 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1515 ## Pager stuff
1517 # isatty FD
1518 isatty()
1520 test -t $1
1523 # pass "diff" to get pager.diff
1524 # if pager.$1 is a boolean false returns cat
1525 # if set to true or unset fails
1526 # otherwise succeeds and returns the value
1527 get_pager()
1529 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1530 [ "$_x" != "true" ] || return 1
1531 echo "cat"
1532 return 0
1534 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1535 echol "$_x"
1536 return 0
1538 return 1
1541 # setup_pager
1542 # Set TG_PAGER to a valid executable
1543 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1544 # See also the following "page" function for ease of use
1545 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1546 # Preference is (same as Git):
1547 # 1. GIT_PAGER
1548 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1549 # 3. core.pager (only if set)
1550 # 4. PAGER
1551 # 5. git var GIT_PAGER
1552 # 6. less
1553 setup_pager()
1555 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1557 emptypager=
1558 if [ -z "$TG_PAGER_IN_USE" ]; then
1559 # TG_PAGER = GIT_PAGER | PAGER | less
1560 # NOTE: GIT_PAGER='' is significant
1561 if [ -n "${GIT_PAGER+set}" ]; then
1562 TG_PAGER="$GIT_PAGER"
1563 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1564 TG_PAGER="$_dp"
1565 elif _cp="$(git config core.pager 2>/dev/null)"; then
1566 TG_PAGER="$_cp"
1567 elif [ -n "${PAGER+set}" ]; then
1568 TG_PAGER="$PAGER"
1569 else
1570 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1571 [ "$_gp" != ":" ] || _gp=
1572 TG_PAGER="${_gp:-less}"
1574 if [ -z "$TG_PAGER" ]; then
1575 emptypager=1
1576 TG_PAGER=cat
1578 else
1579 emptypager=1
1580 TG_PAGER=cat
1583 # Set pager default environment variables
1584 # see pager.c:setup_pager
1585 if [ -z "${LESS+set}" ]; then
1586 LESS="-FRX"
1587 export LESS
1589 if [ -z "${LV+set}" ]; then
1590 LV="-c"
1591 export LV
1594 # this is needed so e.g. $(git diff) will still colorize it's output if
1595 # requested in ~/.gitconfig with color.diff=auto
1596 GIT_PAGER_IN_USE=1
1597 export GIT_PAGER_IN_USE
1599 # this is needed so we don't get nested pagers
1600 TG_PAGER_IN_USE=1
1601 export TG_PAGER_IN_USE
1604 # page eval_arg [arg ...]
1606 # Calls setup_pager then evals the first argument passing it all the rest
1607 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1608 # by setup_pager (in which case the output is left as-is).
1610 # To handle arbitrary paging duties, collect lines to be paged into a
1611 # function and then call page with the function name or perhaps func_name "$@".
1613 # If no arguments at all are passed in do nothing (return with success).
1614 page()
1616 [ $# -gt 0 ] || return 0
1617 setup_pager
1618 _evalarg="$1"; shift
1619 if [ -n "$emptypager" ]; then
1620 eval "$_evalarg" '"$@"'
1621 else
1622 { eval "$_evalarg" '"$@"';} | eval "$TG_PAGER"
1626 # get_temp NAME [-d]
1627 # creates a new temporary file (or directory with -d) in the global
1628 # temporary directory $tg_tmp_dir with pattern prefix NAME
1629 get_temp()
1631 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1634 # automatically called by strftime
1635 # does nothing if already setup
1636 # may be called explicitly if the first call would otherwise be in a subshell
1637 # so that the setup is only done once before subshells start being spawned
1638 setup_strftime()
1640 [ -z "$strftime_is_setup" ] || return 0
1642 # date option to format raw epoch seconds values
1643 daterawopt=
1644 _testes='951807788'
1645 _testdt='2000-02-29 07:03:08 UTC'
1646 _testfm='%Y-%m-%d %H:%M:%S %Z'
1647 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1648 daterawopt='-d@'
1649 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1650 daterawopt='-r'
1652 strftime_is_setup=1
1655 # $1 => strftime format string to use
1656 # $2 => raw timestamp as seconds since epoch
1657 # $3 => optional time zone string (empty/absent for local time zone)
1658 strftime()
1660 setup_strftime
1661 if [ -n "$daterawopt" ]; then
1662 if [ -n "$3" ]; then
1663 TZ="$3" date "$daterawopt$2" "+$1"
1664 else
1665 date "$daterawopt$2" "+$1"
1667 else
1668 if [ -n "$3" ]; then
1669 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1670 else
1671 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1676 got_cdup_result=
1677 git_cdup_result=
1678 v_get_show_cdup()
1680 if [ -z "$got_cdup_result" ]; then
1681 git_cdup_result="$(git rev-parse --show-cdup)"
1682 got_cdup_result=1
1684 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1687 setup_git_dirs()
1689 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1690 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1691 git_dir="$(cd "$git_dir" && pwd)"
1693 if [ -z "$git_common_dir" ]; then
1694 if vcmp "$git_version" '>=' "2.5"; then
1695 # rev-parse --git-common-dir is broken and may give
1696 # an incorrect result unless the current directory is
1697 # already set to the top level directory
1698 v_get_show_cdup
1699 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1700 else
1701 git_common_dir="$git_dir"
1704 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1705 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1706 git_hooks_dir="$git_common_dir/hooks"
1707 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1708 case "$gchp" in
1709 /[!/]*)
1710 git_hooks_dir="$gchp"
1713 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1715 esac
1716 unset gchp
1720 basic_setup()
1722 setup_git_dirs $1
1723 if [ -z "$base_remote" ]; then
1724 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
1725 base_remote="$TG_EXPLICIT_REMOTE"
1726 else
1727 base_remote="$(git config topgit.remote 2>/dev/null)" || :
1730 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1731 tgnosequester=
1732 [ "$tgsequester" != "false" ] || tgnosequester=1
1733 unset tgsequester
1735 # catch errors if topbases is used without being set
1736 unset tg_topbases_set
1737 topbases="programmer*:error"
1738 topbasesrx="programmer*:error}"
1739 oldbases="$topbases"
1742 ## Initial setup
1743 initial_setup()
1745 # suppress the merge log editor feature since git 1.7.10
1747 GIT_MERGE_AUTOEDIT=no
1748 export GIT_MERGE_AUTOEDIT
1750 basic_setup $1
1751 iowopt=
1752 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
1753 gcfbopt=
1754 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
1755 auhopt=
1756 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1757 v_get_show_cdup root_dir
1758 root_dir="${root_dir:-.}"
1759 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1760 [ "$logrefupdates" = "true" ] || logrefupdates=
1762 # make sure root_dir doesn't end with a trailing slash.
1764 root_dir="${root_dir%/}"
1766 # create global temporary directories, inside GIT_DIR
1768 tg_tmp_dir=
1769 trap '${TG_DEBUG:+echo} rm -rf "$tg_tmp_dir" >&2' EXIT
1770 trap 'exit 129' HUP
1771 trap 'exit 130' INT
1772 trap 'exit 131' QUIT
1773 trap 'exit 134' ABRT
1774 trap 'exit 143' TERM
1775 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1776 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1777 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1778 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1779 tg_ref_cache_br="$tg_ref_cache.br"
1780 tg_ref_cache_rbr="$tg_ref_cache.rbr"
1781 tg_ref_cache_ann="$tg_ref_cache.ann"
1782 tg_ref_cache_dep="$tg_ref_cache.dep"
1783 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_ref_cache"; } >/dev/null 2>&1 ||
1784 die "could not create a writable temporary directory"
1786 # make sure global cache directory exists inside GIT_DIR or $tg_tmp_dir
1788 user_id_no="$(id -u)" || :
1789 : "${user_id_no:=_99_}"
1790 tg_cache_dir="$git_common_dir/tg-cache"
1791 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1792 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
1793 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1794 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1795 if [ -z "$tg_cache_dir" ]; then
1796 tg_cache_dir="$tg_tmp_dir/tg-cache"
1797 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1798 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1800 [ -n "$tg_cache_dir" ] ||
1801 die "could not create a writable tg-cache directory (even a temporary one)"
1803 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
1804 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
1805 # so we avoid it if possible and require v2.11.1 to do it at all
1806 # otherwise just don't make an alternates temporary store in that case;
1807 # it's okay to not have one; everything will still work; the nicety of
1808 # making the temporary tree objects vanish when tg exits just won't
1809 # happen in that case but nothing will break also be sure to reuse
1810 # the parent's if we've been recursively invoked and it's for the
1811 # same repository we were invoked on
1813 tg_use_alt_odb=1
1814 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
1815 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] || tg_use_alt_odb=
1816 _fulltmpdir=
1817 [ -z "$tg_use_alt_odb" ] || _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
1818 case "$_fulltmpdir" in *[";:"]*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
1819 _fullodbdir=
1820 [ -z "$tg_use_alt_odb" ] || _fullodbdir="$(cd "$_odbdir" && pwd -P)"
1821 if [ -n "$tg_use_alt_odb" ] && [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
1822 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
1823 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
1824 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
1825 tg_use_alt_odb=2
1828 if [ "$tg_use_alt_odb" = "1" ]; then
1829 # create an alternate objects database to keep the ephemeral objects in
1830 mkdir -p "$tg_tmp_dir/objects/info"
1831 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
1832 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
1833 case "$TG_OBJECT_DIRECTORY" in
1834 *[";:"]*)
1835 # surround in "..." and backslash-escape internal '"' and '\\'
1836 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
1837 sed 's/\([""\\]\)/\\\1/g')\""
1840 _altodbdq="$TG_OBJECT_DIRECTORY"
1842 esac
1843 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1844 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
1845 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1846 else
1847 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
1849 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
1853 noalt_setup()
1855 if [ "${TG_PRESERVED_ALTERNATES+set}" = "set" ]; then
1856 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
1857 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
1858 export GIT_ALTERNATE_OBJECT_DIRECTORIES
1859 else
1860 unset GIT_ALTERNATE_OBJECT_DIRECTORIES
1863 unset TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES tg_use_alt_odb
1866 set_topbases()
1868 # refer to "top-bases" in a refname with $topbases
1870 [ -z "$tg_topbases_set" ] || return 0
1872 topbases_implicit_default=1
1873 # See if topgit.top-bases is set to heads or refs
1874 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
1875 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
1876 if [ -n "$1" ]; then
1877 # never die on the hook script
1878 unset tgtb
1879 else
1880 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
1883 if [ -n "$tgtb" ]; then
1884 case "$tgtb" in
1885 heads)
1886 topbases="heads/{top-bases}"
1887 topbasesrx="heads/[{]top-bases[}]"
1888 oldbases="top-bases";;
1889 refs)
1890 topbases="top-bases"
1891 topbasesrx="top-bases"
1892 oldbases="heads/{top-bases}";;
1893 esac
1894 # MUST NOT be exported
1895 unset tgtb tg_topbases_set topbases_implicit_default
1896 tg_topbases_set=1
1897 return 0
1899 unset tgtb
1901 # check heads and top-bases and see what state the current
1902 # repository is in. remotes are ignored.
1904 rc=0 activebases=
1905 activebases="$(
1906 git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null |
1907 run_awk_ref_prefixes ${1:+-e} -n -- "refs/heads/{top-bases}" "refs/top-bases" "refs/heads")" ||
1908 rc=$?
1909 if [ "$rc" = "65" ]; then
1910 # Complain and die
1911 err "repository contains existing TopGit branches"
1912 err "but some use refs/top-bases/... for the base"
1913 err "and some use refs/heads/{top-bases}/... for the base"
1914 err "with the latter being the new, preferred location"
1915 err "set \"topgit.top-bases\" to either \"heads\" to use"
1916 err "the new heads/{top-bases} location or \"refs\" to use"
1917 err "the old top-bases location."
1918 err "(the tg migrate-bases command can also resolve this issue)"
1919 die "schizophrenic repository requires topgit.top-bases setting"
1921 [ -z "$activebases" ] || unset topbases_implicit_default
1922 if [ "$activebases" = "refs/heads/{top-bases}" ]; then
1923 topbases="heads/{top-bases}"
1924 topbasesrx="heads/[{]top-bases[}]"
1925 oldbases="top-bases"
1926 else
1927 # default is still top-bases for now
1928 topbases="top-bases"
1929 topbasesrx="top-bases"
1930 oldbases="heads/{top-bases}"
1932 # MUST NOT be exported
1933 unset rc activebases tg_topases_set
1934 tg_topbases_set=1
1935 return 0
1938 # init_reflog "ref"
1939 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
1940 # an empty log file to exist so that ref changes will be logged
1941 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
1942 # However, if "$1" is "refs/tgstash" then always make the reflog
1943 # The only ref not under refs/ that Git will write a reflog for is HEAD;
1944 # no matter what, it will NOT update a reflog for any other bare refs so
1945 # just quietly succeed when passed TG_STASH without doing anything.
1946 init_reflog()
1948 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
1949 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
1950 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
1951 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
1952 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
1955 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
1956 # a symbolic link. The directory part must exist, but the basename need not.
1957 v_get_abs_path()
1959 [ -n "$1" ] && [ -n "$2" ] || return 1
1960 set -- "$1" "$2" "${2%/}"
1961 case "$3" in
1962 */*) set -- "$1" "$2" "${3%/*}";;
1963 * ) set -- "$1" "$2" ".";;
1964 esac
1965 case "$2" in */)
1966 set -- "$1" "${2%/}" "$3" "/"
1967 esac
1968 [ -d "$3" ] || return 1
1969 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
1972 ## Startup
1974 : "${TG_INST_CMDDIR:=@cmddir@}"
1975 : "${TG_INST_SHAREDIR:=@sharedir@}"
1976 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1978 [ -d "$TG_INST_CMDDIR" ] ||
1979 die "No command directory: '$TG_INST_CMDDIR'"
1981 ## Include awk scripts and their utility functions (separated for easier debugging)
1983 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
1984 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
1985 . "$TG_INST_CMDDIR/tg--awksome"
1987 if [ -n "$tg__include" ]; then
1989 # We were sourced from another script for our utility functions;
1990 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1991 # work as expected in every shell. See http://bugs.debian.org/516188
1993 # ensure setup happens
1995 initial_setup 1
1996 set_topbases 1
1997 noalt_setup
1999 else
2001 set -e
2003 tgbin="$0"
2004 tgdir="${tgbin%/}"
2005 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
2006 tgdir="${tgdir%/*}/"
2007 tgname="${tgbin##*/}"
2008 [ "$0" != "$tgname" ] || tgdir=""
2010 # If tg contains a '/' but does not start with one then replace it with an absolute path
2012 case "$0" in /*) ;; */*)
2013 tgdir="$(cd "${0%/*}" && pwd -P)/"
2014 tgbin="$tgdir$tgname"
2015 esac
2017 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
2018 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2020 tgdisplaydir="$tgdir"
2021 tgdisplay="$tgbin"
2022 tgdisplayac="$tgdisplay"
2024 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2025 _tgabs="$_tgnameabs" &&
2026 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2027 [ "$_tgabs" = "$_tgnameabs" ]
2028 then
2029 tgdisplaydir=""
2030 tgdisplay="$tgname"
2031 tgdisplayac="$tgdisplay"
2033 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2034 unset _tgabs _tgnameabs
2036 tg() { command "$tgbin" "$@"; }
2038 explicit_remote=
2039 explicit_dir=
2040 gitcdopt=
2041 noremote=
2043 cmd=
2044 while :; do case "$1" in
2046 help|--help|-h)
2047 cmd=help
2048 shift
2049 break;;
2051 status|--status)
2052 cmd=status
2053 shift
2054 break;;
2056 --hooks-path)
2057 cmd=hooks-path
2058 shift
2059 break;;
2061 --exec-path)
2062 cmd=exec-path
2063 shift
2064 break;;
2066 --top-bases)
2067 cmd=top-bases
2068 shift
2069 break;;
2071 --no-pager)
2072 GIT_PAGER_IN_USE=1 TG_PAGER_IN_USE=1 &&
2073 export GIT_PAGER_IN_USE TG_PAGER_IN_USE
2074 shift;;
2077 shift
2078 if [ -z "$1" ]; then
2079 echo "Option -r requires an argument." >&2
2080 do_help
2081 exit 1
2083 unset noremote
2084 base_remote="$1"
2085 explicit_remote="$base_remote"
2086 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2087 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2088 shift;;
2091 unset base_remote explicit_remote
2092 noremote=1
2093 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2094 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2095 shift;;
2098 shift
2099 if [ -z "$1" ]; then
2100 echo "Option -C requires an argument." >&2
2101 do_help
2102 exit 1
2104 cd "$1"
2105 unset GIT_DIR GIT_COMMON_DIR
2106 if [ -z "$explicit_dir" ]; then
2107 explicit_dir="$1"
2108 else
2109 explicit_dir="$PWD"
2111 gitcdopt=" -C \"$explicit_dir\""
2112 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2113 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2114 tgdisplayac="$tgdisplay"
2115 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2116 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2117 shift;;
2120 shift
2121 if [ -z "$1" ]; then
2122 echo "Option -c requires an argument." >&2
2123 do_help
2124 exit 1
2126 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2127 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2128 export GIT_CONFIG_PARAMETERS
2129 shift;;
2132 shift
2133 break;;
2136 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2137 do_help
2138 exit 1;;
2141 break;;
2143 esac; done
2145 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
2147 ## Dispatch
2149 [ -n "$cmd" ] || { do_help; exit 1; }
2151 case "$cmd" in
2153 help)
2154 do_help "$@"
2155 exit 0;;
2157 status|st)
2158 unset base_remote
2159 basic_setup
2160 set_topbases
2161 do_status "$@"
2162 exit ${do_status_result:-0};;
2164 hooks-path)
2165 # Internal command
2166 echol "$TG_INST_HOOKSDIR";;
2168 exec-path)
2169 # Internal command
2170 echol "$TG_INST_CMDDIR";;
2172 top-bases)
2173 # Maintenance command
2174 ! git rev-parse --git-dir >/dev/null 2>&1 || setup_git_dirs
2175 set_topbases
2176 echol "refs/$topbases";;
2179 isutil=
2180 case "$cmd" in index-merge-one-file)
2181 isutil="-"
2182 esac
2183 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2184 looplevel="$TG_ALIAS_DEPTH"
2185 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2186 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2187 looplevel=0
2188 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2189 [ -n "$tgalias" ] || {
2190 echo "Unknown subcommand: $cmd" >&2
2191 do_help
2192 exit 1
2194 looplevel=$(( $looplevel + 1 ))
2195 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2196 TG_ALIAS_DEPTH="$looplevel"
2197 export TG_ALIAS_DEPTH
2198 if [ "!${tgalias#?}" = "$tgalias" ]; then
2199 unset GIT_PREFIX
2200 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2201 GIT_PREFIX="$pfx"
2202 export GIT_PREFIX
2204 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2205 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2206 else
2207 eval 'exec "$tgbin"' "$tgalias" '"$@"'
2209 die "alias execution failed for: $tgalias"
2211 unset TG_ALIAS_DEPTH
2213 showing_help=
2214 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2215 showing_help=1
2218 [ -n "$showing_help" ] || initial_setup
2219 [ -z "$noremote" ] || unset base_remote
2221 nomergesetup="$showing_help"
2222 case "$cmd" in base|contains|info|log|rebase|revert|summary|tag)
2223 # avoid merge setup where not necessary
2225 nomergesetup=1
2226 esac
2228 if [ -z "$nomergesetup" ]; then
2229 # make sure merging the .top* files will always behave sanely
2231 setup_ours
2232 setup_hook "pre-commit"
2235 # everything but rebase needs topbases set
2236 carefully="$showing_help"
2237 [ "$cmd" != "migrate-bases" ] || carefully=1
2238 [ "$cmd" = "rebase" ] || set_topbases $carefully
2240 _use_ref_cache=
2241 tg_read_only=1
2242 _suppress_alt=
2243 case "$cmd$showing_help" in
2244 contains|info|summary|tag)
2245 _use_ref_cache=1;;
2246 "export")
2247 _use_ref_cache=1
2248 suppress_alt=1;;
2249 annihilate|create|delete|depend|import|update)
2250 tg_read_only=
2251 suppress_alt=1;;
2252 esac
2253 [ -z "$_suppress_alt" ] || noalt_setup
2254 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2256 fullcmd="${tgname:-tg} $cmd $*"
2257 . "$TG_INST_CMDDIR"/tg-$isutil$cmd;;
2258 esac