tg.sh: include bad ref in ref_exists_rev failure message
[topgit/pro.git] / tg.sh
blob2a2dfc04036a4ebe763a09428f4769e70cf0b3e2
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 tab=' '
21 lf='
24 ## Auxiliary functions
26 # Preserves current $? value while triggering a non-zero set -e exit if active
27 # This works even for shells that sometimes fail to correctly trigger a -e exit
28 check_exit_code()
30 return $?
33 # This is the POSIX equivalent of which
34 cmd_path()
36 { "unset" -f command unset unalias "$1"; } >/dev/null 2>&1 || :
37 { "unalias" -a; } >/dev/null 2>&1 || :
38 command -v "$1"
41 # helper for wrappers
42 # note deliberate use of '(' ... ')' rather than '{' ... '}'
43 exec_lc_all_c()
45 LC_ALL="C" &&
46 export LC_ALL &&
47 exec "$@"
50 # These tools work better for us with LC_ALL=C and by using these little
51 # convenience functions LC_ALL=C does not have to appear in the code but
52 # any Git translations will still appear for Git commands
53 awk() { exec_lc_all_c @AWK_PATH@ "$@"; }
54 cat() { exec_lc_all_c cat "$@"; }
55 cut() { exec_lc_all_c cut "$@"; }
56 find() { exec_lc_all_c find "$@"; }
57 grep() { exec_lc_all_c grep "$@"; }
58 join() { exec_lc_all_c join "$@"; }
59 paste() { exec_lc_all_c paste "$@"; }
60 sed() { exec_lc_all_c sed "$@"; }
61 sort() { exec_lc_all_c sort "$@"; }
62 tr() { exec_lc_all_c tr "$@"; }
63 wc() { exec_lc_all_c wc "$@"; }
64 xargs() { exec_lc_all_c xargs "$@"; }
66 # Output arguments without any possible interpretation
67 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
68 echol()
70 printf '%s\n' "$*"
73 info()
75 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
78 warn()
80 info "warning: $*" >&2
83 err()
85 info "error: $*" >&2
88 die()
90 info "fatal: $*" >&2
91 exit 1
94 # shift off first arg then return "$*" properly quoted in single-quotes
95 # if $1 was '' output goes to stdout otherwise it's assigned to $1
96 # the final \n, if any, is omitted from the result but any others are included
97 v_quotearg()
99 _quotearg_v="$1"
100 shift
101 set -- "$_quotearg_v" \
102 "sed \"s/'/'\\\\\\''/g;1s/^/'/;\\\$s/\\\$/'/;s/'''/'/g;1s/^''\\(.\\)/\\1/\"" "$*"
103 unset _quotearg_v
104 if [ -z "$3" ]; then
105 if [ -z "$1" ]; then
106 echo "''"
107 else
108 eval "$1=\"''\""
110 else
111 if [ -z "$1" ]; then
112 printf "%s$4" "$3" | eval "$2"
113 else
114 eval "$1="'"$(printf "%s$4" "$3" | eval "$2")"'
119 # same as v_quotearg except there's no extra $1 so output always goes to stdout
120 quotearg()
122 v_quotearg '' "$@"
125 vcmp()
127 # Compare $1 to $3 each of which must match ^[^0-9]*\d*(\.\d*)*.*$
128 # where only the "\d*" parts in the regex participate in the comparison
129 # Since EVERY string matches that regex this function is easy to use
130 # An empty string ('') for $1 or $3 or any "\d*" part is treated as 0
131 # $2 is a compare op '<', '<=', '=', '==', '!=', '>=', '>'
132 # Return code is 0 for true, 1 for false (or unknown compare op)
133 # There is NO difference in behavior between '=' and '=='
134 # Note that "vcmp 1.8 == 1.8.0.0.0.0" correctly returns 0
135 set -- "$1" "$2" "$3" "${1%%[0-9]*}" "${3%%[0-9]*}"
136 set -- "${1#"$4"}" "$2" "${3#"$5"}"
137 set -- "${1%%[!0-9.]*}" "$2" "${3%%[!0-9.]*}"
138 while
139 vcmp_a_="${1%%.*}"
140 vcmp_b_="${3%%.*}"
141 [ "z$vcmp_a_" != "z" -o "z$vcmp_b_" != "z" ]
143 if [ "${vcmp_a_:-0}" -lt "${vcmp_b_:-0}" ]; then
144 unset vcmp_a_ vcmp_b_
145 case "$2" in "<"|"<="|"!=") return 0; esac
146 return 1
147 elif [ "${vcmp_a_:-0}" -gt "${vcmp_b_:-0}" ]; then
148 unset vcmp_a_ vcmp_b_
149 case "$2" in ">"|">="|"!=") return 0; esac
150 return 1;
152 vcmp_a_="${1#$vcmp_a_}"
153 vcmp_b_="${3#$vcmp_b_}"
154 set -- "${vcmp_a_#.}" "$2" "${vcmp_b_#.}"
155 done
156 unset vcmp_a_ vcmp_b_
157 case "$2" in "="|"=="|"<="|">=") return 0; esac
158 return 1
161 precheck() {
162 if ! git_version="$(git version)"; then
163 die "'git version' failed"
165 case "$git_version" in [Gg]"it version "*);;*)
166 die "'git version' output does not start with 'git version '"
167 esac
169 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
170 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
173 case "$1" in version|--version|-V)
174 echo "TopGit version $TG_VERSION"
175 exit 0
176 esac
178 precheck
179 [ "$1" = "precheck" ] && exit 0
182 cat_depsmsg_internal()
184 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
185 if [ -s "$tg_cache_dir/$1/.$2" ]; then
186 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
187 _line=
188 while IFS= read -r _line || [ -n "$_line" ]; do
189 printf '%s\n' "$_line"
190 done
191 return 0
192 fi <"$tg_cache_dir/$1/.$2"
194 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null || :
195 if [ -d "$tg_cache_dir/$1" ]; then
196 printf '%s\n' "$_rev" >"$tg_cache_dir/$1/.$2"
197 _line=
198 git cat-file blob "$_rev:.$2" 2>/dev/null |
199 while IFS= read -r _line || [ -n "$_line" ]; do
200 printf '%s\n' "$_line" >&3
201 printf '%s\n' "$_line"
202 done 3>>"$tg_cache_dir/$1/.$2"
203 else
204 git cat-file blob "$_rev:.$2" 2>/dev/null
208 # cat_deps BRANCHNAME
209 # Caches result
210 cat_deps()
212 cat_depsmsg_internal "$1" topdeps
215 # cat_msg BRANCHNAME
216 # Caches result
217 cat_msg()
219 cat_depsmsg_internal "$1" topmsg
222 # cat_file TOPIC:PATH [FROM]
223 # cat the file PATH from branch TOPIC when FROM is empty.
224 # FROM can be -i or -w, than the file will be from the index or worktree,
225 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
226 cat_file()
228 path="$1"
229 case "$2" in
231 cat "$root_dir/${path#*:}"
234 # ':file' means cat from index
235 git cat-file blob ":${path#*:}" 2>/dev/null
238 case "$path" in
239 refs/heads/*:.topdeps)
240 _temp="${path%:.topdeps}"
241 cat_deps "${_temp#refs/heads/}"
243 refs/heads/*:.topmsg)
244 _temp="${path%:.topmsg}"
245 cat_msg "${_temp#refs/heads/}"
248 git cat-file blob "$path" 2>/dev/null
250 esac
253 die "Wrong argument to cat_file: '$2'"
255 esac
258 # if use_alt_temp_odb and tg_use_alt_odb are true try to write the object(s)
259 # into the temporary alt odb area instead of the usual location
260 git_temp_alt_odb_cmd()
262 if [ -n "$use_alt_temp_odb" ] && [ -n "$tg_use_alt_odb" ] &&
263 [ -n "$TG_OBJECT_DIRECTORY" ] &&
264 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
266 GIT_ALTERNATE_OBJECT_DIRECTORIES="$TG_PRESERVED_ALTERNATES"
267 GIT_OBJECT_DIRECTORY="$TG_OBJECT_DIRECTORY"
268 unset TG_OBJECT_DIRECTORY TG_PRESERVED_ALTERNATES
269 export GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
270 git "$@"
272 else
273 git "$@"
277 git_write_tree() { git_temp_alt_odb_cmd write-tree "$@"; }
278 git_mktree() { git_temp_alt_odb_cmd mktree "$@"; }
280 # get tree for the committed topic
281 get_tree_()
283 echo "refs/heads/$1"
286 # get tree for the base
287 get_tree_b()
289 echo "refs/$topbases/$1"
292 # get tree for the index
293 get_tree_i()
295 git_write_tree
298 # get tree for the worktree
299 get_tree_w()
301 i_tree=$(git_write_tree)
303 # the file for --index-output needs to sit next to the
304 # current index file
305 cd "$root_dir"
306 : ${GIT_INDEX_FILE:="$git_dir/index"}
307 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
308 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
309 GIT_INDEX_FILE="$TMP_INDEX" &&
310 export GIT_INDEX_FILE &&
311 git diff --name-only -z HEAD |
312 git update-index -z --add --remove --stdin &&
313 git_write_tree &&
314 rm -f "$TMP_INDEX"
318 # get tree for arbitrary ref
319 get_tree_r()
321 echo "$1"
324 # strip_ref "$(git symbolic-ref HEAD)"
325 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
326 strip_ref()
328 case "$1" in
329 refs/"$topbases"/*)
330 echol "${1#refs/$topbases/}"
332 refs/heads/*)
333 echol "${1#refs/heads/}"
336 echol "$1"
337 esac
340 # pretty_tree [-t] NAME [-b | -i | -w | -r]
341 # Output tree ID of a cleaned-up tree without tg's artifacts.
342 # NAME will be ignored for -i and -w, but needs to be present
343 # With -r NAME must be a full ref name to a treeish (it's used as-is)
344 # If -t is used the tree is written into the alternate temporary objects area
345 pretty_tree()
347 use_alt_temp_odb=
348 [ "$1" != "-t" ] || { shift; use_alt_temp_odb=1; }
349 name="$1"
350 source="${2#?}"
351 git ls-tree --full-tree "$(get_tree_$source "$name")" |
352 sed -ne '/ \.top.*$/!p' |
353 git_mktree
356 # return an empty-tree root commit -- date is either passed in or current
357 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
358 # An invalid secs causes the current date to be used, an invalid zone offset
359 # causes +0000 to be used
360 make_empty_commit()
362 # the empty tree is guaranteed to always be there even in a repo with
363 # zero objects, but for completeness we force it to exist as a real object
364 SECS=
365 read -r SECS ZONE JUNK <<-EOT || :
368 case "$SECS" in *[!0-9]*) SECS=; esac
369 if [ -z "$SECS" ]; then
370 MTDATE="$(date '+%s %z')"
371 else
372 case "$ZONE" in
373 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
375 [01][0-9][0-5][0-9])
376 ZONE="+$ZONE"
379 ZONE="+0000"
380 esac
381 MTDATE="$SECS $ZONE"
383 EMPTYID="- <-> $MTDATE"
384 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
385 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
386 git hash-object -t commit -w --stdin
389 # standard input is a diff
390 # standard output is the "+" lines with leading "+ " removed
391 diff_added_lines()
393 awk '
394 BEGIN { in_hunk = 0; }
395 /^@@ / { in_hunk = 1; }
396 /^\+/ { if (in_hunk == 1) printf("%s\n", substr($0, 2)); }
397 /^[^@ +-]/ { in_hunk = 0; }
401 # $1 is name of new branch to create locally if all of these are true:
402 # a) exists as a remote TopGit branch for "$base_remote"
403 # b) the branch "name" does not have any invalid characters in it
404 # c) neither of the two branch refs (branch or base) exist locally
405 # returns success only if a new local branch was created (and dumps message)
406 auto_create_local_remote()
408 case "$1" in ""|*[" $tab$lf~^:\\*?["]*|.*|*/.*|*.|*./|/*|*/|*//*) return 1; esac
409 [ -n "$base_remote" ] &&
410 git update-ref --stdin <<-EOT >/dev/null 2>&1 &&
411 verify refs/remotes/$base_remote/${topbases#heads/}/$1 refs/remotes/$base_remote/${topbases#heads/}/$1
412 verify refs/remotes/$base_remote/$1 refs/remotes/$base_remote/$1
413 create refs/$topbases/$1 refs/remotes/$base_remote/${topbases#heads/}/$1^0
414 create refs/heads/$1 refs/remotes/$base_remote/$1^0
416 { init_reflog "refs/$topbases/$1" || :; } &&
417 info "topic branch '$1' automatically set up from remote '$base_remote'"
420 # setup_hook NAME
421 setup_hook()
423 tgname="${0##*/}"
424 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
425 if [ -f "$git_hooks_dir/$1" ] && grep -Fq "$hook_call" "$git_hooks_dir/$1"; then
426 # Another job well done!
427 return
429 # Prepare incantation
430 hook_chain=
431 if [ -s "$git_hooks_dir/$1" -a -x "$git_hooks_dir/$1" ]; then
432 hook_call="$hook_call"' || exit $?'
433 if [ -L "$git_hooks_dir/$1" ] || ! sed -n 1p <"$git_hooks_dir/$1" | grep -Fqx "#!@SHELL_PATH@"; then
434 chain_num=
435 while [ -e "$git_hooks_dir/$1-chain$chain_num" ]; do
436 chain_num=$(( $chain_num + 1 ))
437 done
438 mv -f "$git_hooks_dir/$1" "$git_hooks_dir/$1-chain$chain_num"
439 hook_chain=1
441 else
442 hook_call="exec $hook_call"
443 [ -d "$git_hooks_dir" ] || mkdir -p "$git_hooks_dir" || :
445 # Don't call hook if tg is not installed
446 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
447 # Insert call into the hook
449 echol "#!@SHELL_PATH@"
450 echol "$hook_call"
451 if [ -n "$hook_chain" ]; then
452 echol "exec \"\$0-chain$chain_num\" \"\$@\""
453 else
454 [ ! -s "$git_hooks_dir/$1" ] || cat "$git_hooks_dir/$1"
456 } >"$git_hooks_dir/$1+"
457 chmod a+x "$git_hooks_dir/$1+"
458 mv "$git_hooks_dir/$1+" "$git_hooks_dir/$1"
461 # setup_ours (no arguments)
462 setup_ours()
464 if [ ! -s "$git_common_dir/info/attributes" ] || ! grep -q topmsg "$git_common_dir/info/attributes"; then
465 [ -d "$git_common_dir/info" ] || mkdir "$git_common_dir/info"
467 echo ".topmsg merge=ours"
468 echo ".topdeps merge=ours"
469 } >>"$git_common_dir/info/attributes"
471 if ! git config merge.ours.driver >/dev/null; then
472 git config merge.ours.name '"always keep ours" merge driver'
473 git config merge.ours.driver 'touch %A'
477 # measure_branch NAME [BASE] [EXTRAHEAD...]
478 measure_branch()
480 _bname="$1"; _base="$2"
481 shift; shift
482 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
483 # The caller should've verified $name is valid
484 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
485 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
486 if [ $_commits -ne 1 ]; then
487 _suffix="commits"
488 else
489 _suffix="commit"
491 echo "$_commits/$_nmcommits $_suffix"
494 # true if $1 is contained by (or the same as) $2
495 # this is never slower than merge-base --is-ancestor and is often slightly faster
496 contained_by()
498 [ "$(git rev-list --count --max-count=1 "$1" --not "$2" --)" = "0" ]
501 # branch_contains B1 B2
502 # Whether B1 is a superset of B2.
503 branch_contains()
505 _revb1="$(ref_exists_rev "$1")" || return 0
506 _revb2="$(ref_exists_rev "$2")" || return 0
507 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
508 if read _result _rev_matchb1 _rev_matchb2 &&
509 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
510 return $_result
511 fi <"$tg_cache_dir/$1/.bc/$2/.d"
513 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
514 _result=0
515 contained_by "$_revb2" "$_revb1" || _result=1
516 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
517 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
519 return $_result
522 create_ref_dirs()
524 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
525 awk -v p="$tg_tmp_dir/cached/" '{print p $1}' <"$tg_ref_cache" | tr '\n' '\0' | xargs -0 mkdir -p
526 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
529 # If the first argument is non-empty, stores "1" there if this call created the cache
530 v_create_ref_cache()
532 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
533 _remotespec=
534 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
535 [ -z "$1" ] || eval "$1=1"
536 git for-each-ref --format='%(refname) %(objectname)' \
537 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
538 create_ref_dirs
541 remove_ref_cache()
543 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
544 >"$tg_ref_cache"
547 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
548 rev_parse()
550 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
551 awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
552 else
553 [ -z "$tg_ref_cache_only" ] || return 1
554 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
558 # ref_exists_rev REF
559 # Whether REF is a valid ref name
560 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
561 # or, if $base_remote is set, refs/remotes/$base_remote/
562 # Caches result if $tg_read_only and outputs HASH on success
563 ref_exists_rev()
565 case "$1" in
566 refs/*)
568 $octet20)
569 printf '%s' "$1"
570 return;;
572 die "ref_exists_rev requires fully-qualified ref name (given: $1)"
573 esac
574 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
575 _result=
576 _result_rev=
577 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
578 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
579 _result_rev="$(rev_parse "$1")"
580 _result=$?
581 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
582 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
583 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
584 printf '%s' "$_result_rev"
585 return $_result
588 # Same as ref_exists_rev but output is abbreviated hash
589 # Optional second argument defaults to --short but may be any --short=.../--no-short option
590 ref_exists_rev_short()
592 case "$1" in
593 refs/*)
595 $octet20)
598 die "ref_exists_rev_short requires fully-qualified ref name"
599 esac
600 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
601 _result=
602 _result_rev=
603 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
604 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
605 _result_rev="$(rev_parse "$1")"
606 _result=$?
607 if [ $_result -eq 0 ]; then
608 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev" --)"
609 _result=$?
611 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
612 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
613 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
614 printf '%s' "$_result_rev"
615 return $_result
618 # ref_exists REF
619 # Whether REF is a valid ref name
620 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
621 # or, if $base_remote is set, refs/remotes/$base_remote/
622 # Caches result
623 ref_exists()
625 ref_exists_rev "$1" >/dev/null
628 # rev_parse_tree REF
629 # Runs git rev-parse REF^{tree}
630 # Caches result if $tg_read_only
631 rev_parse_tree()
633 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
634 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
635 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
636 printf '%s\n' "$_result"
637 return 0
639 return 1
641 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
642 if [ -d "$tg_tmp_dir/cached/$1" ]; then
643 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
644 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
645 printf '%s\n' "$_result"
646 return 0
648 return 1
650 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
653 # has_remote BRANCH
654 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
655 has_remote()
657 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
660 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
661 # If -z "$1" still set return code but do not return result
662 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
663 # refs/heads/... then ... will be verified instead.
664 # if "$3" = "-f" (for fail) then return an error rather than dying.
665 v_verify_topgit_branch()
667 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
668 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
669 [ -n "$_verifyname" -o "$3" = "-f" ] || die "HEAD is not a symbolic ref"
670 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
671 [ "$3" != "-f" ] || return 1
672 die "HEAD is not a symbolic ref to the refs/heads namespace"
673 esac
674 set -- "$1" "$_verifyname" "$3"
676 case "$2" in
677 refs/"$topbases"/*)
678 _verifyname="${2#refs/$topbases/}"
680 refs/heads/*)
681 _verifyname="${2#refs/heads/}"
684 _verifyname="$2"
686 esac
687 if ! ref_exists "refs/heads/$_verifyname"; then
688 [ "$3" != "-f" ] || return 1
689 die "no such branch: $_verifyname"
691 if ! ref_exists "refs/$topbases/$_verifyname"; then
692 [ "$3" != "-f" ] || return 1
693 die "not a TopGit-controlled branch: $_verifyname"
695 [ -z "$1" ] || eval "$1="'"$_verifyname"'
698 # Return the verified TopGit branch name or die with an error.
699 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
700 # refs/heads/... then ... will be verified instead.
701 # if "$2" = "-f" (for fail) then return an error rather than dying.
702 verify_topgit_branch()
704 v_verify_topgit_branch _verifyname "$@" || return
705 printf '%s' "$_verifyname"
708 # Caches result
709 # $1 = branch name (i.e. "t/foo/bar")
710 # $2 = optional result of rev-parse "refs/heads/$1"
711 # $3 = optional result of rev-parse "refs/$topbases/$1"
712 branch_annihilated()
714 _branch_name="$1"
715 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
716 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
718 _result=
719 _result_rev=
720 _result_rev_base=
721 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/$_branch_name/.ann"; } 2>/dev/null || :
722 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
724 # use the merge base in case the base is ahead.
725 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
727 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
728 _result=$?
729 [ -d "$tg_cache_dir/$_branch_name" ] || mkdir -p "$tg_cache_dir/$_branch_name" 2>/dev/null
730 [ ! -d "$tg_cache_dir/$_branch_name" ] ||
731 echo $_result $_rev $_rev_base >"$tg_cache_dir/$_branch_name/.ann" 2>/dev/null || :
732 return $_result
735 non_annihilated_branches()
737 [ $# -gt 0 ] || set -- "refs/$topbases"
738 git for-each-ref --format='%(objectname) %(refname)' "$@" |
739 while read rev ref; do
740 name="${ref#refs/$topbases/}"
741 if branch_annihilated "$name" "" "$rev"; then
742 continue
744 echol "$name"
745 done
748 # Make sure our tree is clean
749 # if optional "$1" given also verify that a checkout to "$1" would succeed
750 ensure_clean_tree()
752 check_status
753 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
754 git update-index --ignore-submodules --refresh ||
755 die "the working directory has uncommitted changes (see above) - first commit or reset them"
756 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
757 die "the index has uncommited changes"
758 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
759 die "git checkout \"$1\" would fail"
762 # is_sha1 REF
763 # Whether REF is a SHA1 (compared to a symbolic name).
764 is_sha1()
766 case "$1" in $octet20) return 0;; esac
767 return 1
770 # recurse_deps_internal NAME [BRANCHPATH...]
771 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
772 # followed by a 1 if the branch is "tgish" (2 if it also has a remote); 0 if not
773 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
774 # but missing and remotes are always "0"
775 # then the branch name followed by its depedency chain (which might be empty)
776 # An output line might look like this:
777 # 0 1 1 t/foo/leaf t/foo/int t/stage
778 # If no_remotes is non-empty, exclude remotes
779 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
780 # but the leaf info will always be 0 or 2 in that case
781 # If with_top_level is non-empty, include the top-level that's normally omitted
782 # any branch names in the space-separated recurse_deps_exclude variable
783 # are skipped (along with their dependencies)
784 recurse_deps_internal()
786 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
787 _ref_hash=
788 if ! _ref_hash="$(ref_exists_rev "refs/heads/$1")"; then
789 [ -z "$2" ] || echo "1 0 0 $*"
790 return 0
793 _is_tgish=0
794 _ref_hash_base=
795 _is_leaf=0
796 ! _ref_hash_base="$(ref_exists_rev "refs/$topbases/$1")" || _is_tgish=1
797 [ "$_is_tgish" = "0" ] || [ -n "$no_remotes" ] || ! has_remote "${topbases#heads/}/$1" || _is_tgish=2
798 [ "$_is_tgish" = "0" ] || ! branch_annihilated "$1" "$_ref_hash" "$_ref_hash_base" || _is_leaf=2
799 [ -z "$recurse_preorder" -o -z "${2:-$with_top_level}" ] || echo "0 $_is_tgish $_is_leaf $*"
801 # If no_remotes is unset also check our base against remote base.
802 # Checking our head against remote head has to be done in the helper.
803 if [ "$_is_tgish" = "2" ]; then
804 echo "0 0 0 refs/remotes/$base_remote/${topbases#heads/}/$1 $*"
807 # if the branch was annihilated, it is considered to have no dependencies
808 [ "$_is_leaf" = "2" ] || _is_leaf=1
809 if [ "$_is_tgish" != "0" ] && [ "$_is_leaf" = "1" ]; then
810 #TODO: handle nonexisting .topdeps?
811 while read _dname && [ -n "$_dname" ]; do
812 # Avoid depedency loops
813 case " $* " in *" $_dname "*)
814 warn "dependency loop detected in branch $_dname"
815 _is_leaf=0
816 continue
817 esac
818 # Shoo shoo, leave our environment alone!
819 _dep_is_leaf=0
820 (recurse_deps_internal "$_dname" "$@") || _dep_is_leaf=$?
821 [ "$_dep_is_leaf" = "2" ] || _is_leaf=0
822 done <<-EOT
823 $(cat_deps "$1")
827 [ -n "$recurse_preorder" -o -z "${2:-$with_top_level}" ] || echo "0 $_is_tgish $_is_leaf $*"
828 return ${_is_leaf:-0}
831 # do_eval CMD
832 # helper for recurse_deps so that a return statement executed inside CMD
833 # does not return from recurse_deps. This shouldn't be necessary, but it
834 # seems that it actually is.
835 do_eval()
837 eval "$@"
840 # becomes read-only for caching purposes
841 # assigns new value to tg_read_only
842 # become_cacheable/undo_become_cacheable calls may be nested
843 become_cacheable()
845 _old_tg_read_only="$tg_read_only"
846 if [ -z "$tg_read_only" ]; then
847 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
848 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
849 tg_read_only=1
851 _my_ref_cache=
852 v_create_ref_cache _my_ref_cache
853 _my_ref_cache="${_my_ref_cache:+1}"
854 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
857 # restores tg_read_only and ref_cache to state before become_cacheable call
858 # become_cacheable/undo_bocome_cacheable calls may be nested
859 undo_become_cacheable()
861 case "$tg_read_only" in
862 "undo"[01]"-"*)
863 _suffix="${tg_read_only#undo?-}"
864 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
865 tg_read_only="$_suffix"
866 esac
869 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
870 become_non_cacheable()
872 remove_ref_cache
873 tg_read_only=
874 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
875 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
878 # call this to make sure Git will not complain about a missing user/email
879 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
880 ensure_ident_available()
882 [ -z "$TG_IDENT_CHECKED" ] || return 0
883 git var GIT_AUTHOR_IDENT >/dev/null &&
884 git var GIT_COMMITTER_IDENT >/dev/null || exit
885 TG_IDENT_CHECKED=1
886 export TG_IDENT_CHECKED
887 return 0
890 # recurse_deps CMD NAME [BRANCHPATH...]
891 # Recursively eval CMD on all dependencies of NAME.
892 # Dependencies are visited in topological order.
893 # CMD can refer to the following variables:
895 # _ret starts as 0; CMD can change; will be final return result
896 # _dep bare branch name or "refs/remotes/..." for a remote base
897 # _name has $_dep in its .topdeps ("" for top and $with_top_level)
898 # _depchain 0+ space-separated branch names forming a path to top
899 # _dep_missing boolean "1" if no such $_dep ref; "" if ref present
900 # _dep_is_leaf boolean "1" if leaf; "" if not
901 # _dep_is_tgish boolean "1" if tgish; "" if not (which implies no remote)
902 # _dep_has_remote boolean "1" if $_dep has_remote; "" if not
903 # _dep_annihilated boolean "1" if $_dep annihilated; "" if not
905 # CMD may use a "return" statement without issue; its return value is ignored,
906 # but if CMD sets _ret to a negative value, e.g. "-0" or "-1" the enumeration
907 # will stop immediately and the value with the leading "-" stripped off will
908 # be the final result code
910 # CMD can refer to $_name for queried branch name,
911 # $_dep for dependency name,
912 # $_depchain for space-seperated branch backtrace,
913 # $_dep_missing boolean to check whether $_dep is present
914 # and the $_dep_is_tgish and $_dep_annihilated booleans.
915 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
916 # It can modify $_ret to affect the return value
917 # of the whole function.
918 # If recurse_deps() hits missing dependencies, it will append
919 # them to space-separated $missing_deps list and skip them
920 # after calling CMD with _dep_missing set.
921 # remote dependencies are processed if no_remotes is unset.
922 # any branch names in the space-separated recurse_deps_exclude variable
923 # are skipped (along with their dependencies)
924 recurse_deps()
926 _cmd="$1"; shift
928 become_cacheable
929 _depsfile="$(get_temp tg-depsfile)"
930 recurse_deps_internal "$@" >>"$_depsfile" || :
931 undo_become_cacheable
933 _ret=0
934 while read _ismissing _istgish _isleaf _dep _name _deppath; do
935 _depchain="$_name${_deppath:+ $_deppath}"
936 _dep_is_tgish=
937 [ "$_istgish" = "0" ] || _dep_is_tgish=1
938 _dep_has_remote=
939 [ "$_istgish" != "2" ] || _dep_has_remote=1
940 _dep_missing=
941 if [ "$_ismissing" != "0" ]; then
942 _dep_missing=1
943 case " $missing_deps " in *" $_dep "*);;*)
944 missing_deps="${missing_deps:+$missing_deps }$_dep"
945 esac
947 _dep_annihilated=
948 _dep_is_leaf=
949 if [ "$_isleaf" = "1" ]; then
950 _dep_is_leaf=1
951 elif [ "$_isleaf" = "2" ]; then
952 _dep_annihilated=1
954 do_eval "$_cmd" || :
955 if [ "${_ret#-}" != "$_ret" ]; then
956 _ret="${_ret#-}"
957 break
959 done <"$_depsfile"
960 rm -f "$_depsfile"
961 return ${_ret:-0}
964 find_leaves_internal()
966 if [ -n "$_dep_is_leaf" ] && [ -z "$_dep_annihilated" ] && [ -z "$_dep_missing" ]; then
967 if [ -n "$_dep_is_tgish" ]; then
968 fulldep="refs/$topbases/$_dep"
969 else
970 fulldep="refs/heads/$_dep"
972 case " $seen_leaf_refs " in *" $fulldep "*);;*)
973 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
974 if fullrev="$(ref_exists_rev "$fulldep")"; then
975 case " $seen_leaf_revs " in *" $fullrev "*);;*)
976 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
977 # See if Git knows it by another name
978 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
979 echo "refs/tags/$tagname"
980 else
981 echo "$fulldep"
983 esac
985 esac
989 # find_leaves NAME
990 # output (one per line) the unique leaves of NAME
991 # a leaf is either
992 # 1) a non-tgish dependency
993 # 2) the base of a tgish dependency with no non-annihilated dependencies
994 # duplicates are suppressed (by commit rev) and remotes are always ignored
995 # if a leaf has an exact tag match that will be output
996 # note that recurse_deps_exclude IS honored for this operation
997 find_leaves()
999 no_remotes=1
1000 with_top_level=1
1001 recurse_preorder=
1002 seen_leaf_refs=
1003 seen_leaf_revs=
1004 recurse_deps find_leaves_internal "$1"
1005 with_top_level=
1008 # branch_needs_update
1009 # This is a helper function for determining whether given branch
1010 # is up-to-date wrt. its dependencies. It expects input as if it
1011 # is called as a recurse_deps() helper.
1012 # In case the branch does need update, it will echo it together
1013 # with the branch backtrace on the output (see needs_update()
1014 # description for details) and set $_ret to non-zero.
1015 branch_needs_update()
1017 if [ -n "$_dep_missing" ]; then
1018 echo "! $_dep $_depchain"
1019 return 0
1022 if [ -n "$_dep_is_tgish" ]; then
1023 branch_annihilated "$_dep" && return 0
1025 if has_remote "$_dep"; then
1026 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
1027 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
1029 # We want to sync with our base first and should output this before
1030 # the remote branch, but the order does not actually matter to tg-update
1031 # as it just recurses regardless, but it does matter for tg-info (which
1032 # treats out-of-date bases as though they were already merged in) so
1033 # we output the remote before the base.
1034 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
1035 echo ": $_dep $_depchain"
1036 _ret=1
1037 return
1041 if [ -n "$_name" ]; then
1042 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
1043 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
1044 # Some new commits in _dep
1045 echo "$_dep $_depchain"
1046 _ret=1
1051 # needs_update NAME
1052 # This function is recursive; it outputs reverse path from NAME
1053 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
1054 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
1055 # if the head is not in sync with the <remote> branch <name>, ':' if
1056 # the head is not in sync with the base (in this order of priority)
1057 # or '!' if dependency is missing. Note that the remote branch, base
1058 # order is reversed from the order they will actually be updated in
1059 # order to accomodate tg info which treats out-of-date items that are
1060 # only in the base as already being in the head for status purposes.
1061 # It will also return non-zero status if NAME needs update.
1062 # If needs_update() hits missing dependencies, it will append
1063 # them to space-separated $missing_deps list and skip them.
1064 needs_update()
1066 recurse_deps branch_needs_update "$1"
1069 # branch_empty NAME [-i | -w]
1070 branch_empty()
1072 if [ -z "$2" ]; then
1073 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
1074 _result=
1075 _result_rev=
1076 { read -r _result _result_rev <"$tg_cache_dir/$1/.mt"; } 2>/dev/null || :
1077 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
1078 _result=0
1079 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ] || _result=$?
1080 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null
1081 [ ! -d "$tg_cache_dir/$1" ] || echo $_result $_rev >"$tg_cache_dir/$1/.mt"
1082 return $_result
1083 else
1084 [ "$(pretty_tree -t "$1" -b)" = "$(pretty_tree -t "$1" $2)" ]
1088 # list_deps [-i | -w] [BRANCH]
1089 # -i/-w apply only to HEAD
1090 list_deps()
1092 head_from=
1093 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
1094 head="$(git symbolic-ref -q HEAD)" ||
1095 head="..detached.."
1097 git for-each-ref --format='%(objectname) %(refname)' "refs/$topbases${1:+/$1}" |
1098 while read rev ref; do
1099 name="${ref#refs/$topbases/}"
1100 if branch_annihilated "$name" "" "$rev"; then
1101 continue
1104 from=$head_from
1105 [ "refs/heads/$name" = "$head" ] ||
1106 from=
1107 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
1108 dep_is_tgish=true
1109 ref_exists "refs/$topbases/$dep" ||
1110 dep_is_tgish=false
1111 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
1112 echo "$name $dep"
1114 done
1115 done
1118 # checkout_symref_full [-f] FULLREF [SEED]
1119 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1120 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1121 # MUST be a committish which if present will be used instead of current FULLREF
1122 # (and FULLREF will be updated to it as well in that case)
1123 # Any merge state is always cleared by this function
1124 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset
1125 # instead of -m) but it will clear out any unmerged entries
1126 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1127 checkout_symref_full()
1129 _mode=-m
1130 if [ "$1" = "-f" ]; then
1131 _mode="--reset"
1132 shift
1134 _ishash=
1135 case "$1" in
1136 refs/?*)
1138 $octet20)
1139 _ishash=1
1140 [ -z "$2" ] || [ "$1" = "$2" ] ||
1141 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1142 set -- HEAD "$1"
1145 die "programmer error: invalid checkout_symref_full \"$1\""
1147 esac
1148 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1149 die "invalid committish: \"${2:-$1}\""
1150 # Clear out any MERGE_HEAD kruft
1151 rm -f "$git_dir/MERGE_HEAD" || :
1152 # We have to do all the hard work ourselves :/
1153 # This is like git checkout -b "$1" "$2"
1154 # (or just git checkout "$1"),
1155 # but never creates a detached HEAD (unless $1 is a hash)
1156 git read-tree -u $_mode HEAD "$_seedrev" &&
1158 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1159 git update-ref "$1" "$_seedrev"
1160 } && {
1161 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1165 # switch_to_base NAME [SEED]
1166 switch_to_base()
1168 checkout_symref_full "refs/$topbases/$1" "$2"
1171 # run editor with arguments
1172 # the editor setting will be cached in $tg_editor (which is eval'd)
1173 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1174 run_editor()
1176 tg_editor="$GIT_EDITOR"
1177 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1178 eval "$tg_editor" '"$@"'
1181 # Show the help messages.
1182 do_help()
1184 _www=
1185 if [ "$1" = "-w" ]; then
1186 _www=1
1187 shift
1189 if [ -z "$1" ] ; then
1190 # This is currently invoked in all kinds of circumstances,
1191 # including when the user made a usage error. Should we end up
1192 # providing more than a short help message, then we should
1193 # differentiate.
1194 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1196 ## Build available commands list for help output
1198 cmds=
1199 sep=
1200 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1201 ! [ -r "$cmd" ] && continue
1202 # strip directory part and "tg-" prefix
1203 cmd="${cmd##*/}"
1204 cmd="${cmd#tg-}"
1205 [ "$cmd" != "migrate-bases" ] || continue
1206 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1207 cmds="$cmds$sep$cmd"
1208 sep="|"
1209 done
1211 echo "TopGit version $TG_VERSION - A different patch queue manager"
1212 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
1213 echo " Or: $tgname help [-w] [<command>]"
1214 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1215 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1216 if [ -n "$_www" ]; then
1217 nohtml=
1218 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1219 echo "${0##*/}: missing html help file:" \
1220 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1221 nohtml=1
1223 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1224 echo "${0##*/}: missing html help file:" \
1225 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1226 nohtml=1
1228 if [ -n "$nohtml" ]; then
1229 echo "${0##*/}: use" \
1230 "\"${0##*/} help $1\" instead" 1>&2
1231 exit 1
1233 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1234 exit
1236 output()
1238 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1239 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1240 echo
1241 elif [ "$1" = "help" ]; then
1242 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1243 echo
1244 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1245 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1246 echo
1248 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1249 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1252 page output "$1"
1253 else
1254 echo "${0##*/}: no help for $1" 1>&2
1255 do_help
1256 exit 1
1260 check_status()
1262 git_state=
1263 git_remove=
1264 if [ -e "$git_dir/MERGE_HEAD" ]; then
1265 git_state="merge"
1266 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1267 git_state="am"
1268 git_remove="$git_dir/rebase-apply"
1269 elif [ -e "$git_dir/rebase-apply" ]; then
1270 git_state="rebase"
1271 git_remove="$git_dir/rebase-apply"
1272 elif [ -e "$git_dir/rebase-merge" ]; then
1273 git_state="rebase"
1274 git_remove="$git_dir/rebase-merge"
1275 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1276 git_state="cherry-pick"
1277 elif [ -e "$git_dir/BISECT_LOG" ]; then
1278 git_state="bisect"
1279 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1280 git_state="revert"
1282 git_remove="${git_remove#./}"
1284 tg_state=
1285 tg_remove=
1286 tg_topmerge=
1287 if [ -e "$git_dir/tg-update" ]; then
1288 tg_state="update"
1289 tg_remove="$git_dir/tg-update"
1290 ! [ -s "$git_dir/tg-update/merging_topfiles" ] || tg_topmerge=1
1292 tg_remove="${tg_remove#./}"
1295 # Show status information
1296 do_status()
1298 do_status_result=0
1299 do_status_verbose=
1300 do_status_help=
1301 abbrev=refs
1302 pfx=
1303 while [ $# -gt 0 ] && case "$1" in
1304 --help|-h)
1305 do_status_help=1
1306 break;;
1307 -vv)
1308 # kludge in this common bundling option
1309 abbrev=
1310 do_status_verbose=1
1311 pfx="## "
1313 --verbose|-v)
1314 [ -z "$do_status_verbose" ] || abbrev=
1315 do_status_verbose=1
1316 pfx="## "
1318 --exit-code)
1319 do_status_result=2
1322 die "unknown status argument: $1"
1324 esac; do shift; done
1325 if [ -n "$do_status_help" ]; then
1326 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1327 return
1329 check_status
1330 symref="$(git symbolic-ref --quiet HEAD)" || :
1331 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1332 if [ -n "$symref" ]; then
1333 uprefpart=
1334 if [ -n "$headrv" ]; then
1335 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1336 if [ -n "$upref" ]; then
1337 uprefpart=" ... ${upref#$abbrev/remotes/}"
1338 mbase="$(git merge-base HEAD "$upref")" || :
1339 ahead="$(git rev-list --count HEAD ${mbase:+--not $mbase})" || ahead=0
1340 behind="$(git rev-list --count "$upref" ${mbase:+--not $mbase})" || behind=0
1341 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1342 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1343 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1344 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1345 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1348 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1349 else
1350 echol "${pfx}HEAD -> ${headrv:-?}"
1352 if [ -n "$tg_state" ]; then
1353 extra=
1354 if [ "$tg_state" = "update" ]; then
1355 IFS= read -r uname <"$git_dir/tg-update/name" || :
1356 [ -z "$uname" ] ||
1357 extra="; currently updating branch '$uname'"
1359 echol "${pfx}tg $tg_state in progress$extra"
1360 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1361 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1362 cat "$git_dir/tg-update/fullcmd"
1363 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1364 if [ $bcnt -gt 1 ]; then
1365 pcnt=0
1366 ! [ -s "$git_dir/tg-update/processed" ] ||
1367 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1368 echo "${pfx}$pcnt of $bcnt branches updated so far"
1371 if [ "$tg_state" = "update" ]; then
1372 echol "${pfx} (use \"$tgdisplayac update --continue\" to continue)"
1373 echol "${pfx} (use \"$tgdisplayac update --skip\" to skip this branch and continue)"
1374 echol "${pfx} (use \"$tgdisplayac update --stop\" to stop and retain changes so far)"
1375 echol "${pfx} (use \"$tgdisplayac update --abort\" to restore pre-update state)"
1378 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1379 if [ "$git_state" = "merge" ]; then
1380 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1381 if [ $ucnt -gt 0 ]; then
1382 echo "${pfx}"'fix conflicts and then "git commit" the result'
1383 else
1384 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1387 if [ -z "$git_state" ]; then
1388 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository
1389 gspcnt=0
1390 [ -z "$gsp" ] ||
1391 gspcnt="$(( $(printf '%s\n' "$gsp" | sed -n '/^??/!p' | wc -l) ))"
1392 untr=
1393 if [ "$gspcnt" -eq 0 ]; then
1394 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1395 echo "${pfx}working directory is clean$untr"
1396 [ -n "$tg_state" ] || do_status_result=0
1397 else
1398 echo "${pfx}working directory is DIRTY"
1399 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1404 ## Pager stuff
1406 # isatty FD
1407 isatty()
1409 test -t $1
1412 # pass "diff" to get pager.diff
1413 # if pager.$1 is a boolean false returns cat
1414 # if set to true or unset fails
1415 # otherwise succeeds and returns the value
1416 get_pager()
1418 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1419 [ "$_x" != "true" ] || return 1
1420 echo "cat"
1421 return 0
1423 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1424 echol "$_x"
1425 return 0
1427 return 1
1430 # setup_pager
1431 # Set TG_PAGER to a valid executable
1432 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1433 # See also the following "page" function for ease of use
1434 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1435 # Preference is (same as Git):
1436 # 1. GIT_PAGER
1437 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1438 # 3. core.pager (only if set)
1439 # 4. PAGER
1440 # 5. git var GIT_PAGER
1441 # 6. less
1442 setup_pager()
1444 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1446 emptypager=
1447 if [ -z "$TG_PAGER_IN_USE" ]; then
1448 # TG_PAGER = GIT_PAGER | PAGER | less
1449 # NOTE: GIT_PAGER='' is significant
1450 if [ -n "${GIT_PAGER+set}" ]; then
1451 TG_PAGER="$GIT_PAGER"
1452 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1453 TG_PAGER="$_dp"
1454 elif _cp="$(git config core.pager 2>/dev/null)"; then
1455 TG_PAGER="$_cp"
1456 elif [ -n "${PAGER+set}" ]; then
1457 TG_PAGER="$PAGER"
1458 else
1459 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1460 [ "$_gp" != ":" ] || _gp=
1461 TG_PAGER="${_gp:-less}"
1463 if [ -z "$TG_PAGER" ]; then
1464 emptypager=1
1465 TG_PAGER=cat
1467 else
1468 emptypager=1
1469 TG_PAGER=cat
1472 # Set pager default environment variables
1473 # see pager.c:setup_pager
1474 if [ -z "${LESS+set}" ]; then
1475 LESS="-FRX"
1476 export LESS
1478 if [ -z "${LV+set}" ]; then
1479 LV="-c"
1480 export LV
1483 # this is needed so e.g. $(git diff) will still colorize it's output if
1484 # requested in ~/.gitconfig with color.diff=auto
1485 GIT_PAGER_IN_USE=1
1486 export GIT_PAGER_IN_USE
1488 # this is needed so we don't get nested pagers
1489 TG_PAGER_IN_USE=1
1490 export TG_PAGER_IN_USE
1493 # page eval_arg [arg ...]
1495 # Calls setup_pager then evals the first argument passing it all the rest
1496 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1497 # by setup_pager (in which case the output is left as-is).
1499 # To handle arbitrary paging duties, collect lines to be paged into a
1500 # function and then call page with the function name or perhaps func_name "$@".
1502 # If no arguments at all are passed in do nothing (return with success).
1503 page()
1505 [ $# -gt 0 ] || return 0
1506 setup_pager
1507 _evalarg="$1"; shift
1508 if [ -n "$emptypager" ]; then
1509 eval "$_evalarg" '"$@"'
1510 else
1511 eval "$_evalarg" '"$@"' | eval "$TG_PAGER"
1515 # get_temp NAME [-d]
1516 # creates a new temporary file (or directory with -d) in the global
1517 # temporary directory $tg_tmp_dir with pattern prefix NAME
1518 get_temp()
1520 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1523 # automatically called by strftime
1524 # does nothing if already setup
1525 # may be called explicitly if the first call would otherwise be in a subshell
1526 # so that the setup is only done once before subshells start being spawned
1527 setup_strftime()
1529 [ -z "$strftime_is_setup" ] || return 0
1531 # date option to format raw epoch seconds values
1532 daterawopt=
1533 _testes='951807788'
1534 _testdt='2000-02-29 07:03:08 UTC'
1535 _testfm='%Y-%m-%d %H:%M:%S %Z'
1536 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1537 daterawopt='-d@'
1538 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1539 daterawopt='-r'
1541 strftime_is_setup=1
1544 # $1 => strftime format string to use
1545 # $2 => raw timestamp as seconds since epoch
1546 # $3 => optional time zone string (empty/absent for local time zone)
1547 strftime()
1549 setup_strftime
1550 if [ -n "$daterawopt" ]; then
1551 if [ -n "$3" ]; then
1552 TZ="$3" date "$daterawopt$2" "+$1"
1553 else
1554 date "$daterawopt$2" "+$1"
1556 else
1557 if [ -n "$3" ]; then
1558 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1559 else
1560 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1565 got_cdup_result=
1566 git_cdup_result=
1567 v_get_show_cdup()
1569 if [ -z "$got_cdup_result" ]; then
1570 git_cdup_result="$(git rev-parse --show-cdup)"
1571 got_cdup_result=1
1573 [ -z "$1" ] || eval "$1="'"$git_cdup_result"'
1576 setup_git_dirs()
1578 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1579 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1580 git_dir="$(cd "$git_dir" && pwd)"
1582 if [ -z "$git_common_dir" ]; then
1583 if vcmp "$git_version" '>=' "2.5"; then
1584 # rev-parse --git-common-dir is broken and may give
1585 # an incorrect result unless the current directory is
1586 # already set to the top level directory
1587 v_get_show_cdup
1588 git_common_dir="$(cd "./$git_cdup_result" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1589 else
1590 git_common_dir="$git_dir"
1593 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1594 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1595 git_hooks_dir="$git_common_dir/hooks"
1596 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1597 case "$gchp" in
1598 /[!/]*)
1599 git_hooks_dir="$gchp"
1602 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1604 esac
1605 unset gchp
1609 basic_setup()
1611 setup_git_dirs $1
1612 if [ -z "$base_remote" ]; then
1613 if [ "${TG_EXPLICIT_REMOTE+set}" = "set" ]; then
1614 base_remote="$TG_EXPLICIT_REMOTE"
1615 else
1616 base_remote="$(git config topgit.remote 2>/dev/null)" || :
1619 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1620 tgnosequester=
1621 [ "$tgsequester" != "false" ] || tgnosequester=1
1622 unset tgsequester
1624 # catch errors if topbases is used without being set
1625 unset tg_topbases_set
1626 topbases="programmer*:error"
1627 topbasesrx="programmer*:error}"
1628 oldbases="$topbases"
1631 ## Initial setup
1632 initial_setup()
1634 # suppress the merge log editor feature since git 1.7.10
1636 GIT_MERGE_AUTOEDIT=no
1637 export GIT_MERGE_AUTOEDIT
1639 basic_setup $1
1640 iowopt=
1641 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
1642 auhopt=
1643 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1644 v_get_show_cdup root_dir
1645 root_dir="${root_dir:-.}"
1646 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1647 [ "$logrefupdates" = "true" ] || logrefupdates=
1649 # make sure root_dir doesn't end with a trailing slash.
1651 root_dir="${root_dir%/}"
1653 # create global temporary directories, inside GIT_DIR
1655 tg_tmp_dir=
1656 trap 'rm -rf "$tg_tmp_dir"' EXIT
1657 trap 'exit 129' HUP
1658 trap 'exit 130' INT
1659 trap 'exit 131' QUIT
1660 trap 'exit 134' ABRT
1661 trap 'exit 143' TERM
1662 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1663 [ -n "$tg_tmp_dir" ] || tg_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1664 [ -n "$tg_tmp_dir" ] || [ -z "$TMPDIR" ] || tg_tmp_dir="$(mktemp -d "/tmp/tg-tmp.XXXXXX" 2>/dev/null)" || tg_tmp_dir=
1665 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1666 [ -n "$tg_tmp_dir" ] && [ -w "$tg_tmp_dir" ] && { >"$tg_ref_cache"; } >/dev/null 2>&1 ||
1667 die "could not create a writable temporary directory"
1669 # make sure global cache directory exists inside GIT_DIR or $tg_tmp_dir
1671 user_id_no="$(id -u)" || :
1672 : "${user_id_no:=_99_}"
1673 tg_cache_dir="$git_common_dir/tg-cache"
1674 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1675 [ -z "$tg_cache_dir" ] || tg_cache_dir="$tg_cache_dir/$user_id_no"
1676 [ -z "$tg_cache_dir" ] || [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1677 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1678 if [ -z "$tg_cache_dir" ]; then
1679 tg_cache_dir="$tg_tmp_dir/tg-cache"
1680 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir" >/dev/null 2>&1 || tg_cache_dir=
1681 [ -z "$tg_cache_dir" ] || { >"$tg_cache_dir/.tgcache"; } >/dev/null 2>&1 || tg_cache_dir=
1683 [ -n "$tg_cache_dir" ] ||
1684 die "could not create a writable tg-cache directory (even a temporary one)"
1686 # GIT_ALTERNATE_OBJECT_DIRECTORIES can contain double-quoted entries
1687 # since Git v2.11.1; however, it's only necessary for : (or perhaps ;)
1688 # so we avoid it if possible and require v2.11.1 to do it at all
1689 # otherwise just don't make an alternates temporary store in that case;
1690 # it's okay to not have one; everything will still work; the nicety of
1691 # making the temporary tree objects vanish when tg exits just won't
1692 # happen in that case but nothing will break also be sure to reuse
1693 # the parent's if we've been recursively invoked and it's for the
1694 # same repository we were invoked on
1696 tg_use_alt_odb=1
1697 _odbdir="${GIT_OBJECT_DIRECTORY:-$git_common_dir/objects}"
1698 [ -n "$_odbdir" ] && [ -d "$_odbdir" ] || tg_use_alt_odb=
1699 _fulltmpdir=
1700 [ -z "$tg_use_alt_odb" ] || _fulltmpdir="$(cd "$tg_tmp_dir" && pwd -P)"
1701 case "$_fulltmpdir" in *[";:"]*) vcmp "$git_version" '>=' "2.11.1" || tg_use_alt_odb=; esac
1702 _fullodbdir=
1703 [ -z "$tg_use_alt_odb" ] || _fullodbdir="$(cd "$_odbdir" && pwd -P)"
1704 if [ -n "$tg_use_alt_odb" ] && [ -n "$TG_OBJECT_DIRECTORY" ] && [ -d "$TG_OBJECT_DIRECTORY/info" ] &&
1705 [ -f "$TG_OBJECT_DIRECTORY/info/alternates" ] && [ -r "$TG_OBJECT_DIRECTORY/info/alternates" ]; then
1706 if IFS= read -r _otherodbdir <"$TG_OBJECT_DIRECTORY/info/alternates" &&
1707 [ -n "$_otherodbdir" ] && [ "$_otherodbdir" = "$_fullodbdir" ]; then
1708 tg_use_alt_odb=2
1711 if [ "$tg_use_alt_odb" = "1" ]; then
1712 # create an alternate objects database to keep the ephemeral objects in
1713 mkdir -p "$tg_tmp_dir/objects/info"
1714 echol "$_fullodbdir" >"$tg_tmp_dir/objects/info/alternates"
1715 TG_OBJECT_DIRECTORY="$_fulltmpdir/objects"
1716 case "$TG_OBJECT_DIRECTORY" in
1717 *[";:"]*)
1718 # surround in "..." and backslash-escape internal '"' and '\\'
1719 _altodbdq="\"$(printf '%s\n' "$TG_OBJECT_DIRECTORY" |
1720 sed 's/\([""\\]\)/\\\1/g')\""
1723 _altodbdq="$TG_OBJECT_DIRECTORY"
1725 esac
1726 TG_PRESERVED_ALTERNATES="$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1727 if [ -n "$GIT_ALTERNATE_OBJECT_DIRECTORIES" ]; then
1728 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq:$GIT_ALTERNATE_OBJECT_DIRECTORIES"
1729 else
1730 GIT_ALTERNATE_OBJECT_DIRECTORIES="$_altodbdq"
1732 export TG_PRESERVED_ALTERNATES TG_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_OBJECT_DIRECTORY
1736 set_topbases()
1738 # refer to "top-bases" in a refname with $topbases
1740 [ -z "$tg_topbases_set" ] || return 0
1742 topbases_implicit_default=1
1743 # See if topgit.top-bases is set to heads or refs
1744 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
1745 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
1746 if [ -n "$1" ]; then
1747 # never die on the hook script
1748 unset tgtb
1749 else
1750 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
1753 if [ -n "$tgtb" ]; then
1754 case "$tgtb" in
1755 heads)
1756 topbases="heads/{top-bases}"
1757 topbasesrx="heads/[{]top-bases[}]"
1758 oldbases="top-bases";;
1759 refs)
1760 topbases="top-bases"
1761 topbasesrx="top-bases"
1762 oldbases="heads/{top-bases}";;
1763 esac
1764 # MUST NOT be exported
1765 unset tgtb tg_topbases_set topbases_implicit_default
1766 tg_topbases_set=1
1767 return 0
1769 unset tgtb
1771 # check heads and top-bases and see what state the current
1772 # repository is in. remotes are ignored.
1774 hblist=" "
1775 topbases=
1776 both=
1777 newtb="heads/{top-bases}"
1778 while read -r rn && [ -n "$rn" ]; do case "$rn" in
1779 "refs/heads/{top-bases}"/*)
1780 case "$hblist" in *" ${rn#refs/$newtb/} "*)
1781 if [ "$topbases" != "heads/{top-bases}" ] && [ -n "$topbases" ]; then
1782 both=1
1783 break;
1784 else
1785 topbases="heads/{top-bases}"
1786 topbasesrx="heads/[{]top-bases[}]"
1787 oldbases="top-bases"
1789 esac;;
1790 "refs/top-bases"/*)
1791 case "$hblist" in *" ${rn#refs/top-bases/} "*)
1792 if [ "$topbases" != "top-bases" ] && [ -n "$topbases" ]; then
1793 both=1
1794 break;
1795 else
1796 topbases="top-bases"
1797 topbasesrx="top-bases"
1798 oldbases="heads/{top-bases}"
1800 esac;;
1801 "refs/heads"/*)
1802 hblist="$hblist${rn#refs/heads/} ";;
1803 esac; done <<-EOT
1804 $(git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null)
1806 if [ -n "$both" ]; then
1807 if [ -n "$1" ]; then
1808 # hook script always prefers newer without complaint
1809 topbases="heads/{top-bases}"
1810 topbasesrx="heads/[{]top-bases[}]"
1811 oldbases="top-bases"
1812 else
1813 # Complain and die
1814 err "repository contains existing TopGit branches"
1815 err "but some use refs/top-bases/... for the base"
1816 err "and some use refs/heads/{top-bases}/... for the base"
1817 err "with the latter being the new, preferred location"
1818 err "set \"topgit.top-bases\" to either \"heads\" to use"
1819 err "the new heads/{top-bases} location or \"refs\" to use"
1820 err "the old top-bases location."
1821 err "(the tg migrate-bases command can also resolve this issue)"
1822 die "schizophrenic repository requires topgit.top-bases setting"
1824 elif [ -n "$topbases" ]; then
1825 unset topbases_implicit_default
1828 [ -n "$topbases" ] || {
1829 # default is still top-bases for now
1830 topbases="top-bases"
1831 topbasesrx="top-bases"
1832 oldbases="heads/{top-bases}"
1834 # MUST NOT be exported
1835 unset hblist both newtb rn tg_topases_set
1836 tg_topbases_set=1
1837 return 0
1840 # init_reflog "ref"
1841 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
1842 # an empty log file to exist so that ref changes will be logged
1843 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
1844 # However, if "$1" is "refs/tgstash" then always make the reflog
1845 # The only ref not under refs/ that Git will write a reflog for is HEAD;
1846 # no matter what, it will NOT update a reflog for any other bare refs so
1847 # just quietly succeed when passed TG_STASH without doing anything.
1848 init_reflog()
1850 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
1851 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
1852 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
1853 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
1854 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
1857 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
1858 # a symbolic link. The directory part must exist, but the basename need not.
1859 v_get_abs_path()
1861 [ -n "$1" ] && [ -n "$2" ] || return 1
1862 set -- "$1" "$2" "${2%/}"
1863 case "$3" in
1864 */*) set -- "$1" "$2" "${3%/*}";;
1865 * ) set -- "$1" "$2" ".";;
1866 esac
1867 case "$2" in */)
1868 set -- "$1" "${2%/}" "$3" "/"
1869 esac
1870 [ -d "$3" ] || return 1
1871 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}$4"'
1874 ## Startup
1876 : "${TG_INST_CMDDIR:=@cmddir@}"
1877 : "${TG_INST_SHAREDIR:=@sharedir@}"
1878 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1880 [ -d "$TG_INST_CMDDIR" ] ||
1881 die "No command directory: '$TG_INST_CMDDIR'"
1883 if [ -n "$tg__include" ]; then
1885 # We were sourced from another script for our utility functions;
1886 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1887 # work as expected in every shell. See http://bugs.debian.org/516188
1889 # ensure setup happens
1891 initial_setup 1
1892 set_topbases 1
1894 else
1896 set -e
1898 tgbin="$0"
1899 tgdir="${tgbin%/}"
1900 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
1901 tgdir="${tgdir%/*}/"
1902 tgname="${tgbin##*/}"
1903 [ "$0" != "$tgname" ] || tgdir=""
1905 # If tg contains a '/' but does not start with one then replace it with an absolute path
1907 case "$0" in /*) ;; */*)
1908 tgdir="$(cd "${0%/*}" && pwd -P)/"
1909 tgbin="$tgdir$tgname"
1910 esac
1912 # tgdisplay will include any explicit -C <dir> etc. options whereas tgname will not
1913 # tgdisplayac is the same as tgdisplay but without any -r or -u options (ac => abort/continue)
1915 tgdisplaydir="$tgdir"
1916 tgdisplay="$tgbin"
1917 tgdisplayac="$tgdisplay"
1919 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
1920 _tgabs="$_tgnameabs" &&
1921 { [ "$tgbin" = "$tgname" ] || v_get_abs_path _tgabs "$tgbin"; } &&
1922 [ "$_tgabs" = "$_tgnameabs" ]
1923 then
1924 tgdisplaydir=""
1925 tgdisplay="$tgname"
1926 tgdisplayac="$tgdisplay"
1928 [ -z "$_tgabs" ] || tgbin="$_tgabs"
1929 unset _tgabs _tgnameabs
1931 tg() { command "$tgbin" "$@"; }
1933 explicit_remote=
1934 explicit_dir=
1935 gitcdopt=
1936 noremote=
1938 cmd=
1939 while :; do case "$1" in
1941 help|--help|-h)
1942 cmd=help
1943 shift
1944 break;;
1946 status|--status)
1947 cmd=status
1948 shift
1949 break;;
1951 --hooks-path)
1952 cmd=hooks-path
1953 shift
1954 break;;
1956 --exec-path)
1957 cmd=exec-path
1958 shift
1959 break;;
1961 --top-bases)
1962 cmd=top-bases
1963 shift
1964 break;;
1967 shift
1968 if [ -z "$1" ]; then
1969 echo "Option -r requires an argument." >&2
1970 do_help
1971 exit 1
1973 unset noremote
1974 base_remote="$1"
1975 explicit_remote="$base_remote"
1976 tgdisplay="$tgdisplaydir$tgname$gitcdopt -r $explicit_remote"
1977 TG_EXPLICIT_REMOTE="$base_remote" && export TG_EXPLICIT_REMOTE
1978 shift;;
1981 unset base_remote explicit_remote
1982 noremote=1
1983 tgdisplay="$tgdisplaydir$tgname$gitcdopt -u"
1984 TG_EXPLICIT_REMOTE= && export TG_EXPLICIT_REMOTE
1985 shift;;
1988 shift
1989 if [ -z "$1" ]; then
1990 echo "Option -C requires an argument." >&2
1991 do_help
1992 exit 1
1994 cd "$1"
1995 unset GIT_DIR GIT_COMMON_DIR
1996 if [ -z "$explicit_dir" ]; then
1997 explicit_dir="$1"
1998 else
1999 explicit_dir="$PWD"
2001 gitcdopt=" -C \"$explicit_dir\""
2002 [ "$explicit_dir" != "." ] || explicit_dir="." gitcdopt=" -C ."
2003 tgdisplay="$tgdisplaydir$tgname$gitcdopt"
2004 tgdisplayac="$tgdisplay"
2005 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
2006 [ -z "$noremote" ] || tgdisplay="$tgdisplay -u"
2007 shift;;
2010 shift
2011 if [ -z "$1" ]; then
2012 echo "Option -c requires an argument." >&2
2013 do_help
2014 exit 1
2016 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
2017 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
2018 export GIT_CONFIG_PARAMETERS
2019 shift;;
2022 shift
2023 break;;
2026 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
2027 do_help
2028 exit 1;;
2031 break;;
2033 esac; done
2035 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
2037 ## Dispatch
2039 [ -n "$cmd" ] || { do_help; exit 1; }
2041 case "$cmd" in
2043 help)
2044 do_help "$@"
2045 exit 0;;
2047 status|st)
2048 unset base_remote
2049 basic_setup
2050 set_topbases
2051 do_status "$@"
2052 exit ${do_status_result:-0};;
2054 hooks-path)
2055 # Internal command
2056 echol "$TG_INST_HOOKSDIR";;
2058 exec-path)
2059 # Internal command
2060 echol "$TG_INST_CMDDIR";;
2062 top-bases)
2063 # Maintenance command
2064 ! git rev-parse --git-dir >/dev/null 2>&1 || setup_git_dirs
2065 set_topbases
2066 echol "refs/$topbases";;
2069 isutil=
2070 case "$cmd" in index-merge-one-file)
2071 isutil="-"
2072 esac
2073 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
2074 looplevel="$TG_ALIAS_DEPTH"
2075 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
2076 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
2077 looplevel=0
2078 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
2079 [ -n "$tgalias" ] || {
2080 echo "Unknown subcommand: $cmd" >&2
2081 do_help
2082 exit 1
2084 looplevel=$(( $looplevel + 1 ))
2085 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
2086 TG_ALIAS_DEPTH="$looplevel"
2087 export TG_ALIAS_DEPTH
2088 if [ "!${tgalias#?}" = "$tgalias" ]; then
2089 unset GIT_PREFIX
2090 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
2091 GIT_PREFIX="$pfx"
2092 export GIT_PREFIX
2094 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
2095 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
2096 else
2097 eval 'exec "$tgbin"' "$tgalias" '"$@"'
2099 die "alias execution failed for: $tgalias"
2101 unset TG_ALIAS_DEPTH
2103 showing_help=
2104 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
2105 showing_help=1
2108 [ -n "$showing_help" ] || initial_setup
2109 [ -z "$noremote" ] || unset base_remote
2111 nomergesetup="$showing_help"
2112 case "$cmd" in base|contains|info|log|rebase|revert|summary|tag)
2113 # avoid merge setup where not necessary
2115 nomergesetup=1
2116 esac
2118 if [ -z "$nomergesetup" ]; then
2119 # make sure merging the .top* files will always behave sanely
2121 setup_ours
2122 setup_hook "pre-commit"
2125 # everything but rebase needs topbases set
2126 carefully="$showing_help"
2127 [ "$cmd" != "migrate-bases" ] || carefully=1
2128 [ "$cmd" = "rebase" ] || set_topbases $carefully
2130 _use_ref_cache=
2131 tg_read_only=1
2132 case "$cmd$showing_help" in
2133 contains|export|info|summary|tag)
2134 _use_ref_cache=1;;
2135 annihilate|create|delete|depend|import|update)
2136 tg_use_alt_odb=
2137 tg_read_only=;;
2138 esac
2139 [ -z "$_use_ref_cache" ] || v_create_ref_cache
2141 fullcmd="${tgname:-tg} $cmd $*"
2142 . "$TG_INST_CMDDIR"/tg-$isutil$cmd;;
2143 esac