tg.sh: awksome accelerate recurse_deps_internal
[topgit/pro.git] / tg.sh
blob3f5db1293fe5b185f3a12b9edc5c5eb10fb8bd46
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 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
530 # If the first argument is non-empty, stores "1" there if this call created the cache
531 v_create_ref_cache()
533 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
534 _remotespec=
535 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
536 [ -z "$1" ] || eval "$1=1"
537 git for-each-ref --format='%(refname) %(objectname)' \
538 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
539 create_ref_dirs
542 remove_ref_cache()
544 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
545 >"$tg_ref_cache"
546 >"$tg_ref_cache_br"
547 >"$tg_ref_cache_rbr"
548 >"$tg_ref_cache_ann"
549 >"$tg_ref_cache_dep"
552 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
553 rev_parse()
555 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
556 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
557 else
558 [ -z "$tg_ref_cache_only" ] || return 1
559 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
563 # ref_exists_rev REF
564 # Whether REF is a valid ref name
565 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
566 # or, if $base_remote is set, refs/remotes/$base_remote/
567 # Caches result if $tg_read_only and outputs HASH on success
568 ref_exists_rev()
570 case "$1" in
571 refs/*)
573 $octet20)
574 printf '%s' "$1"
575 return;;
577 die "ref_exists_rev requires fully-qualified ref name (given: $1)"
578 esac
579 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
580 _result=
581 _result_rev=
582 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
583 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
584 _result_rev="$(rev_parse "$1")"
585 _result=$?
586 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
587 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
588 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
589 printf '%s' "$_result_rev"
590 return $_result
593 # Same as ref_exists_rev but output is abbreviated hash
594 # Optional second argument defaults to --short but may be any --short=.../--no-short option
595 ref_exists_rev_short()
597 case "$1" in
598 refs/*)
600 $octet20)
603 die "ref_exists_rev_short requires fully-qualified ref name"
604 esac
605 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
606 _result=
607 _result_rev=
608 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
609 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
610 _result_rev="$(rev_parse "$1")"
611 _result=$?
612 if [ $_result -eq 0 ]; then
613 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev" --)"
614 _result=$?
616 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
617 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
618 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
619 printf '%s' "$_result_rev"
620 return $_result
623 # ref_exists REF
624 # Whether REF is a valid ref name
625 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
626 # or, if $base_remote is set, refs/remotes/$base_remote/
627 # Caches result
628 ref_exists()
630 ref_exists_rev "$1" >/dev/null
633 # rev_parse_tree REF
634 # Runs git rev-parse REF^{tree}
635 # Caches result if $tg_read_only
636 rev_parse_tree()
638 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
639 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
640 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
641 printf '%s\n' "$_result"
642 return 0
644 return 1
646 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
647 if [ -d "$tg_tmp_dir/cached/$1" ]; then
648 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
649 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
650 printf '%s\n' "$_result"
651 return 0
653 return 1
655 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
658 # has_remote BRANCH
659 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
660 has_remote()
662 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
665 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
666 # If -z "$1" still set return code but do not return result
667 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
668 # refs/heads/... then ... will be verified instead.
669 # if "$3" = "-f" (for fail) then return an error rather than dying.
670 v_verify_topgit_branch()
672 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
673 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
674 [ -n "$_verifyname" -o "$3" = "-f" ] || die "HEAD is not a symbolic ref"
675 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
676 [ "$3" != "-f" ] || return 1
677 die "HEAD is not a symbolic ref to the refs/heads namespace"
678 esac
679 set -- "$1" "$_verifyname" "$3"
681 case "$2" in
682 refs/"$topbases"/*)
683 _verifyname="${2#refs/$topbases/}"
685 refs/heads/*)
686 _verifyname="${2#refs/heads/}"
689 _verifyname="$2"
691 esac
692 if ! ref_exists "refs/heads/$_verifyname"; then
693 [ "$3" != "-f" ] || return 1
694 die "no such branch: $_verifyname"
696 if ! ref_exists "refs/$topbases/$_verifyname"; then
697 [ "$3" != "-f" ] || return 1
698 die "not a TopGit-controlled branch: $_verifyname"
700 [ -z "$1" ] || eval "$1="'"$_verifyname"'
703 # Return the verified TopGit branch name or die with an error.
704 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
705 # refs/heads/... then ... will be verified instead.
706 # if "$2" = "-f" (for fail) then return an error rather than dying.
707 verify_topgit_branch()
709 v_verify_topgit_branch _verifyname "$@" || return
710 printf '%s' "$_verifyname"
713 # Caches result
714 # $1 = branch name (i.e. "t/foo/bar")
715 # $2 = optional result of rev-parse "refs/heads/$1"
716 # $3 = optional result of rev-parse "refs/$topbases/$1"
717 branch_annihilated()
719 _branch_name="$1"
720 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
721 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
723 _result=
724 _result_rev=
725 _result_rev_base=
726 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/refs/heads/$_branch_name/.ann"; } 2>/dev/null || :
727 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
729 # use the merge base in case the base is ahead.
730 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
732 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
733 _result=$?
734 [ -d "$tg_cache_dir/refs/heads/$_branch_name" ] || mkdir -p "$tg_cache_dir/refs/heads/$_branch_name" 2>/dev/null
735 [ ! -d "$tg_cache_dir/refs/heads/$_branch_name" ] ||
736 echo $_result $_rev $_rev_base >"$tg_cache_dir/refs/heads/$_branch_name/.ann" 2>/dev/null || :
737 return $_result
740 non_annihilated_branches()
742 [ $# -gt 0 ] || set -- "refs/$topbases"
743 git for-each-ref --format='%(objectname) %(refname)' "$@" |
744 while read rev ref; do
745 name="${ref#refs/$topbases/}"
746 if branch_annihilated "$name" "" "$rev"; then
747 continue
749 echol "$name"
750 done
753 # Make sure our tree is clean
754 # if optional "$1" given also verify that a checkout to "$1" would succeed
755 ensure_clean_tree()
757 check_status
758 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
759 git update-index --ignore-submodules --refresh ||
760 die "the working directory has uncommitted changes (see above) - first commit or reset them"
761 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
762 die "the index has uncommited changes"
763 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
764 die "git checkout \"$1\" would fail"
767 # Make sure .topdeps and .topmsg are "clean"
768 # They are considered "clean" if each is identical in worktree, index and HEAD
769 # With "-u" as the argument skip the HEAD check (-u => unborn)
770 # untracked .topdeps and/or .topmsg files are always considered "dirty" as well
771 # with -u them just existing constitutes "dirty"
772 ensure_clean_topfiles()
774 _dirtw=0
775 _dirti=0
776 _dirtu=0
777 _check="$(git diff-files --ignore-submodules --name-only -- :/.topdeps :/.topmsg)" &&
778 [ -z "$_check" ] || _dirtw=1
779 if [ "$1" != "-u" ]; then
780 _check="$(git diff-index --cached --ignore-submodules --name-only HEAD -- :/.topdeps :/.topmsg)" &&
781 [ -z "$_check" ] || _dirti=1
783 if [ "$_dirti$_dirtw" = "00" ]; then
784 v_get_show_cdup
785 if [ -e "${git_cdup_result}.topdeps" ] || [ -e "${git_cdup_result}.topmsg" ]; then
786 [ "$1" != "-u" ] &&
787 _check="$(git status --porcelain --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg)" &&
788 [ -z "$_check" ] || _dirtu=1
791 if [ "$_dirtu$_dirti$_dirtw" != "000" ]; then
792 git status --ignored --untracked-files --ignore-submodules -- :/.topdeps :/.topmsg || :
793 case "$_dirtu$_dirti$_dirtw" in
794 001) die "the working directory has uncommitted changes (see above) - first commit or reset them";;
795 010) die "the index has uncommited changes (see above)";;
796 011) die "the working directory and index have uncommitted changes (see above) - first commit or reset them";;
797 100) die "the working directory has untracked files that would be overwritten (see above)";;
798 esac
802 # is_sha1 REF
803 # Whether REF is a SHA1 (compared to a symbolic name).
804 is_sha1()
806 case "$1" in $octet20) return 0;; esac
807 return 1
810 # recurse_deps_internal NAME [BRANCHPATH...]
811 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
812 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
813 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
814 # but missing and remotes are always "0"
815 # then the branch name followed by its depedency chain (which might be empty)
816 # An output line might look like this:
817 # 0 1 1 t/foo/leaf t/foo/int t/stage
818 # If no_remotes is non-empty, exclude remotes
819 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
820 # If with_top_level is non-empty, include the top-level that's normally omitted
821 # any branch names in the space-separated recurse_deps_exclude variable
822 # are skipped (along with their dependencies)
823 recurse_deps_internal()
825 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
826 ratr_opts="${recurse_preorder:+-f} ${with_top_level:+-s}"
827 dogfer=
828 dorad=1
829 userc=
830 tmpdep=
831 if [ -n "$tg_read_only" ] && [ -n "$tg_ref_cache" ]; then
832 userc=1
833 tmprfs="$tg_ref_cache"
834 tmptgbr="$tg_ref_cache_br"
835 tmpann="$tg_ref_cache_ann"
836 tmpdep="$tg_ref_cache_dep"
837 [ -s "$tg_ref_cache" ] || dogfer=1
838 [ -n "$dogfer" ] || ! [ -s "$tmptgbr" ] || ! [ -f "$tmpann" ] || ! [ -s "$tmpdep" ] || dorad=
839 else
840 ratr_opts="$ratr_opts -rmh -rma -rmb"
841 tmprfs="$tg_tmp_dir/refs.$$"
842 tmpann="$tg_tmp_dir/ann.$$"
843 tmptgbr="$tg_tmp_dir/tgbr.$$"
844 dogfer=1
846 refpats="\"refs/heads\" \"refs/\$topbases\""
847 [ -z "$base_remote" ] || refpats="$refpats \"refs/remotes/\$base_remote\""
848 tmptgrmtbr=
849 dorab=1
850 if [ -z "$no_remotes" ] && [ -n "$base_remote" ]; then
851 if [ -n "$userc" ]; then
852 tmptgrmtbr="$tg_ref_cache_rbr"
853 [ -n "$dogfer" ] || ! [ -s "$tmptgrmtbr" ] || dorab=
854 else
855 tmptgrmtbr="$tg_tmp_dir/tgrmtbr.$$"
856 ratr_opts="$ratr_opts -rmr"
858 ratr_opts="$ratr_opts -r=\"\$tmptgbr\" -u=\"refs/remotes/\$base_remote/\${topbases#heads/}\""
860 [ -z "$dogfer" ] ||
861 eval git for-each-ref '--format="%(refname) %(objectname)"' "$refpats" >"$tmprfs"
862 if [ -n "$tmptgrmtbr" ] && [ -n "$dorab" ]; then
863 run_awk_topgit_branches -n -h="refs/remotes/$base_remote" -r="$tmprfs" \
864 "refs/remotes/$base_remote/${topbases#heads/}" >"$tmptgrmtbr"
866 depscmd='run_awk_topgit_deps -a="$tmpann" -b="$tmptgbr" -r="$tmprfs" -m="$mtblob" "refs/$topbases"'
867 if [ -n "$userc" ]; then
868 if [ -n "$dorad" ]; then
869 eval "$depscmd" >"$tmpdep"
871 depscmd='<"$tmpdep" '
872 else
873 depscmd="$depscmd |"
875 eval "$depscmd" run_awk_topgit_recurse '-a="$tmpann" -b="$tmptgbr"' \
876 '-c=1 -h="$tmprfs"' "$ratr_opts" '-x="$recurse_deps_exclude"' '"$@"'
879 # do_eval CMD
880 # helper for recurse_deps so that a return statement executed inside CMD
881 # does not return from recurse_deps. This shouldn't be necessary, but it
882 # seems that it actually is.
883 do_eval()
885 eval "$@"
888 # becomes read-only for caching purposes
889 # assigns new value to tg_read_only
890 # become_cacheable/undo_become_cacheable calls may be nested
891 become_cacheable()
893 _old_tg_read_only="$tg_read_only"
894 if [ -z "$tg_read_only" ]; then
895 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
896 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
897 tg_read_only=1
899 _my_ref_cache=
900 v_create_ref_cache _my_ref_cache
901 _my_ref_cache="${_my_ref_cache:+1}"
902 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
905 # restores tg_read_only and ref_cache to state before become_cacheable call
906 # become_cacheable/undo_bocome_cacheable calls may be nested
907 undo_become_cacheable()
909 case "$tg_read_only" in
910 "undo"[01]"-"*)
911 _suffix="${tg_read_only#undo?-}"
912 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
913 tg_read_only="$_suffix"
914 esac
917 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
918 become_non_cacheable()
920 remove_ref_cache
921 tg_read_only=
922 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
923 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
926 # call this to make sure Git will not complain about a missing user/email
927 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
928 ensure_ident_available()
930 [ -z "$TG_IDENT_CHECKED" ] || return 0
931 git var GIT_AUTHOR_IDENT >/dev/null &&
932 git var GIT_COMMITTER_IDENT >/dev/null || exit
933 TG_IDENT_CHECKED=1
934 export TG_IDENT_CHECKED
935 return 0
938 # recurse_deps CMD NAME [BRANCHPATH...]
939 # Recursively eval CMD on all dependencies of NAME.
940 # Dependencies are visited in topological order.
941 # CMD can refer to the following variables:
943 # _ret starts as 0; CMD can change; will be final return result
944 # _dep bare branch name or "refs/remotes/..." for a remote base
945 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
946 # _depchain 0+ space-separated branch names forming a path to top
947 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
948 # _dep_is_leaf boolean "1" if leaf; "" if not
949 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
950 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
951 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
953 # CMD may use a "return" statement without issue; its return value is ignored,
954 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
955 # will stop immediately and the value with the leading "-" stripped off will
956 # be the final result code
958 # CMD can refer to $_name for queried branch name,
959 # $_dep for dependency name,
960 # $_depchain for space-seperated branch backtrace,
961 # $_dep_missing boolean to check whether $_dep is present
962 # and the $_dep_is_tgish and $_dep_annihilated booleans.
963 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
964 # It can modify $_ret to affect the return value
965 # of the whole function.
966 # If recurse_deps() hits missing dependencies, it will append
967 # them to space-separated $missing_deps list and skip them
968 # after calling CMD with _dep_missing set.
969 # remote dependencies are processed if no_remotes is unset.
970 # any branch names in the space-separated recurse_deps_exclude variable
971 # are skipped (along with their dependencies)
973 # If no_remotes is non-empty, exclude remotes
974 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
975 # If with_top_level is non-empty, include the top-level that's normally omitted
976 # any branch names in the space-separated recurse_deps_exclude variable
977 # are skipped (along with their dependencies)
978 recurse_deps()
980 _cmd="$1"; shift
982 _depsfile="$(get_temp tg-depsfile)"
983 recurse_deps_internal -- "$@" >"$_depsfile" || :
985 _ret=0
986 while read _ismissing _istgish _isleaf _dep _name _deppath; do
987 _depchain="$_name${_deppath:+ $_deppath}"
988 _dep_is_tgish=
989 [ "$_istgish" = "0" ] || _dep_is_tgish=1
990 _dep_has_remote=
991 [ "$_istgish" != "2" ] || _dep_has_remote=1
992 _dep_missing=
993 if [ "$_ismissing" != "0" ]; then
994 _dep_missing=1
995 case " $missing_deps " in *" $_dep "*);;*)
996 missing_deps="${missing_deps:+$missing_deps }$_dep"
997 esac
999 _dep_annihilated=
1000 _dep_is_leaf=
1001 if [ "$_isleaf" = "1" ]; then
1002 _dep_is_leaf=1
1003 elif [ "$_isleaf" = "2" ]; then
1004 _dep_annihilated=1
1006 do_eval "$_cmd" || :
1007 if [ "${_ret#-}" != "$_ret" ]; then
1008 _ret="${_ret#-}"
1009 break
1011 done <"$_depsfile"
1012 rm -f "$_depsfile"
1013 return ${_ret:-0}
1016 find_leaves_internal()
1018 if [ -n "$_dep_is_leaf" ] && [ -z "$_dep_annihilated" ] && [ -z "$_dep_missing" ]; then
1019 if [ -n "$_dep_is_tgish" ]; then
1020 fulldep="refs/$topbases/$_dep"
1021 else
1022 fulldep="refs/heads/$_dep"
1024 case " $seen_leaf_refs " in *" $fulldep "*);;*)
1025 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
1026 if fullrev="$(ref_exists_rev "$fulldep")"; then
1027 case " $seen_leaf_revs " in *" $fullrev "*);;*)
1028 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
1029 # See if Git knows it by another name
1030 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
1031 echo "refs/tags/$tagname"
1032 else
1033 echo "$fulldep"
1035 esac
1037 esac
1041 # find_leaves NAME
1042 # output (one per line) the unique leaves of NAME
1043 # a leaf is either
1044 # 1) a non-tgish dependency
1045 # 2) the base of a tgish dependency with no non-annihilated dependencies
1046 # duplicates are suppressed (by commit rev) and remotes are always ignored
1047 # if a leaf has an exact tag match that will be output
1048 # note that recurse_deps_exclude IS honored for this operation
1049 find_leaves()
1051 no_remotes=1
1052 with_top_level=1
1053 recurse_preorder=
1054 seen_leaf_refs=
1055 seen_leaf_revs=
1056 recurse_deps find_leaves_internal "$1"
1057 with_top_level=
1060 # branch_needs_update
1061 # This is a helper function for determining whether given branch
1062 # is up-to-date wrt. its dependencies. It expects input as if it
1063 # is called as a recurse_deps() helper.
1064 # In case the branch does need update, it will echo it together
1065 # with the branch backtrace on the output (see needs_update()
1066 # description for details) and set $_ret to non-zero.
1067 branch_needs_update()
1069 if [ -n "$_dep_missing" ]; then
1070 echo "! $_dep $_depchain"
1071 return 0
1074 if [ -n "$_dep_is_tgish" ]; then
1075 [ -z "$_dep_annihilated" ] || return 0
1077 if [ -n "$_dep_has_remote" ]; then
1078 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
1079 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
1081 # We want to sync with our base first and should output this before
1082 # the remote branch, but the order does not actually matter to tg-update
1083 # as it just recurses regardless, but it does matter for tg-info (which
1084 # treats out-of-date bases as though they were already merged in) so
1085 # we output the remote before the base.
1086 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1087 echo ": $_dep $_depchain"
1088 _ret=1
1089 return
1093 if [ -n "$_name" ]; then
1094 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
1095 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1096 # Some new commits in _dep
1097 echo "$_dep $_depchain"
1098 _ret=1
1103 # needs_update NAME
1104 # This function is recursive; it outputs reverse path from NAME
1105 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1106 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
1107 # if the head is not in sync with the <remote> branch <name>, ':' if
1108 # the head is not in sync with the base (in this order of priority)
1109 # or '!' if dependency is missing. Note that the remote branch, base
1110 # order is reversed from the order they will actually be updated in
1111 # order to accomodate tg info which treats out-of-date items that are
1112 # only in the base as already being in the head for status purposes.
1113 # It will also return non-zero status if NAME needs update.
1114 # If needs_update() hits missing dependencies, it will append
1115 # them to space-separated $missing_deps list and skip them.
1116 needs_update()
1118 recurse_deps branch_needs_update "$1"
1121 # branch_empty NAME [-i | -w]
1122 branch_empty()
1124 if [ -z "$2" ]; then
1125 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1126 _result=
1127 _result_rev=
1128 { read -r _result _result_rev <"$tg_cache_dir/refs/heads/$1/.mt"; } 2>/dev/null || :
1129 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
1130 _result=0
1131 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1132 [ -d "$tg_cache_dir/refs/heads/$1" ] || mkdir -p "$tg_cache_dir/refs/heads/$1" 2>/dev/null
1133 [ ! -d "$tg_cache_dir/refs/heads/$1" ] || echo $_result $_rev >"$tg_cache_dir/refs/heads/$1/.mt"
1134 return $_result
1135 else
1136 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1140 # list_deps [-i | -w] [BRANCH]
1141 # -i/-w apply only to HEAD
1142 list_deps()
1144 head_from=
1145 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
1146 head="$(git symbolic-ref -q HEAD)" ||
1147 head="..detached.."
1149 git for-each-ref --format='%(objectname) %(refname)' "refs/$topbases${1:+/$1}" |
1150 while read rev ref; do
1151 name="${ref#refs/$topbases/}"
1152 if branch_annihilated "$name" "" "$rev"; then
1153 continue
1156 from=$head_from
1157 [ "refs/heads/$name" = "$head" ] ||
1158 from=
1159 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
1160 dep_is_tgish=true
1161 ref_exists "refs/$topbases/$dep" ||
1162 dep_is_tgish=false
1163 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
1164 echo "$name $dep"
1166 done
1167 done
1170 # checkout_symref_full [-f] FULLREF [SEED]
1171 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1172 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1173 # MUST be a committish which if present will be used instead of current FULLREF
1174 # (and FULLREF will be updated to it as well in that case)
1175 # Any merge state is always cleared by this function
1176 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1177 # instead of -m) but it will clear out any unmerged entries
1178 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1179 checkout_symref_full()
1181 _mode=-m
1182 _head="HEAD"
1183 if [ "$1" = "-f" ]; then
1184 _mode="--reset"
1185 _head=
1186 shift
1188 _ishash=
1189 case "$1" in
1190 refs/?*)
1192 $octet20)
1193 _ishash=1
1194 [ -z "$2" ] || [ "$1" = "$2" ] ||
1195 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1196 set -- HEAD "$1"
1199 die "programmer error: invalid checkout_symref_full \"$1\""
1201 esac
1202 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1203 die "invalid committish: \"${2:-$1}\""
1204 # Clear out any MERGE_HEAD kruft
1205 rm -f "$git_dir/MERGE_HEAD" || :
1206 # We have to do all the hard work ourselves :/
1207 # This is like git checkout -b "$1" "$2"
1208 # (or just git checkout "$1"),
1209 # but never creates a detached HEAD (unless $1 is a hash)
1210 git read-tree -u $_mode $_head "$_seedrev" &&
1212 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1213 git update-ref ${_ishash:+--no-deref} "$1" "$_seedrev"
1214 } && {
1215 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1219 # switch_to_base NAME [SEED]
1220 switch_to_base()
1222 checkout_symref_full "refs/$topbases/$1" "$2"
1225 # run editor with arguments
1226 # the editor setting will be cached in $tg_editor (which is eval'd)
1227 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1228 run_editor()
1230 tg_editor="$GIT_EDITOR"
1231 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1232 eval "$tg_editor" '"$@"'
1235 # Show the help messages.
1236 do_help()
1238 _www=
1239 if [ "$1" = "-w" ]; then
1240 _www=1
1241 shift
1243 if [ -z "$1" ] ; then
1244 # This is currently invoked in all kinds of circumstances,
1245 # including when the user made a usage error. Should we end up
1246 # providing more than a short help message, then we should
1247 # differentiate.
1248 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1250 ## Build available commands list for help output
1252 cmds=
1253 sep=
1254 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1255 ! [ -r "$cmd" ] && continue
1256 # strip directory part and "tg-" prefix
1257 cmd="${cmd##*/}"
1258 cmd="${cmd#tg-}"
1259 [ "$cmd" != "migrate-bases" ] || continue
1260 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1261 cmds="$cmds$sep$cmd"
1262 sep="|"
1263 done
1265 echo "TopGit version $TG_VERSION - A different patch queue manager"
1266 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
1267 echo " Or: $tgname help [-w] [<command>]"
1268 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1269 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1270 if [ -n "$_www" ]; then
1271 nohtml=
1272 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1273 echo "${0##*/}: missing html help file:" \
1274 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1275 nohtml=1
1277 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1278 echo "${0##*/}: missing html help file:" \
1279 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1280 nohtml=1
1282 if [ -n "$nohtml" ]; then
1283 echo "${0##*/}: use" \
1284 "\"${0##*/} help $1\" instead" 1>&2
1285 exit 1
1287 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1288 exit
1290 output()
1292 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1293 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1294 echo
1295 elif [ "$1" = "help" ]; then
1296 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1297 echo
1298 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1299 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1300 echo
1302 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1303 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1306 page output "$1"
1307 else
1308 echo "${0##*/}: no help for $1" 1>&2
1309 do_help
1310 exit 1
1314 check_status()
1316 git_state=
1317 git_remove=
1318 if [ -e "$git_dir/MERGE_HEAD" ]; then
1319 git_state="merge"
1320 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1321 git_state="am"
1322 git_remove="$git_dir/rebase-apply"
1323 elif [ -e "$git_dir/rebase-apply" ]; then
1324 git_state="rebase"
1325 git_remove="$git_dir/rebase-apply"
1326 elif [ -e "$git_dir/rebase-merge" ]; then
1327 git_state="rebase"
1328 git_remove="$git_dir/rebase-merge"
1329 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1330 git_state="cherry-pick"
1331 elif [ -e "$git_dir/BISECT_LOG" ]; then
1332 git_state="bisect"
1333 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1334 git_state="revert"
1336 git_remove="${git_remove#./}"
1338 tg_state=
1339 tg_remove=
1340 tg_topmerge=
1341 if [ -e "$git_dir/tg-update" ]; then
1342 tg_state="update"
1343 tg_remove="$git_dir/tg-update"
1344 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1346 tg_remove="${tg_remove#./}"
1349 # Show status information
1350 do_status()
1352 do_status_result=0
1353 do_status_verbose=
1354 do_status_help=
1355 abbrev=refs
1356 pfx=
1357 while [ $# -gt 0 ] && case "$1" in
1358 --help|-h)
1359 do_status_help=1
1360 break;;
1361 -vv)
1362 # kludge in this common bundling option
1363 abbrev=
1364 do_status_verbose=1
1365 pfx="## "
1367 --verbose|-v)
1368 [ -z "$do_status_verbose" ] || abbrev=
1369 do_status_verbose=1
1370 pfx="## "
1372 --exit-code)
1373 do_status_result=2
1376 die "unknown status argument: $1"
1378 esac; do shift; done
1379 if [ -n "$do_status_help" ]; then
1380 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1381 return
1383 check_status
1384 symref="$(git symbolic-ref --quiet HEAD)" || :
1385 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1386 if [ -n "$symref" ]; then
1387 uprefpart=
1388 if [ -n "$headrv" ]; then
1389 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1390 if [ -n "$upref" ]; then
1391 uprefpart=" ... ${upref#$abbrev/remotes/}"
1392 mbase="$(git merge-base HEAD "$upref")" || :
1393 ahead="$(git rev-list --count HEAD ${mbase:+--not $mbase})" || ahead=0
1394 behind="$(git rev-list --count "$upref" ${mbase:+--not $mbase})" || behind=0
1395 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1396 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1397 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1398 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1399 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1402 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1403 else
1404 echol "${pfx}HEAD -> ${headrv:-?}"
1406 if [ -n "$tg_state" ]; then
1407 extra=
1408 if [ "$tg_state" = "update" ]; then
1409 IFS= read -r uname <"$git_dir/tg-update/name" || :
1410 [ -z "$uname" ] ||
1411 extra="; currently updating branch '$uname'"
1413 echol "${pfx}tg $tg_state in progress$extra"
1414 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1415 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1416 cat "$git_dir/tg-update/fullcmd"
1417 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1418 if [ $bcnt -gt 1 ]; then
1419 pcnt=0
1420 ! [ -s "$git_dir/tg-update/processed" ] ||
1421 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1422 echo "${pfx}$pcnt of $bcnt branches updated so far"
1425 if [ "$tg_state" = "update" ]; then
1426 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1427 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1428 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1429 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1432 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1433 if [ "$git_state" = "merge" ]; then
1434 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1435 if [ $ucnt -gt 0 ]; then
1436 echo "${pfx}"'fix conflicts and then "git commit" the result'
1437 else
1438 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1441 if [ -z "$git_state" ]; then
1442 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository
1443 gspcnt=0
1444 [ -z "$gsp" ] ||
1445 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1446 untr=
1447 if [ "$gspcnt" -eq 0 ]; then
1448 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1449 echo "${pfx}working directory is clean$untr"
1450 [ -n "$tg_state" ] || do_status_result=0
1451 else
1452 echo "${pfx}working directory is DIRTY"
1453 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1458 ## Pager stuff
1460 # isatty FD
1461 isatty()
1463 test -t $1
1466 # pass "diff" to get pager.diff
1467 # if pager.$1 is a boolean false returns cat
1468 # if set to true or unset fails
1469 # otherwise succeeds and returns the value
1470 get_pager()
1472 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1473 [ "$_x" != "true" ] || return 1
1474 echo "cat"
1475 return 0
1477 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1478 echol "$_x"
1479 return 0
1481 return 1
1484 # setup_pager
1485 # Set TG_PAGER to a valid executable
1486 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1487 # See also the following "page" function for ease of use
1488 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1489 # Preference is (same as Git):
1490 # 1. GIT_PAGER
1491 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1492 # 3. core.pager (only if set)
1493 # 4. PAGER
1494 # 5. git var GIT_PAGER
1495 # 6. less
1496 setup_pager()
1498 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1500 emptypager=
1501 if [ -z "$TG_PAGER_IN_USE" ]; then
1502 # TG_PAGER = GIT_PAGER | PAGER | less
1503 # NOTE: GIT_PAGER='' is significant
1504 if [ -n "${GIT_PAGER+set}" ]; then
1505 TG_PAGER="$GIT_PAGER"
1506 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1507 TG_PAGER="$_dp"
1508 elif _cp="$(git config core.pager 2>/dev/null)"; then
1509 TG_PAGER="$_cp"
1510 elif [ -n "${PAGER+set}" ]; then
1511 TG_PAGER="$PAGER"
1512 else
1513 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1514 [ "$_gp" != ":" ] || _gp=
1515 TG_PAGER="${_gp:-less}"
1517 if [ -z "$TG_PAGER" ]; then
1518 emptypager=1
1519 TG_PAGER=cat
1521 else
1522 emptypager=1
1523 TG_PAGER=cat
1526 # Set pager default environment variables
1527 # see pager.c:setup_pager
1528 if [ -z "${LESS+set}" ]; then
1529 LESS="-FRX"
1530 export LESS
1532 if [ -z "${LV+set}" ]; then
1533 LV="-c"
1534 export LV
1537 # this is needed so e.g. $(git diff) will still colorize it's output if
1538 # requested in ~/.gitconfig with color.diff=auto
1539 GIT_PAGER_IN_USE=1
1540 export GIT_PAGER_IN_USE
1542 # this is needed so we don't get nested pagers
1543 TG_PAGER_IN_USE=1
1544 export TG_PAGER_IN_USE
1547 # page eval_arg [arg ...]
1549 # Calls setup_pager then evals the first argument passing it all the rest
1550 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1551 # by setup_pager (in which case the output is left as-is).
1553 # To handle arbitrary paging duties, collect lines to be paged into a
1554 # function and then call page with the function name or perhaps func_name "$@".
1556 # If no arguments at all are passed in do nothing (return with success).
1557 page()
1559 [ $# -gt 0 ] || return 0
1560 setup_pager
1561 _evalarg="$1"; shift
1562 if [ -n "$emptypager" ]; then
1563 eval "$_evalarg" '"$@"'
1564 else
1565 eval "$_evalarg" '"$@"' | eval "$TG_PAGER"
1569 # get_temp NAME [-d]
1570 # creates a new temporary file (or directory with -d) in the global
1571 # temporary directory $tg_tmp_dir with pattern prefix NAME
1572 get_temp()
1574 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1577 # automatically called by strftime
1578 # does nothing if already setup
1579 # may be called explicitly if the first call would otherwise be in a subshell
1580 # so that the setup is only done once before subshells start being spawned
1581 setup_strftime()
1583 [ -z "$strftime_is_setup" ] || return 0
1585 # date option to format raw epoch seconds values
1586 daterawopt=
1587 _testes='951807788'
1588 _testdt='2000-02-29 07:03:08 UTC'
1589 _testfm='%Y-%m-%d %H:%M:%S %Z'
1590 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1591 daterawopt='-d@'
1592 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1593 daterawopt='-r'
1595 strftime_is_setup=1
1598 # $1 => strftime format string to use
1599 # $2 => raw timestamp as seconds since epoch
1600 # $3 => optional time zone string (empty/absent for local time zone)
1601 strftime()
1603 setup_strftime
1604 if [ -n "$daterawopt" ]; then
1605 if [ -n "$3" ]; then
1606 TZ="$3" date "$daterawopt$2" "+$1"
1607 else
1608 date "$daterawopt$2" "+$1"
1610 else
1611 if [ -n "$3" ]; then
1612 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1613 else
1614 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1619 got_cdup_result=
1620 git_cdup_result=
1621 v_get_show_cdup()
1623 if [ -z "$got_cdup_result" ]; then
1624 git_cdup_result="$(git rev-parse --show-cdup)"
1625 got_cdup_result=1
1627 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1630 setup_git_dirs()
1632 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1633 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1634 git_dir="$(cd "$git_dir" && pwd)"
1636 if [ -z "$git_common_dir" ]; then
1637 if vcmp "$git_version" '>=' "2.5"; then
1638 # rev-parse --git-common-dir is broken and may give
1639 # an incorrect result unless the current directory is
1640 # already set to the top level directory
1641 v_get_show_cdup
1642 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1643 else
1644 git_common_dir="$git_dir"
1647 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1648 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1649 git_hooks_dir="$git_common_dir/hooks"
1650 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1651 case "$gchp" in
1652 /[!/]*)
1653 git_hooks_dir="$gchp"
1656 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1658 esac
1659 unset gchp
1663 basic_setup()
1665 setup_git_dirs $1
1666 if [ -z "$base_remote" ]; then
1667 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
1668 base_remote="$TG_EXPLICIT_REMOTE"
1669 else
1670 base_remote="$(git config topgit.remote 2>/dev/null)" || :
1673 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1674 tgnosequester=
1675 [ "$tgsequester" != "false" ] || tgnosequester=1
1676 unset tgsequester
1678 # catch errors if topbases is used without being set
1679 unset tg_topbases_set
1680 topbases="programmer*:error"
1681 topbasesrx="programmer*:error}"
1682 oldbases="$topbases"
1685 ## Initial setup
1686 initial_setup()
1688 # suppress the merge log editor feature since git 1.7.10
1690 GIT_MERGE_AUTOEDIT=no
1691 export GIT_MERGE_AUTOEDIT
1693 basic_setup $1
1694 iowopt=
1695 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
1696 gcfbopt=
1697 ! vcmp "$git_version" '>=' "2.6" || gcfbopt="--buffer"
1698 auhopt=
1699 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1700 v_get_show_cdup root_dir
1701 root_dir="${root_dir:-.}"
1702 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1703 [ "$logrefupdates" = "true" ] || logrefupdates=
1705 # make sure root_dir doesn't end with a trailing slash.
1707 root_dir="${root_dir%/}"
1709 # create global temporary directories, inside GIT_DIR
1711 tg_tmp_dir=
1712 trap 'rm -rf "$tg_tmp_dir"' EXIT
1713 trap 'exit 129' HUP
1714 trap 'exit 130' INT
1715 trap 'exit 131' QUIT
1716 trap 'exit 134' ABRT
1717 trap 'exit 143' TERM
1718 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1719 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1720 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1721 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1722 tg_ref_cache_br="$tg_ref_cache.br"
1723 tg_ref_cache_rbr="$tg_ref_cache.rbr"
1724 tg_ref_cache_ann="$tg_ref_cache.ann"
1725 tg_ref_cache_dep="$tg_ref_cache.dep"
1726 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_ref_cache"; } >/dev/null 2>&1 ||
1727 die "could not create a writable temporary directory"
1729 # make sure global cache directory exists inside GIT_DIR or $tg_tmp_dir
1731 user_id_no="$(id -u)" || :
1732 : "${user_id_no:=_99_}"
1733 tg_cache_dir="$git_common_dir/tg-cache"
1734 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1735 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
1736 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1737 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1738 if [ -z "$tg_cache_dir" ]; then
1739 tg_cache_dir="$tg_tmp_dir/tg-cache"
1740 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1741 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1743 [ -n "$tg_cache_dir" ] ||
1744 die "could not create a writable tg-cache directory (even a temporary one)"
1746 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
1747 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
1748 # so we avoid it if possible and require v2.11.1 to do it at all
1749 # otherwise just don't make an alternates temporary store in that case;
1750 # it's okay to not have one; everything will still work; the nicety of
1751 # making the temporary tree objects vanish when tg exits just won't
1752 # happen in that case but nothing will break also be sure to reuse
1753 # the parent's if we've been recursively invoked and it's for the
1754 # same repository we were invoked on
1756 tg_use_alt_odb=1
1757 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
1758 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] || tg_use_alt_odb=
1759 _fulltmpdir=
1760 [ -z "$tg_use_alt_odb" ] || _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
1761 case "$_fulltmpdir" in *[";:"]*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
1762 _fullodbdir=
1763 [ -z "$tg_use_alt_odb" ] || _fullodbdir="$(cd "$_odbdir" && pwd -P)"
1764 if [ -n "$tg_use_alt_odb" ] && [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
1765 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
1766 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
1767 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
1768 tg_use_alt_odb=2
1771 if [ "$tg_use_alt_odb" = "1" ]; then
1772 # create an alternate objects database to keep the ephemeral objects in
1773 mkdir -p "$tg_tmp_dir/objects/info"
1774 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
1775 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
1776 case "$TG_OBJECT_DIRECTORY" in
1777 *[";:"]*)
1778 # surround in "..." and backslash-escape internal '"' and '\\'
1779 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
1780 sed 's/\([""\\]\)/\\\1/g')\""
1783 _altodbdq="$TG_OBJECT_DIRECTORY"
1785 esac
1786 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1787 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
1788 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1789 else
1790 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
1792 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
1796 set_topbases()
1798 # refer to "top-bases" in a refname with $topbases
1800 [ -z "$tg_topbases_set" ] || return 0
1802 topbases_implicit_default=1
1803 # See if topgit.top-bases is set to heads or refs
1804 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
1805 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
1806 if [ -n "$1" ]; then
1807 # never die on the hook script
1808 unset tgtb
1809 else
1810 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
1813 if [ -n "$tgtb" ]; then
1814 case "$tgtb" in
1815 heads)
1816 topbases="heads/{top-bases}"
1817 topbasesrx="heads/[{]top-bases[}]"
1818 oldbases="top-bases";;
1819 refs)
1820 topbases="top-bases"
1821 topbasesrx="top-bases"
1822 oldbases="heads/{top-bases}";;
1823 esac
1824 # MUST NOT be exported
1825 unset tgtb tg_topbases_set topbases_implicit_default
1826 tg_topbases_set=1
1827 return 0
1829 unset tgtb
1831 # check heads and top-bases and see what state the current
1832 # repository is in. remotes are ignored.
1834 hblist=" "
1835 topbases=
1836 both=
1837 newtb="heads/{top-bases}"
1838 while read -r rn && [ -n "$rn" ]; do case "$rn" in
1839 "refs/heads/{top-bases}"/*)
1840 case "$hblist" in *" ${rn#refs/$newtb/} "*)
1841 if [ "$topbases" != "heads/{top-bases}" ] && [ -n "$topbases" ]; then
1842 both=1
1843 break;
1844 else
1845 topbases="heads/{top-bases}"
1846 topbasesrx="heads/[{]top-bases[}]"
1847 oldbases="top-bases"
1849 esac;;
1850 "refs/top-bases"/*)
1851 case "$hblist" in *" ${rn#refs/top-bases/} "*)
1852 if [ "$topbases" != "top-bases" ] && [ -n "$topbases" ]; then
1853 both=1
1854 break;
1855 else
1856 topbases="top-bases"
1857 topbasesrx="top-bases"
1858 oldbases="heads/{top-bases}"
1860 esac;;
1861 "refs/heads"/*)
1862 hblist="$hblist${rn#refs/heads/} ";;
1863 esac; done <<-EOT
1864 $(git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null)
1866 if [ -n "$both" ]; then
1867 if [ -n "$1" ]; then
1868 # hook script always prefers newer without complaint
1869 topbases="heads/{top-bases}"
1870 topbasesrx="heads/[{]top-bases[}]"
1871 oldbases="top-bases"
1872 else
1873 # Complain and die
1874 err "repository contains existing TopGit branches"
1875 err "but some use refs/top-bases/... for the base"
1876 err "and some use refs/heads/{top-bases}/... for the base"
1877 err "with the latter being the new, preferred location"
1878 err "set \"topgit.top-bases\" to either \"heads\" to use"
1879 err "the new heads/{top-bases} location or \"refs\" to use"
1880 err "the old top-bases location."
1881 err "(the tg migrate-bases command can also resolve this issue)"
1882 die "schizophrenic repository requires topgit.top-bases setting"
1884 elif [ -n "$topbases" ]; then
1885 unset topbases_implicit_default
1888 [ -n "$topbases" ] || {
1889 # default is still top-bases for now
1890 topbases="top-bases"
1891 topbasesrx="top-bases"
1892 oldbases="heads/{top-bases}"
1894 # MUST NOT be exported
1895 unset hblist both newtb rn tg_topases_set
1896 tg_topbases_set=1
1897 return 0
1900 # init_reflog "ref"
1901 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
1902 # an empty log file to exist so that ref changes will be logged
1903 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
1904 # However, if "$1" is "refs/tgstash" then always make the reflog
1905 # The only ref not under refs/ that Git will write a reflog for is HEAD;
1906 # no matter what, it will NOT update a reflog for any other bare refs so
1907 # just quietly succeed when passed TG_STASH without doing anything.
1908 init_reflog()
1910 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
1911 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
1912 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
1913 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
1914 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
1917 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
1918 # a symbolic link. The directory part must exist, but the basename need not.
1919 v_get_abs_path()
1921 [ -n "$1" ] && [ -n "$2" ] || return 1
1922 set -- "$1" "$2" "${2%/}"
1923 case "$3" in
1924 */*) set -- "$1" "$2" "${3%/*}";;
1925 * ) set -- "$1" "$2" ".";;
1926 esac
1927 case "$2" in */)
1928 set -- "$1" "${2%/}" "$3" "/"
1929 esac
1930 [ -d "$3" ] || return 1
1931 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
1934 ## Startup
1936 : "${TG_INST_CMDDIR:=@cmddir@}"
1937 : "${TG_INST_SHAREDIR:=@sharedir@}"
1938 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1940 [ -d "$TG_INST_CMDDIR" ] ||
1941 die "No command directory: '$TG_INST_CMDDIR'"
1943 ## Include awk scripts and their utility functions (separated for easier debugging)
1945 [ -f "$TG_INST_CMDDIR/tg--awksome" ] && [ -r "$TG_INST_CMDDIR/tg--awksome" ] ||
1946 die "Missing awk scripts: '$TG_INST_CMDDIR/tg--awksome'"
1947 . "$TG_INST_CMDDIR/tg--awksome"
1949 if [ -n "$tg__include" ]; then
1951 # We were sourced from another script for our utility functions;
1952 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1953 # work as expected in every shell. See http://bugs.debian.org/516188
1955 # ensure setup happens
1957 initial_setup 1
1958 set_topbases 1
1960 else
1962 set -e
1964 tgbin="$0"
1965 tgdir="${tgbin%/}"
1966 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
1967 tgdir="${tgdir%/*}/"
1968 tgname="${tgbin##*/}"
1969 [ "$0" != "$tgname" ] || tgdir=""
1971 # If tg contains a '/' but does not start with one then replace it with an absolute path
1973 case "$0" in /*) ;; */*)
1974 tgdir="$(cd "${0%/*}" && pwd -P)/"
1975 tgbin="$tgdir$tgname"
1976 esac
1978 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
1979 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
1981 tgdisplaydir="$tgdir"
1982 tgdisplay="$tgbin"
1983 tgdisplayac="$tgdisplay"
1985 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
1986 _tgabs="$_tgnameabs" &&
1987 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
1988 [ "$_tgabs" = "$_tgnameabs" ]
1989 then
1990 tgdisplaydir=""
1991 tgdisplay="$tgname"
1992 tgdisplayac="$tgdisplay"
1994 [ -z "$_tgabs" ] || tgbin="$_tgabs"
1995 unset _tgabs _tgnameabs
1997 tg() { command "$tgbin" "$@"; }
1999 explicit_remote=
2000 explicit_dir=
2001 gitcdopt=
2002 noremote=
2004 cmd=
2005 while :; do case "$1" in
2007 help|--help|-h)
2008 cmd=help
2009 shift
2010 break;;
2012 status|--status)
2013 cmd=status
2014 shift
2015 break;;
2017 --hooks-path)
2018 cmd=hooks-path
2019 shift
2020 break;;
2022 --exec-path)
2023 cmd=exec-path
2024 shift
2025 break;;
2027 --top-bases)
2028 cmd=top-bases
2029 shift
2030 break;;
2033 shift
2034 if [ -z "$1" ]; then
2035 echo "Option -r requires an argument." >&2
2036 do_help
2037 exit 1
2039 unset noremote
2040 base_remote="$1"
2041 explicit_remote="$base_remote"
2042 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
2043 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
2044 shift;;
2047 unset base_remote explicit_remote
2048 noremote=1
2049 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
2050 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
2051 shift;;
2054 shift
2055 if [ -z "$1" ]; then
2056 echo "Option -C requires an argument." >&2
2057 do_help
2058 exit 1
2060 cd "$1"
2061 unset GIT_DIR GIT_COMMON_DIR
2062 if [ -z "$explicit_dir" ]; then
2063 explicit_dir="$1"
2064 else
2065 explicit_dir="$PWD"
2067 gitcdopt=" -C \"$explicit_dir\""
2068 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2069 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2070 tgdisplayac="$tgdisplay"
2071 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2072 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2073 shift;;
2076 shift
2077 if [ -z "$1" ]; then
2078 echo "Option -c requires an argument." >&2
2079 do_help
2080 exit 1
2082 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2083 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2084 export GIT_CONFIG_PARAMETERS
2085 shift;;
2088 shift
2089 break;;
2092 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2093 do_help
2094 exit 1;;
2097 break;;
2099 esac; done
2101 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
2103 ## Dispatch
2105 [ -n "$cmd" ] || { do_help; exit 1; }
2107 case "$cmd" in
2109 help)
2110 do_help "$@"
2111 exit 0;;
2113 status|st)
2114 unset base_remote
2115 basic_setup
2116 set_topbases
2117 do_status "$@"
2118 exit ${do_status_result:-0};;
2120 hooks-path)
2121 # Internal command
2122 echol "$TG_INST_HOOKSDIR";;
2124 exec-path)
2125 # Internal command
2126 echol "$TG_INST_CMDDIR";;
2128 top-bases)
2129 # Maintenance command
2130 ! git rev-parse --git-dir >/dev/null 2>&1 || setup_git_dirs
2131 set_topbases
2132 echol "refs/$topbases";;
2135 isutil=
2136 case "$cmd" in index-merge-one-file)
2137 isutil="-"
2138 esac
2139 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2140 looplevel="$TG_ALIAS_DEPTH"
2141 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2142 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2143 looplevel=0
2144 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2145 [ -n "$tgalias" ] || {
2146 echo "Unknown subcommand: $cmd" >&2
2147 do_help
2148 exit 1
2150 looplevel=$(( $looplevel + 1 ))
2151 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2152 TG_ALIAS_DEPTH="$looplevel"
2153 export TG_ALIAS_DEPTH
2154 if [ "!${tgalias#?}" = "$tgalias" ]; then
2155 unset GIT_PREFIX
2156 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2157 GIT_PREFIX="$pfx"
2158 export GIT_PREFIX
2160 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2161 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2162 else
2163 eval 'exec "$tgbin"' "$tgalias" '"$@"'
2165 die "alias execution failed for: $tgalias"
2167 unset TG_ALIAS_DEPTH
2169 showing_help=
2170 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2171 showing_help=1
2174 [ -n "$showing_help" ] || initial_setup
2175 [ -z "$noremote" ] || unset base_remote
2177 nomergesetup="$showing_help"
2178 case "$cmd" in base|contains|info|log|rebase|revert|summary|tag)
2179 # avoid merge setup where not necessary
2181 nomergesetup=1
2182 esac
2184 if [ -z "$nomergesetup" ]; then
2185 # make sure merging the .top* files will always behave sanely
2187 setup_ours
2188 setup_hook "pre-commit"
2191 # everything but rebase needs topbases set
2192 carefully="$showing_help"
2193 [ "$cmd" != "migrate-bases" ] || carefully=1
2194 [ "$cmd" = "rebase" ] || set_topbases $carefully
2196 _use_ref_cache=
2197 tg_read_only=1
2198 case "$cmd$showing_help" in
2199 contains|export|info|summary|tag)
2200 _use_ref_cache=1;;
2201 annihilate|create|delete|depend|import|update)
2202 tg_use_alt_odb=
2203 tg_read_only=;;
2204 esac
2205 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2207 fullcmd="${tgname:-tg} $cmd $*"
2208 . "$TG_INST_CMDDIR"/tg-$isutil$cmd;;
2209 esac