tg-patch.sh: get all awked up on --from
[topgit/pro.git] / tg.sh
blob84771049859d2845d2b2c598bec38157aaabe8d0
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 # list_deps [-i | -w] [BRANCH]
1196 # -i/-w apply only to HEAD
1197 list_deps()
1199 head_from=
1200 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
1201 head="$(git symbolic-ref -q HEAD)" ||
1202 head="..detached.."
1204 git for-each-ref --format='%(objectname) %(refname)' "refs/$topbases${1:+/$1}" |
1205 while read rev ref; do
1206 name="${ref#refs/$topbases/}"
1207 if branch_annihilated "$name" "" "$rev"; then
1208 continue
1211 from=$head_from
1212 [ "refs/heads/$name" = "$head" ] ||
1213 from=
1214 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
1215 dep_is_tgish=true
1216 ref_exists "refs/$topbases/$dep" ||
1217 dep_is_tgish=false
1218 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
1219 echo "$name $dep"
1221 done
1222 done
1225 # checkout_symref_full [-f] FULLREF [SEED]
1226 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1227 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1228 # MUST be a committish which if present will be used instead of current FULLREF
1229 # (and FULLREF will be updated to it as well in that case)
1230 # Any merge state is always cleared by this function
1231 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1232 # instead of -m) but it will clear out any unmerged entries
1233 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1234 checkout_symref_full()
1236 _mode=-m
1237 _head="HEAD"
1238 if [ "$1" = "-f" ]; then
1239 _mode="--reset"
1240 _head=
1241 shift
1243 _ishash=
1244 case "$1" in
1245 refs/?*)
1247 $octet20)
1248 _ishash=1
1249 [ -z "$2" ] || [ "$1" = "$2" ] ||
1250 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1251 set -- HEAD "$1"
1254 die "programmer error: invalid checkout_symref_full \"$1\""
1256 esac
1257 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1258 die "invalid committish: \"${2:-$1}\""
1259 # Clear out any MERGE_HEAD kruft
1260 rm -f "$git_dir/MERGE_HEAD" || :
1261 # We have to do all the hard work ourselves :/
1262 # This is like git checkout -b "$1" "$2"
1263 # (or just git checkout "$1"),
1264 # but never creates a detached HEAD (unless $1 is a hash)
1265 git read-tree -u $_mode $_head "$_seedrev" &&
1267 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1268 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1269 } && {
1270 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1274 # switch_to_base NAME [SEED]
1275 switch_to_base()
1277 checkout_symref_full "refs/$topbases/$1" "$2"
1280 # run editor with arguments
1281 # the editor setting will be cached in $tg_editor (which is eval'd)
1282 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1283 run_editor()
1285 tg_editor="$GIT_EDITOR"
1286 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1287 eval "$tg_editor" '"$@"'
1290 # Show the help messages.
1291 do_help()
1293 _www=
1294 if [ "$1" = "-w" ]; then
1295 _www=1
1296 shift
1298 if [ -z "$1" ] ; then
1299 # This is currently invoked in all kinds of circumstances,
1300 # including when the user made a usage error. Should we end up
1301 # providing more than a short help message, then we should
1302 # differentiate.
1303 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1305 ## Build available commands list for help output
1307 cmds=
1308 sep=
1309 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1310 ! [ -r "$cmd" ] && continue
1311 # strip directory part and "tg-" prefix
1312 cmd="${cmd##*/}"
1313 cmd="${cmd#tg-}"
1314 [ "$cmd" != "migrate-bases" ] || continue
1315 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1316 cmds="$cmds$sep$cmd"
1317 sep="|"
1318 done
1320 echo "TopGit version $TG_VERSION - A different patch queue manager"
1321 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
1322 echo " Or: $tgname help [-w] [<command>]"
1323 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1324 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1325 if [ -n "$_www" ]; then
1326 nohtml=
1327 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1328 echo "${0##*/}: missing html help file:" \
1329 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1330 nohtml=1
1332 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1333 echo "${0##*/}: missing html help file:" \
1334 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1335 nohtml=1
1337 if [ -n "$nohtml" ]; then
1338 echo "${0##*/}: use" \
1339 "\"${0##*/} help $1\" instead" 1>&2
1340 exit 1
1342 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1343 exit
1345 output()
1347 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1348 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1349 echo
1350 elif [ "$1" = "help" ]; then
1351 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1352 echo
1353 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1354 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1355 echo
1357 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1358 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1361 page output "$1"
1362 else
1363 echo "${0##*/}: no help for $1" 1>&2
1364 do_help
1365 exit 1
1369 check_status()
1371 git_state=
1372 git_remove=
1373 if [ -e "$git_dir/MERGE_HEAD" ]; then
1374 git_state="merge"
1375 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1376 git_state="am"
1377 git_remove="$git_dir/rebase-apply"
1378 elif [ -e "$git_dir/rebase-apply" ]; then
1379 git_state="rebase"
1380 git_remove="$git_dir/rebase-apply"
1381 elif [ -e "$git_dir/rebase-merge" ]; then
1382 git_state="rebase"
1383 git_remove="$git_dir/rebase-merge"
1384 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1385 git_state="cherry-pick"
1386 elif [ -e "$git_dir/BISECT_LOG" ]; then
1387 git_state="bisect"
1388 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1389 git_state="revert"
1391 git_remove="${git_remove#./}"
1393 tg_state=
1394 tg_remove=
1395 tg_topmerge=
1396 if [ -e "$git_dir/tg-update" ]; then
1397 tg_state="update"
1398 tg_remove="$git_dir/tg-update"
1399 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1401 tg_remove="${tg_remove#./}"
1404 # Show status information
1405 do_status()
1407 do_status_result=0
1408 do_status_verbose=
1409 do_status_help=
1410 abbrev=refs
1411 pfx=
1412 while [ $# -gt 0 ] && case "$1" in
1413 --help|-h)
1414 do_status_help=1
1415 break;;
1416 -vv)
1417 # kludge in this common bundling option
1418 abbrev=
1419 do_status_verbose=1
1420 pfx="## "
1422 --verbose|-v)
1423 [ -z "$do_status_verbose" ] || abbrev=
1424 do_status_verbose=1
1425 pfx="## "
1427 --exit-code)
1428 do_status_result=2
1431 die "unknown status argument: $1"
1433 esac; do shift; done
1434 if [ -n "$do_status_help" ]; then
1435 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1436 return
1438 check_status
1439 symref="$(git symbolic-ref --quiet HEAD)" || :
1440 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1441 if [ -n "$symref" ]; then
1442 uprefpart=
1443 if [ -n "$headrv" ]; then
1444 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1445 if [ -n "$upref" ]; then
1446 uprefpart=" ... ${upref#$abbrev/remotes/}"
1447 mbase="$(git merge-base HEAD "$upref")" || :
1448 ahead="$(git rev-list --count HEAD ${mbase:+--not $mbase})" || ahead=0
1449 behind="$(git rev-list --count "$upref" ${mbase:+--not $mbase})" || behind=0
1450 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1451 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1452 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1453 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1454 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1457 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1458 else
1459 echol "${pfx}HEAD -> ${headrv:-?}"
1461 if [ -n "$tg_state" ]; then
1462 extra=
1463 if [ "$tg_state" = "update" ]; then
1464 IFS= read -r uname <"$git_dir/tg-update/name" || :
1465 [ -z "$uname" ] ||
1466 extra="; currently updating branch '$uname'"
1468 echol "${pfx}tg $tg_state in progress$extra"
1469 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1470 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1471 cat "$git_dir/tg-update/fullcmd"
1472 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1473 if [ $bcnt -gt 1 ]; then
1474 pcnt=0
1475 ! [ -s "$git_dir/tg-update/processed" ] ||
1476 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1477 echo "${pfx}$pcnt of $bcnt branches updated so far"
1480 if [ "$tg_state" = "update" ]; then
1481 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1482 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1483 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1484 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1487 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1488 if [ "$git_state" = "merge" ]; then
1489 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1490 if [ $ucnt -gt 0 ]; then
1491 echo "${pfx}"'fix conflicts and then "git commit" the result'
1492 else
1493 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1496 if [ -z "$git_state" ]; then
1497 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository
1498 gspcnt=0
1499 [ -z "$gsp" ] ||
1500 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1501 untr=
1502 if [ "$gspcnt" -eq 0 ]; then
1503 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1504 echo "${pfx}working directory is clean$untr"
1505 [ -n "$tg_state" ] || do_status_result=0
1506 else
1507 echo "${pfx}working directory is DIRTY"
1508 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1513 ## Pager stuff
1515 # isatty FD
1516 isatty()
1518 test -t $1
1521 # pass "diff" to get pager.diff
1522 # if pager.$1 is a boolean false returns cat
1523 # if set to true or unset fails
1524 # otherwise succeeds and returns the value
1525 get_pager()
1527 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1528 [ "$_x" != "true" ] || return 1
1529 echo "cat"
1530 return 0
1532 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1533 echol "$_x"
1534 return 0
1536 return 1
1539 # setup_pager
1540 # Set TG_PAGER to a valid executable
1541 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1542 # See also the following "page" function for ease of use
1543 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1544 # Preference is (same as Git):
1545 # 1. GIT_PAGER
1546 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1547 # 3. core.pager (only if set)
1548 # 4. PAGER
1549 # 5. git var GIT_PAGER
1550 # 6. less
1551 setup_pager()
1553 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1555 emptypager=
1556 if [ -z "$TG_PAGER_IN_USE" ]; then
1557 # TG_PAGER = GIT_PAGER | PAGER | less
1558 # NOTE: GIT_PAGER='' is significant
1559 if [ -n "${GIT_PAGER+set}" ]; then
1560 TG_PAGER="$GIT_PAGER"
1561 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1562 TG_PAGER="$_dp"
1563 elif _cp="$(git config core.pager 2>/dev/null)"; then
1564 TG_PAGER="$_cp"
1565 elif [ -n "${PAGER+set}" ]; then
1566 TG_PAGER="$PAGER"
1567 else
1568 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1569 [ "$_gp" != ":" ] || _gp=
1570 TG_PAGER="${_gp:-less}"
1572 if [ -z "$TG_PAGER" ]; then
1573 emptypager=1
1574 TG_PAGER=cat
1576 else
1577 emptypager=1
1578 TG_PAGER=cat
1581 # Set pager default environment variables
1582 # see pager.c:setup_pager
1583 if [ -z "${LESS+set}" ]; then
1584 LESS="-FRX"
1585 export LESS
1587 if [ -z "${LV+set}" ]; then
1588 LV="-c"
1589 export LV
1592 # this is needed so e.g. $(git diff) will still colorize it's output if
1593 # requested in ~/.gitconfig with color.diff=auto
1594 GIT_PAGER_IN_USE=1
1595 export GIT_PAGER_IN_USE
1597 # this is needed so we don't get nested pagers
1598 TG_PAGER_IN_USE=1
1599 export TG_PAGER_IN_USE
1602 # page eval_arg [arg ...]
1604 # Calls setup_pager then evals the first argument passing it all the rest
1605 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1606 # by setup_pager (in which case the output is left as-is).
1608 # To handle arbitrary paging duties, collect lines to be paged into a
1609 # function and then call page with the function name or perhaps func_name "$@".
1611 # If no arguments at all are passed in do nothing (return with success).
1612 page()
1614 [ $# -gt 0 ] || return 0
1615 setup_pager
1616 _evalarg="$1"; shift
1617 if [ -n "$emptypager" ]; then
1618 eval "$_evalarg" '"$@"'
1619 else
1620 { eval "$_evalarg" '"$@"';} | eval "$TG_PAGER"
1624 # get_temp NAME [-d]
1625 # creates a new temporary file (or directory with -d) in the global
1626 # temporary directory $tg_tmp_dir with pattern prefix NAME
1627 get_temp()
1629 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1632 # automatically called by strftime
1633 # does nothing if already setup
1634 # may be called explicitly if the first call would otherwise be in a subshell
1635 # so that the setup is only done once before subshells start being spawned
1636 setup_strftime()
1638 [ -z "$strftime_is_setup" ] || return 0
1640 # date option to format raw epoch seconds values
1641 daterawopt=
1642 _testes='951807788'
1643 _testdt='2000-02-29 07:03:08 UTC'
1644 _testfm='%Y-%m-%d %H:%M:%S %Z'
1645 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1646 daterawopt='-d@'
1647 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1648 daterawopt='-r'
1650 strftime_is_setup=1
1653 # $1 => strftime format string to use
1654 # $2 => raw timestamp as seconds since epoch
1655 # $3 => optional time zone string (empty/absent for local time zone)
1656 strftime()
1658 setup_strftime
1659 if [ -n "$daterawopt" ]; then
1660 if [ -n "$3" ]; then
1661 TZ="$3" date "$daterawopt$2" "+$1"
1662 else
1663 date "$daterawopt$2" "+$1"
1665 else
1666 if [ -n "$3" ]; then
1667 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1668 else
1669 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1674 got_cdup_result=
1675 git_cdup_result=
1676 v_get_show_cdup()
1678 if [ -z "$got_cdup_result" ]; then
1679 git_cdup_result="$(git rev-parse --show-cdup)"
1680 got_cdup_result=1
1682 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1685 setup_git_dirs()
1687 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1688 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1689 git_dir="$(cd "$git_dir" && pwd)"
1691 if [ -z "$git_common_dir" ]; then
1692 if vcmp "$git_version" '>=' "2.5"; then
1693 # rev-parse --git-common-dir is broken and may give
1694 # an incorrect result unless the current directory is
1695 # already set to the top level directory
1696 v_get_show_cdup
1697 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1698 else
1699 git_common_dir="$git_dir"
1702 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1703 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1704 git_hooks_dir="$git_common_dir/hooks"
1705 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1706 case "$gchp" in
1707 /[!/]*)
1708 git_hooks_dir="$gchp"
1711 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1713 esac
1714 unset gchp
1718 basic_setup()
1720 setup_git_dirs $1
1721 if [ -z "$base_remote" ]; then
1722 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
1723 base_remote="$TG_EXPLICIT_REMOTE"
1724 else
1725 base_remote="$(git config topgit.remote 2>/dev/null)" || :
1728 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1729 tgnosequester=
1730 [ "$tgsequester" != "false" ] || tgnosequester=1
1731 unset tgsequester
1733 # catch errors if topbases is used without being set
1734 unset tg_topbases_set
1735 topbases="programmer*:error"
1736 topbasesrx="programmer*:error}"
1737 oldbases="$topbases"
1740 ## Initial setup
1741 initial_setup()
1743 # suppress the merge log editor feature since git 1.7.10
1745 GIT_MERGE_AUTOEDIT=no
1746 export GIT_MERGE_AUTOEDIT
1748 basic_setup $1
1749 iowopt=
1750 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
1751 gcfbopt=
1752 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
1753 auhopt=
1754 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1755 v_get_show_cdup root_dir
1756 root_dir="${root_dir:-.}"
1757 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1758 [ "$logrefupdates" = "true" ] || logrefupdates=
1760 # make sure root_dir doesn't end with a trailing slash.
1762 root_dir="${root_dir%/}"
1764 # create global temporary directories, inside GIT_DIR
1766 tg_tmp_dir=
1767 trap 'rm -rf "$tg_tmp_dir"' EXIT
1768 trap 'exit 129' HUP
1769 trap 'exit 130' INT
1770 trap 'exit 131' QUIT
1771 trap 'exit 134' ABRT
1772 trap 'exit 143' TERM
1773 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1774 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1775 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1776 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1777 tg_ref_cache_br="$tg_ref_cache.br"
1778 tg_ref_cache_rbr="$tg_ref_cache.rbr"
1779 tg_ref_cache_ann="$tg_ref_cache.ann"
1780 tg_ref_cache_dep="$tg_ref_cache.dep"
1781 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_ref_cache"; } >/dev/null 2>&1 ||
1782 die "could not create a writable temporary directory"
1784 # make sure global cache directory exists inside GIT_DIR or $tg_tmp_dir
1786 user_id_no="$(id -u)" || :
1787 : "${user_id_no:=_99_}"
1788 tg_cache_dir="$git_common_dir/tg-cache"
1789 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1790 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
1791 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1792 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1793 if [ -z "$tg_cache_dir" ]; then
1794 tg_cache_dir="$tg_tmp_dir/tg-cache"
1795 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1796 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1798 [ -n "$tg_cache_dir" ] ||
1799 die "could not create a writable tg-cache directory (even a temporary one)"
1801 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
1802 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
1803 # so we avoid it if possible and require v2.11.1 to do it at all
1804 # otherwise just don't make an alternates temporary store in that case;
1805 # it's okay to not have one; everything will still work; the nicety of
1806 # making the temporary tree objects vanish when tg exits just won't
1807 # happen in that case but nothing will break also be sure to reuse
1808 # the parent's if we've been recursively invoked and it's for the
1809 # same repository we were invoked on
1811 tg_use_alt_odb=1
1812 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
1813 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] || tg_use_alt_odb=
1814 _fulltmpdir=
1815 [ -z "$tg_use_alt_odb" ] || _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
1816 case "$_fulltmpdir" in *[";:"]*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
1817 _fullodbdir=
1818 [ -z "$tg_use_alt_odb" ] || _fullodbdir="$(cd "$_odbdir" && pwd -P)"
1819 if [ -n "$tg_use_alt_odb" ] && [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
1820 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
1821 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
1822 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
1823 tg_use_alt_odb=2
1826 if [ "$tg_use_alt_odb" = "1" ]; then
1827 # create an alternate objects database to keep the ephemeral objects in
1828 mkdir -p "$tg_tmp_dir/objects/info"
1829 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
1830 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
1831 case "$TG_OBJECT_DIRECTORY" in
1832 *[";:"]*)
1833 # surround in "..." and backslash-escape internal '"' and '\\'
1834 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
1835 sed 's/\([""\\]\)/\\\1/g')\""
1838 _altodbdq="$TG_OBJECT_DIRECTORY"
1840 esac
1841 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1842 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
1843 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1844 else
1845 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
1847 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
1851 set_topbases()
1853 # refer to "top-bases" in a refname with $topbases
1855 [ -z "$tg_topbases_set" ] || return 0
1857 topbases_implicit_default=1
1858 # See if topgit.top-bases is set to heads or refs
1859 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
1860 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
1861 if [ -n "$1" ]; then
1862 # never die on the hook script
1863 unset tgtb
1864 else
1865 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
1868 if [ -n "$tgtb" ]; then
1869 case "$tgtb" in
1870 heads)
1871 topbases="heads/{top-bases}"
1872 topbasesrx="heads/[{]top-bases[}]"
1873 oldbases="top-bases";;
1874 refs)
1875 topbases="top-bases"
1876 topbasesrx="top-bases"
1877 oldbases="heads/{top-bases}";;
1878 esac
1879 # MUST NOT be exported
1880 unset tgtb tg_topbases_set topbases_implicit_default
1881 tg_topbases_set=1
1882 return 0
1884 unset tgtb
1886 # check heads and top-bases and see what state the current
1887 # repository is in. remotes are ignored.
1889 hblist=" "
1890 topbases=
1891 both=
1892 newtb="heads/{top-bases}"
1893 while read -r rn && [ -n "$rn" ]; do case "$rn" in
1894 "refs/heads/{top-bases}"/*)
1895 case "$hblist" in *" ${rn#refs/$newtb/} "*)
1896 if [ "$topbases" != "heads/{top-bases}" ] && [ -n "$topbases" ]; then
1897 both=1
1898 break;
1899 else
1900 topbases="heads/{top-bases}"
1901 topbasesrx="heads/[{]top-bases[}]"
1902 oldbases="top-bases"
1904 esac;;
1905 "refs/top-bases"/*)
1906 case "$hblist" in *" ${rn#refs/top-bases/} "*)
1907 if [ "$topbases" != "top-bases" ] && [ -n "$topbases" ]; then
1908 both=1
1909 break;
1910 else
1911 topbases="top-bases"
1912 topbasesrx="top-bases"
1913 oldbases="heads/{top-bases}"
1915 esac;;
1916 "refs/heads"/*)
1917 hblist="$hblist${rn#refs/heads/} ";;
1918 esac; done <<-EOT
1919 $(git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null)
1921 if [ -n "$both" ]; then
1922 if [ -n "$1" ]; then
1923 # hook script always prefers newer without complaint
1924 topbases="heads/{top-bases}"
1925 topbasesrx="heads/[{]top-bases[}]"
1926 oldbases="top-bases"
1927 else
1928 # Complain and die
1929 err "repository contains existing TopGit branches"
1930 err "but some use refs/top-bases/... for the base"
1931 err "and some use refs/heads/{top-bases}/... for the base"
1932 err "with the latter being the new, preferred location"
1933 err "set \"topgit.top-bases\" to either \"heads\" to use"
1934 err "the new heads/{top-bases} location or \"refs\" to use"
1935 err "the old top-bases location."
1936 err "(the tg migrate-bases command can also resolve this issue)"
1937 die "schizophrenic repository requires topgit.top-bases setting"
1939 elif [ -n "$topbases" ]; then
1940 unset topbases_implicit_default
1943 [ -n "$topbases" ] || {
1944 # default is still top-bases for now
1945 topbases="top-bases"
1946 topbasesrx="top-bases"
1947 oldbases="heads/{top-bases}"
1949 # MUST NOT be exported
1950 unset hblist both newtb rn tg_topases_set
1951 tg_topbases_set=1
1952 return 0
1955 # init_reflog "ref"
1956 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
1957 # an empty log file to exist so that ref changes will be logged
1958 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
1959 # However, if "$1" is "refs/tgstash" then always make the reflog
1960 # The only ref not under refs/ that Git will write a reflog for is HEAD;
1961 # no matter what, it will NOT update a reflog for any other bare refs so
1962 # just quietly succeed when passed TG_STASH without doing anything.
1963 init_reflog()
1965 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
1966 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
1967 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
1968 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
1969 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
1972 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
1973 # a symbolic link. The directory part must exist, but the basename need not.
1974 v_get_abs_path()
1976 [ -n "$1" ] && [ -n "$2" ] || return 1
1977 set -- "$1" "$2" "${2%/}"
1978 case "$3" in
1979 */*) set -- "$1" "$2" "${3%/*}";;
1980 * ) set -- "$1" "$2" ".";;
1981 esac
1982 case "$2" in */)
1983 set -- "$1" "${2%/}" "$3" "/"
1984 esac
1985 [ -d "$3" ] || return 1
1986 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
1989 ## Startup
1991 : "${TG_INST_CMDDIR:=@cmddir@}"
1992 : "${TG_INST_SHAREDIR:=@sharedir@}"
1993 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1995 [ -d "$TG_INST_CMDDIR" ] ||
1996 die "No command directory: '$TG_INST_CMDDIR'"
1998 ## Include awk scripts and their utility functions (separated for easier debugging)
2000 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
2001 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
2002 . "$TG_INST_CMDDIR/tg--awksome"
2004 if [ -n "$tg__include" ]; then
2006 # We were sourced from another script for our utility functions;
2007 # this is set by hooks. Skip the rest of the file. A simple return doesn't
2008 # work as expected in every shell. See http://bugs.debian.org/516188
2010 # ensure setup happens
2012 initial_setup 1
2013 set_topbases 1
2015 else
2017 set -e
2019 tgbin="$0"
2020 tgdir="${tgbin%/}"
2021 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
2022 tgdir="${tgdir%/*}/"
2023 tgname="${tgbin##*/}"
2024 [ "$0" != "$tgname" ] || tgdir=""
2026 # If tg contains a '/' but does not start with one then replace it with an absolute path
2028 case "$0" in /*) ;; */*)
2029 tgdir="$(cd "${0%/*}" && pwd -P)/"
2030 tgbin="$tgdir$tgname"
2031 esac
2033 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
2034 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
2036 tgdisplaydir="$tgdir"
2037 tgdisplay="$tgbin"
2038 tgdisplayac="$tgdisplay"
2040 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
2041 _tgabs="$_tgnameabs" &&
2042 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
2043 [ "$_tgabs" = "$_tgnameabs" ]
2044 then
2045 tgdisplaydir=""
2046 tgdisplay="$tgname"
2047 tgdisplayac="$tgdisplay"
2049 [ -z "$_tgabs" ] || tgbin="$_tgabs"
2050 unset _tgabs _tgnameabs
2052 tg() { command "$tgbin" "$@"; }
2054 explicit_remote=
2055 explicit_dir=
2056 gitcdopt=
2057 noremote=
2059 cmd=
2060 while :; do case "$1" in
2062 help|--help|-h)
2063 cmd=help
2064 shift
2065 break;;
2067 status|--status)
2068 cmd=status
2069 shift
2070 break;;
2072 --hooks-path)
2073 cmd=hooks-path
2074 shift
2075 break;;
2077 --exec-path)
2078 cmd=exec-path
2079 shift
2080 break;;
2082 --top-bases)
2083 cmd=top-bases
2084 shift
2085 break;;
2088 shift
2089 if [ -z "$1" ]; then
2090 echo "Option -r requires an argument." >&2
2091 do_help
2092 exit 1
2094 unset noremote
2095 base_remote="$1"
2096 explicit_remote="$base_remote"
2097 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2098 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2099 shift;;
2102 unset base_remote explicit_remote
2103 noremote=1
2104 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2105 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2106 shift;;
2109 shift
2110 if [ -z "$1" ]; then
2111 echo "Option -C requires an argument." >&2
2112 do_help
2113 exit 1
2115 cd "$1"
2116 unset GIT_DIR GIT_COMMON_DIR
2117 if [ -z "$explicit_dir" ]; then
2118 explicit_dir="$1"
2119 else
2120 explicit_dir="$PWD"
2122 gitcdopt=" -C \"$explicit_dir\""
2123 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2124 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2125 tgdisplayac="$tgdisplay"
2126 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2127 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2128 shift;;
2131 shift
2132 if [ -z "$1" ]; then
2133 echo "Option -c requires an argument." >&2
2134 do_help
2135 exit 1
2137 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2138 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2139 export GIT_CONFIG_PARAMETERS
2140 shift;;
2143 shift
2144 break;;
2147 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2148 do_help
2149 exit 1;;
2152 break;;
2154 esac; done
2156 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
2158 ## Dispatch
2160 [ -n "$cmd" ] || { do_help; exit 1; }
2162 case "$cmd" in
2164 help)
2165 do_help "$@"
2166 exit 0;;
2168 status|st)
2169 unset base_remote
2170 basic_setup
2171 set_topbases
2172 do_status "$@"
2173 exit ${do_status_result:-0};;
2175 hooks-path)
2176 # Internal command
2177 echol "$TG_INST_HOOKSDIR";;
2179 exec-path)
2180 # Internal command
2181 echol "$TG_INST_CMDDIR";;
2183 top-bases)
2184 # Maintenance command
2185 ! git rev-parse --git-dir >/dev/null 2>&1 || setup_git_dirs
2186 set_topbases
2187 echol "refs/$topbases";;
2190 isutil=
2191 case "$cmd" in index-merge-one-file)
2192 isutil="-"
2193 esac
2194 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2195 looplevel="$TG_ALIAS_DEPTH"
2196 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2197 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2198 looplevel=0
2199 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2200 [ -n "$tgalias" ] || {
2201 echo "Unknown subcommand: $cmd" >&2
2202 do_help
2203 exit 1
2205 looplevel=$(( $looplevel + 1 ))
2206 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2207 TG_ALIAS_DEPTH="$looplevel"
2208 export TG_ALIAS_DEPTH
2209 if [ "!${tgalias#?}" = "$tgalias" ]; then
2210 unset GIT_PREFIX
2211 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2212 GIT_PREFIX="$pfx"
2213 export GIT_PREFIX
2215 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2216 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2217 else
2218 eval 'exec "$tgbin"' "$tgalias" '"$@"'
2220 die "alias execution failed for: $tgalias"
2222 unset TG_ALIAS_DEPTH
2224 showing_help=
2225 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2226 showing_help=1
2229 [ -n "$showing_help" ] || initial_setup
2230 [ -z "$noremote" ] || unset base_remote
2232 nomergesetup="$showing_help"
2233 case "$cmd" in base|contains|info|log|rebase|revert|summary|tag)
2234 # avoid merge setup where not necessary
2236 nomergesetup=1
2237 esac
2239 if [ -z "$nomergesetup" ]; then
2240 # make sure merging the .top* files will always behave sanely
2242 setup_ours
2243 setup_hook "pre-commit"
2246 # everything but rebase needs topbases set
2247 carefully="$showing_help"
2248 [ "$cmd" != "migrate-bases" ] || carefully=1
2249 [ "$cmd" = "rebase" ] || set_topbases $carefully
2251 _use_ref_cache=
2252 tg_read_only=1
2253 case "$cmd$showing_help" in
2254 contains|export|info|summary|tag)
2255 _use_ref_cache=1;;
2256 annihilate|create|delete|depend|import|update)
2257 tg_use_alt_odb=
2258 tg_read_only=;;
2259 esac
2260 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2262 fullcmd="${tgname:-tg} $cmd $*"
2263 . "$TG_INST_CMDDIR"/tg-$isutil$cmd;;
2264 esac