test-lib-functions-tg.sh: introduce TopGit-specific test functions library
[topgit/pro.git] / tg.sh
blob3adb43aabe9e036cb60e2c003efe019320a1ade7
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 # Output arguments without any possible interpretation
42 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
43 echol()
45 printf '%s\n' "$*"
48 info()
50 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
53 warn()
55 info "warning: $*" >&2
58 err()
60 info "error: $*" >&2
63 die()
65 info "fatal: $*" >&2
66 exit 1
69 # shift off first arg then return "$*" properly quoted in single-quotes
70 # if $1 was '' output goes to stdout otherwise it's assigned to $1
71 # the final \n, if any, is omitted from the result but any others are included
72 v_quotearg()
74 _quotearg_v="$1"
75 shift
76 set -- "$_quotearg_v" \
77 "sed \"s/'/'\\\\\\''/g;1s/^/'/;\\\$s/\\\$/'/;s/'''/'/g;1s/^''\\(.\\)/\\1/\"" "$*"
78 unset _quotearg_v
79 if [ -z "$3" ]; then
80 if [ -z "$1" ]; then
81 echo "''"
82 else
83 eval "$1=\"''\""
85 else
86 if [ -z "$1" ]; then
87 printf "%s$4" "$3" | eval "$2"
88 else
89 eval "$1="'"$(printf "%s$4" "$3" | eval "$2")"'
94 # same as v_quotearg except there's no extra $1 so output always goes to stdout
95 quotearg()
97 v_quotearg '' "$@"
100 vcmp()
102 # Compare $1 to $3 each of which must match ^[^0-9]*\d*(\.\d*)*.*$
103 # where only the "\d*" parts in the regex participate in the comparison
104 # Since EVERY string matches that regex this function is easy to use
105 # An empty string ('') for $1 or $3 or any "\d*" part is treated as 0
106 # $2 is a compare op '<', '<=', '=', '==', '!=', '>=', '>'
107 # Return code is 0 for true, 1 for false (or unknown compare op)
108 # There is NO difference in behavior between '=' and '=='
109 # Note that "vcmp 1.8 == 1.8.0.0.0.0" correctly returns 0
110 set -- "$1" "$2" "$3" "${1%%[0-9]*}" "${3%%[0-9]*}"
111 set -- "${1#"$4"}" "$2" "${3#"$5"}"
112 set -- "${1%%[!0-9.]*}" "$2" "${3%%[!0-9.]*}"
113 while
114 vcmp_a_="${1%%.*}"
115 vcmp_b_="${3%%.*}"
116 [ "z$vcmp_a_" != "z" -o "z$vcmp_b_" != "z" ]
118 if [ "${vcmp_a_:-0}" -lt "${vcmp_b_:-0}" ]; then
119 unset vcmp_a_ vcmp_b_
120 case "$2" in "<"|"<="|"!=") return 0; esac
121 return 1
122 elif [ "${vcmp_a_:-0}" -gt "${vcmp_b_:-0}" ]; then
123 unset vcmp_a_ vcmp_b_
124 case "$2" in ">"|">="|"!=") return 0; esac
125 return 1;
127 vcmp_a_="${1#$vcmp_a_}"
128 vcmp_b_="${3#$vcmp_b_}"
129 set -- "${vcmp_a_#.}" "$2" "${vcmp_b_#.}"
130 done
131 unset vcmp_a_ vcmp_b_
132 case "$2" in "="|"=="|"<="|">=") return 0; esac
133 return 1
136 precheck() {
137 if ! git_version="$(git version)"; then
138 die "'git version' failed"
140 case "$git_version" in [Gg]"it version "*);;*)
141 die "'git version' output does not start with 'git version '"
142 esac
144 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
145 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
148 case "$1" in version|--version|-V)
149 echo "TopGit version $TG_VERSION"
150 exit 0
151 esac
153 precheck
154 [ "$1" = "precheck" ] && exit 0
157 cat_depsmsg_internal()
159 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
160 if [ -s "$tg_cache_dir/$1/.$2" ]; then
161 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
162 _line=
163 while IFS= read -r _line || [ -n "$_line" ]; do
164 printf '%s\n' "$_line"
165 done
166 return 0
167 fi <"$tg_cache_dir/$1/.$2"
169 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null || :
170 if [ -d "$tg_cache_dir/$1" ]; then
171 printf '%s\n' "$_rev" >"$tg_cache_dir/$1/.$2"
172 _line=
173 git cat-file blob "$_rev:.$2" 2>/dev/null |
174 while IFS= read -r _line || [ -n "$_line" ]; do
175 printf '%s\n' "$_line" >&3
176 printf '%s\n' "$_line"
177 done 3>>"$tg_cache_dir/$1/.$2"
178 else
179 git cat-file blob "$_rev:.$2" 2>/dev/null
183 # cat_deps BRANCHNAME
184 # Caches result
185 cat_deps()
187 cat_depsmsg_internal "$1" topdeps
190 # cat_msg BRANCHNAME
191 # Caches result
192 cat_msg()
194 cat_depsmsg_internal "$1" topmsg
197 # cat_file TOPIC:PATH [FROM]
198 # cat the file PATH from branch TOPIC when FROM is empty.
199 # FROM can be -i or -w, than the file will be from the index or worktree,
200 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
201 cat_file()
203 path="$1"
204 case "$2" in
206 cat "$root_dir/${path#*:}"
209 # ':file' means cat from index
210 git cat-file blob ":${path#*:}"
213 case "$path" in
214 refs/heads/*:.topdeps)
215 _temp="${path%:.topdeps}"
216 cat_deps "${_temp#refs/heads/}"
218 refs/heads/*:.topmsg)
219 _temp="${path%:.topmsg}"
220 cat_msg "${_temp#refs/heads/}"
223 git cat-file blob "$path"
225 esac
228 die "Wrong argument to cat_file: '$2'"
230 esac
233 # get tree for the committed topic
234 get_tree_()
236 echo "refs/heads/$1"
239 # get tree for the base
240 get_tree_b()
242 echo "refs/$topbases/$1"
245 # get tree for the index
246 get_tree_i()
248 git write-tree
251 # get tree for the worktree
252 get_tree_w()
254 i_tree=$(git write-tree)
256 # the file for --index-output needs to sit next to the
257 # current index file
258 cd "$root_dir"
259 : ${GIT_INDEX_FILE:="$git_dir/index"}
260 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
261 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
262 GIT_INDEX_FILE="$TMP_INDEX" &&
263 export GIT_INDEX_FILE &&
264 git diff --name-only -z HEAD |
265 git update-index -z --add --remove --stdin &&
266 git write-tree &&
267 rm -f "$TMP_INDEX"
271 # strip_ref "$(git symbolic-ref HEAD)"
272 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
273 strip_ref()
275 case "$1" in
276 refs/"$topbases"/*)
277 echol "${1#refs/$topbases/}"
279 refs/heads/*)
280 echol "${1#refs/heads/}"
283 echol "$1"
284 esac
287 # pretty_tree NAME [-b | -i | -w]
288 # Output tree ID of a cleaned-up tree without tg's artifacts.
289 # NAME will be ignored for -i and -w, but needs to be present
290 pretty_tree()
292 name=$1
293 source=${2#?}
294 git ls-tree --full-tree "$(get_tree_$source "$name")" |
295 LC_ALL=C sed -ne '/ \.top.*$/!p' |
296 git mktree
299 # return an empty-tree root commit -- date is either passed in or current
300 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
301 # An invalid secs causes the current date to be used, an invalid zone offset
302 # causes +0000 to be used
303 make_empty_commit()
305 # the empty tree is guaranteed to always be there even in a repo with
306 # zero objects, but for completeness we force it to exist as a real object
307 SECS=
308 read -r SECS ZONE JUNK <<-EOT || :
311 case "$SECS" in *[!0-9]*) SECS=; esac
312 if [ -z "$SECS" ]; then
313 MTDATE="$(date '+%s %z')"
314 else
315 case "$ZONE" in
316 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
318 [01][0-9][0-5][0-9])
319 ZONE="+$ZONE"
322 ZONE="+0000"
323 esac
324 MTDATE="$SECS $ZONE"
326 EMPTYID="- <-> $MTDATE"
327 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
328 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
329 git hash-object -t commit -w --stdin
332 # setup_hook NAME
333 setup_hook()
335 tgname="${0##*/}"
336 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
337 if [ -f "$git_hooks_dir/$1" ] && LC_ALL=C grep -Fq "$hook_call" "$git_hooks_dir/$1"; then
338 # Another job well done!
339 return
341 # Prepare incantation
342 hook_chain=
343 if [ -s "$git_hooks_dir/$1" -a -x "$git_hooks_dir/$1" ]; then
344 hook_call="$hook_call"' || exit $?'
345 if [ -L "$git_hooks_dir/$1" ] || ! LC_ALL=C sed -n 1p <"$git_hooks_dir/$1" | LC_ALL=C grep -Fqx "#!@SHELL_PATH@"; then
346 chain_num=
347 while [ -e "$git_hooks_dir/$1-chain$chain_num" ]; do
348 chain_num=$(( $chain_num + 1 ))
349 done
350 mv -f "$git_hooks_dir/$1" "$git_hooks_dir/$1-chain$chain_num"
351 hook_chain=1
353 else
354 hook_call="exec $hook_call"
355 [ -d "$git_hooks_dir" ] || mkdir -p "$git_hooks_dir" || :
357 # Don't call hook if tg is not installed
358 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
359 # Insert call into the hook
361 echol "#!@SHELL_PATH@"
362 echol "$hook_call"
363 if [ -n "$hook_chain" ]; then
364 echol "exec \"\$0-chain$chain_num\" \"\$@\""
365 else
366 [ ! -s "$git_hooks_dir/$1" ] || cat "$git_hooks_dir/$1"
368 } >"$git_hooks_dir/$1+"
369 chmod a+x "$git_hooks_dir/$1+"
370 mv "$git_hooks_dir/$1+" "$git_hooks_dir/$1"
373 # setup_ours (no arguments)
374 setup_ours()
376 if [ ! -s "$git_common_dir/info/attributes" ] || ! grep -q topmsg "$git_common_dir/info/attributes"; then
377 [ -d "$git_common_dir/info" ] || mkdir "$git_common_dir/info"
379 echo ".topmsg merge=ours"
380 echo ".topdeps merge=ours"
381 } >>"$git_common_dir/info/attributes"
383 if ! git config merge.ours.driver >/dev/null; then
384 git config merge.ours.name '"always keep ours" merge driver'
385 git config merge.ours.driver 'touch %A'
389 # measure_branch NAME [BASE] [EXTRAHEAD...]
390 measure_branch()
392 _bname="$1"; _base="$2"
393 shift; shift
394 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
395 # The caller should've verified $name is valid
396 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
397 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
398 if [ $_commits -ne 1 ]; then
399 _suffix="commits"
400 else
401 _suffix="commit"
403 echo "$_commits/$_nmcommits $_suffix"
406 # branch_contains B1 B2
407 # Whether B1 is a superset of B2.
408 branch_contains()
410 _revb1="$(ref_exists_rev "$1")" || return 0
411 _revb2="$(ref_exists_rev "$2")" || return 0
412 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
413 if read _result _rev_matchb1 _rev_matchb2 &&
414 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
415 return $_result
416 fi <"$tg_cache_dir/$1/.bc/$2/.d"
418 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
419 _result=0
420 [ "$(git rev-list --count --max-count=1 "$_revb2" --not "$_revb1" --)" = "0" ] || _result=1
421 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
422 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
424 return $_result
427 create_ref_dirs()
429 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
430 LC_ALL=C awk -v p="$tg_tmp_dir/cached/" '{print p $1}' <"$tg_ref_cache" | LC_ALL=C tr '\n' '\0' | xargs -0 mkdir -p
431 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
434 # If the first argument is non-empty, stores "1" there if this call created the cache
435 v_create_ref_cache()
437 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
438 _remotespec=
439 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
440 [ -z "$1" ] || eval "$1=1"
441 git for-each-ref --format='%(refname) %(objectname)' \
442 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
443 create_ref_dirs
446 remove_ref_cache()
448 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
449 >"$tg_ref_cache"
452 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
453 rev_parse()
455 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
456 LC_ALL=C awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
457 else
458 [ -z "$tg_ref_cache_only" ] || return 1
459 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
463 # ref_exists_rev REF
464 # Whether REF is a valid ref name
465 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
466 # or, if $base_remote is set, refs/remotes/$base_remote/
467 # Caches result if $tg_read_only and outputs HASH on success
468 ref_exists_rev()
470 case "$1" in
471 refs/*)
473 $octet20)
474 printf '%s' "$1"
475 return;;
477 die "ref_exists_rev requires fully-qualified ref name"
478 esac
479 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
480 _result=
481 _result_rev=
482 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
483 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
484 _result_rev="$(rev_parse "$1")"
485 _result=$?
486 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
487 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
488 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
489 printf '%s' "$_result_rev"
490 return $_result
493 # Same as ref_exists_rev but output is abbreviated hash
494 # Optional second argument defaults to --short but may be any --short=.../--no-short option
495 ref_exists_rev_short()
497 case "$1" in
498 refs/*)
500 $octet20)
503 die "ref_exists_rev_short requires fully-qualified ref name"
504 esac
505 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
506 _result=
507 _result_rev=
508 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
509 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
510 _result_rev="$(rev_parse "$1")"
511 _result=$?
512 if [ $_result -eq 0 ]; then
513 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev" --)"
514 _result=$?
516 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
517 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
518 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
519 printf '%s' "$_result_rev"
520 return $_result
523 # ref_exists REF
524 # Whether REF is a valid ref name
525 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
526 # or, if $base_remote is set, refs/remotes/$base_remote/
527 # Caches result
528 ref_exists()
530 ref_exists_rev "$1" >/dev/null
533 # rev_parse_tree REF
534 # Runs git rev-parse REF^{tree}
535 # Caches result if $tg_read_only
536 rev_parse_tree()
538 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
539 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
540 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
541 printf '%s\n' "$_result"
542 return 0
544 return 1
546 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
547 if [ -d "$tg_tmp_dir/cached/$1" ]; then
548 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
549 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
550 printf '%s\n' "$_result"
551 return 0
553 return 1
555 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
558 # has_remote BRANCH
559 # Whether BRANCH has a remote equivalent (accepts ${topbases#heads/}/ too)
560 has_remote()
562 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
565 # Return the verified TopGit branch name for "$2" in "$1" or die with an error.
566 # If -z "$1" still set return code but do not return result
567 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
568 # refs/heads/... then ... will be verified instead.
569 # if "$3" = "-f" (for fail) then return an error rather than dying.
570 v_verify_topgit_branch()
572 if [ "$2" = "HEAD" ] || [ "$2" = "@" ]; then
573 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
574 [ -n "$_verifyname" -o "$3" = "-f" ] || die "HEAD is not a symbolic ref"
575 case "$_verifyname" in refs/"$topbases"/*|refs/heads/*);;*)
576 [ "$3" != "-f" ] || return 1
577 die "HEAD is not a symbolic ref to the refs/heads namespace"
578 esac
579 set -- "$1" "$_verifyname" "$3"
581 case "$2" in
582 refs/"$topbases"/*)
583 _verifyname="${2#refs/$topbases/}"
585 refs/heads/*)
586 _verifyname="${2#refs/heads/}"
589 _verifyname="$2"
591 esac
592 if ! ref_exists "refs/heads/$_verifyname"; then
593 [ "$3" != "-f" ] || return 1
594 die "no such branch: $_verifyname"
596 if ! ref_exists "refs/$topbases/$_verifyname"; then
597 [ "$3" != "-f" ] || return 1
598 die "not a TopGit-controlled branch: $_verifyname"
600 [ -z "$1" ] || eval "$1="'"$_verifyname"'
603 # Return the verified TopGit branch name or die with an error.
604 # As a convenience, if HEAD or @ is given and HEAD is a symbolic ref to
605 # refs/heads/... then ... will be verified instead.
606 # if "$2" = "-f" (for fail) then return an error rather than dying.
607 verify_topgit_branch()
609 v_verify_topgit_branch _verifyname "$@" || return
610 printf '%s' "$_verifyname"
613 # Caches result
614 # $1 = branch name (i.e. "t/foo/bar")
615 # $2 = optional result of rev-parse "refs/heads/$1"
616 # $3 = optional result of rev-parse "refs/$topbases/$1"
617 branch_annihilated()
619 _branch_name="$1"
620 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
621 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
623 _result=
624 _result_rev=
625 _result_rev_base=
626 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/$_branch_name/.ann"; } 2>/dev/null || :
627 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
629 # use the merge base in case the base is ahead.
630 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
632 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
633 _result=$?
634 [ -d "$tg_cache_dir/$_branch_name" ] || mkdir -p "$tg_cache_dir/$_branch_name" 2>/dev/null
635 [ ! -d "$tg_cache_dir/$_branch_name" ] ||
636 echo $_result $_rev $_rev_base >"$tg_cache_dir/$_branch_name/.ann" 2>/dev/null || :
637 return $_result
640 non_annihilated_branches()
642 [ $# -gt 0 ] || set -- "refs/$topbases"
643 git for-each-ref --format='%(objectname) %(refname)' "$@" |
644 while read rev ref; do
645 name="${ref#refs/$topbases/}"
646 if branch_annihilated "$name" "" "$rev"; then
647 continue
649 echol "$name"
650 done
653 # Make sure our tree is clean
654 # if optional "$1" given also verify that a checkout to "$1" would succeed
655 ensure_clean_tree()
657 check_status
658 [ -z "$tg_state$git_state" ] || { do_status; exit 1; }
659 git update-index --ignore-submodules --refresh ||
660 die "the working directory has uncommitted changes (see above) - first commit or reset them"
661 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
662 die "the index has uncommited changes"
663 [ -z "$1" ] || git read-tree -n -u -m "$1" ||
664 die "git checkout \"$1\" would fail"
667 # is_sha1 REF
668 # Whether REF is a SHA1 (compared to a symbolic name).
669 is_sha1()
671 case "$1" in $octet20) return 0;; esac
672 return 1
675 # recurse_deps_internal NAME [BRANCHPATH...]
676 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
677 # followed by a 1 if the branch is "tgish" or a 0 if not
678 # followed by a 0 for a non-leaf, 1 for a leaf or 2 for annihilated tgish
679 # but missing and remotes are always "0"
680 # then the branch name followed by its depedency chain (which might be empty)
681 # An output line might look like this:
682 # 0 1 1 t/foo/leaf t/foo/int t/stage
683 # If no_remotes is non-empty, exclude remotes
684 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
685 # but the leaf info will always be 0 or 2 in that case
686 # If with_top_level is non-empty, include the top-level that's normally omitted
687 # any branch names in the space-separated recurse_deps_exclude variable
688 # are skipped (along with their dependencies)
689 recurse_deps_internal()
691 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
692 _ref_hash=
693 if ! _ref_hash="$(ref_exists_rev "refs/heads/$1")"; then
694 [ -z "$2" ] || echo "1 0 0 $*"
695 return 0
698 _is_tgish=0
699 _ref_hash_base=
700 _is_leaf=0
701 ! _ref_hash_base="$(ref_exists_rev "refs/$topbases/$1")" || _is_tgish=1
702 [ "$_is_tgish" = "0" ] || ! branch_annihilated "$1" "$_ref_hash" "$_ref_hash_base" || _is_leaf=2
703 [ -z "$recurse_preorder" -o -z "${2:-$with_top_level}" ] || echo "0 $_is_tgish $_is_leaf $*"
705 # If no_remotes is unset also check our base against remote base.
706 # Checking our head against remote head has to be done in the helper.
707 if [ "$_is_tgish" = "1" ] && [ -z "$no_remotes" ] && has_remote "${topbases#heads/}/$1"; then
708 echo "0 0 0 refs/remotes/$base_remote/${topbases#heads/}/$1 $*"
711 # if the branch was annihilated, it is considered to have no dependencies
712 [ "$_is_leaf" = "2" ] || _is_leaf=1
713 if [ "$_is_tgish" = "1" ] && [ "$_is_leaf" = "1" ]; then
714 #TODO: handle nonexisting .topdeps?
715 while read _dname && [ -n "$_dname" ]; do
716 # Avoid depedency loops
717 case " $* " in *" $_dname "*)
718 warn "dependency loop detected in branch $_dname"
719 _is_leaf=0
720 continue
721 esac
722 # Shoo shoo, leave our environment alone!
723 _dep_is_leaf=0
724 (recurse_deps_internal "$_dname" "$@") || _dep_is_leaf=$?
725 [ "$_dep_is_leaf" = "2" ] || _is_leaf=0
726 done <<-EOT
727 $(cat_deps "$1")
731 [ -n "$recurse_preorder" -o -z "${2:-$with_top_level}" ] || echo "0 $_is_tgish $_is_leaf $*"
732 return ${_is_leaf:-0}
735 # do_eval CMD
736 # helper for recurse_deps so that a return statement executed inside CMD
737 # does not return from recurse_deps. This shouldn't be necessary, but it
738 # seems that it actually is.
739 do_eval()
741 eval "$@"
744 # becomes read-only for caching purposes
745 # assigns new value to tg_read_only
746 # become_cacheable/undo_become_cacheable calls may be nested
747 become_cacheable()
749 _old_tg_read_only="$tg_read_only"
750 if [ -z "$tg_read_only" ]; then
751 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
752 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
753 tg_read_only=1
755 _my_ref_cache=
756 v_create_ref_cache _my_ref_cache
757 _my_ref_cache="${_my_ref_cache:+1}"
758 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
761 # restores tg_read_only and ref_cache to state before become_cacheable call
762 # become_cacheable/undo_bocome_cacheable calls may be nested
763 undo_become_cacheable()
765 case "$tg_read_only" in
766 "undo"[01]"-"*)
767 _suffix="${tg_read_only#undo?-}"
768 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
769 tg_read_only="$_suffix"
770 esac
773 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
774 become_non_cacheable()
776 remove_ref_cache
777 tg_read_only=
778 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
779 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
782 # call this to make sure Git will not complain about a missing user/email
783 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
784 ensure_ident_available()
786 [ -z "$TG_IDENT_CHECKED" ] || return 0
787 git var GIT_AUTHOR_IDENT >/dev/null &&
788 git var GIT_COMMITTER_IDENT >/dev/null || exit
789 TG_IDENT_CHECKED=1
790 export TG_IDENT_CHECKED
791 return 0
794 # recurse_deps CMD NAME [BRANCHPATH...]
795 # Recursively eval CMD on all dependencies of NAME.
796 # Dependencies are visited in topological order.
797 # CMD can refer to $_name for queried branch name,
798 # $_dep for dependency name,
799 # $_depchain for space-seperated branch backtrace,
800 # $_dep_missing boolean to check whether $_dep is present
801 # and the $_dep_is_tgish and $_dep_annihilated booleans.
802 # If recurse_preorder is NOT set then the $_dep_is_leaf boolean is also valid.
803 # It can modify $_ret to affect the return value
804 # of the whole function.
805 # If recurse_deps() hits missing dependencies, it will append
806 # them to space-separated $missing_deps list and skip them
807 # after calling CMD with _dep_missing set.
808 # remote dependencies are processed if no_remotes is unset.
809 # any branch names in the space-separated recurse_deps_exclude variable
810 # are skipped (along with their dependencies)
811 recurse_deps()
813 _cmd="$1"; shift
815 become_cacheable
816 _depsfile="$(get_temp tg-depsfile)"
817 recurse_deps_internal "$@" >>"$_depsfile" || :
818 undo_become_cacheable
820 _ret=0
821 while read _ismissing _istgish _isleaf _dep _name _deppath; do
822 _depchain="$_name${_deppath:+ $_deppath}"
823 _dep_is_tgish=
824 [ "$_istgish" = "0" ] || _dep_is_tgish=1
825 _dep_missing=
826 if [ "$_ismissing" != "0" ]; then
827 _dep_missing=1
828 case " $missing_deps " in *" $_dep "*);;*)
829 missing_deps="${missing_deps:+$missing_deps }$_dep"
830 esac
832 _dep_annihilated=
833 _dep_is_leaf=
834 if [ "$_isleaf" = "1" ]; then
835 _dep_is_leaf=1
836 elif [ "$_isleaf" = "2" ]; then
837 _dep_annihilated=1
839 do_eval "$_cmd"
840 done <"$_depsfile"
841 rm -f "$_depsfile"
842 return $_ret
845 find_leaves_internal()
847 if [ -n "$_dep_is_leaf" ] && [ -z "$_dep_annihilated" ] && [ -z "$_dep_missing" ]; then
848 if [ -n "$_dep_is_tgish" ]; then
849 fulldep="refs/$topbases/$_dep"
850 else
851 fulldep="refs/heads/$_dep"
853 case " $seen_leaf_refs " in *" $fulldep "*);;*)
854 seen_leaf_refs="${seen_leaf_refs:+$seen_leaf_refs }$fulldep"
855 if fullrev="$(ref_exists_rev "$fulldep")"; then
856 case " $seen_leaf_revs " in *" $fullrev "*);;*)
857 seen_leaf_revs="${seen_leaf_revs:+$seen_leaf_revs }$fullrev"
858 # See if Git knows it by another name
859 if tagname="$(git describe --exact-match "$fullrev" 2>/dev/null)" && [ -n "$tagname" ]; then
860 echo "refs/tags/$tagname"
861 else
862 echo "$fulldep"
864 esac
866 esac
870 # find_leaves NAME
871 # output (one per line) the unique leaves of NAME
872 # a leaf is either
873 # 1) a non-tgish dependency
874 # 2) the base of a tgish dependency with no non-annihilated dependencies
875 # duplicates are suppressed (by commit rev) and remotes are always ignored
876 # if a leaf has an exact tag match that will be output
877 # note that recurse_deps_exclude IS honored for this operation
878 find_leaves()
880 no_remotes=1
881 with_top_level=1
882 recurse_preorder=
883 seen_leaf_refs=
884 seen_leaf_revs=
885 recurse_deps find_leaves_internal "$1"
886 with_top_level=
889 # branch_needs_update
890 # This is a helper function for determining whether given branch
891 # is up-to-date wrt. its dependencies. It expects input as if it
892 # is called as a recurse_deps() helper.
893 # In case the branch does need update, it will echo it together
894 # with the branch backtrace on the output (see needs_update()
895 # description for details) and set $_ret to non-zero.
896 branch_needs_update()
898 if [ -n "$_dep_missing" ]; then
899 echo "! $_dep $_depchain"
900 return 0
903 if [ -n "$_dep_is_tgish" ]; then
904 branch_annihilated "$_dep" && return 0
906 if has_remote "$_dep"; then
907 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
908 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
910 # We want to sync with our base first and should output this before
911 # the remote branch, but the order does not actually matter to tg-update
912 # as it just recurses regardless, but it does matter for tg-info (which
913 # treats out-of-date bases as though they were already merged in) so
914 # we output the remote before the base.
915 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
916 echo ": $_dep $_depchain"
917 _ret=1
918 return
922 if [ -n "$_name" ]; then
923 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
924 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
925 # Some new commits in _dep
926 echo "$_dep $_depchain"
927 _ret=1
932 # needs_update NAME
933 # This function is recursive; it outputs reverse path from NAME
934 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
935 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
936 # if the head is not in sync with the <remote> branch <name>, ':' if
937 # the head is not in sync with the base (in this order of priority)
938 # or '!' if dependency is missing. Note that the remote branch, base
939 # order is reversed from the order they will actually be updated in
940 # order to accomodate tg info which treats out-of-date items that are
941 # only in the base as already being in the head for status purposes.
942 # It will also return non-zero status if NAME needs update.
943 # If needs_update() hits missing dependencies, it will append
944 # them to space-separated $missing_deps list and skip them.
945 needs_update()
947 recurse_deps branch_needs_update "$1"
950 # branch_empty NAME [-i | -w]
951 branch_empty()
953 if [ -z "$2" ]; then
954 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
955 _result=
956 _result_rev=
957 { read -r _result _result_rev <"$tg_cache_dir/$1/.mt"; } 2>/dev/null || :
958 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
959 _result=0
960 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ] || _result=$?
961 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null
962 [ ! -d "$tg_cache_dir/$1" ] || echo $_result $_rev >"$tg_cache_dir/$1/.mt"
963 return $_result
964 else
965 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ]
969 # list_deps [-i | -w] [BRANCH]
970 # -i/-w apply only to HEAD
971 list_deps()
973 head_from=
974 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
975 head="$(git symbolic-ref -q HEAD)" ||
976 head="..detached.."
978 git for-each-ref --format='%(objectname) %(refname)' "refs/$topbases${1:+/$1}" |
979 while read rev ref; do
980 name="${ref#refs/$topbases/}"
981 if branch_annihilated "$name" "" "$rev"; then
982 continue
985 from=$head_from
986 [ "refs/heads/$name" = "$head" ] ||
987 from=
988 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
989 dep_is_tgish=true
990 ref_exists "refs/$topbases/$dep" ||
991 dep_is_tgish=false
992 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
993 echo "$name $dep"
995 done
996 done
999 # checkout_symref_full [-f] FULLREF [SEED]
1000 # Just like git checkout $iowopt -b FULLREF [SEED] except that FULLREF MUST start with
1001 # refs/ and HEAD is ALWAYS set to a symref to it and [SEED] (default is FULLREF)
1002 # MUST be a committish which if present will be used instead of current FULLREF
1003 # (and FULLREF will be updated to it as well in that case)
1004 # With -f it's like git checkout $iowopt -f -b FULLREF (uses read-tree --reset instead of -m)
1005 # As an extension, FULLREF may also be a full hash to create a detached HEAD instead
1006 checkout_symref_full()
1008 _mode=-m
1009 if [ "$1" = "-f" ]; then
1010 mode="--reset"
1011 shift
1013 _ishash=
1014 case "$1" in
1015 refs/?*)
1017 $octet20)
1018 _ishash=1
1019 [ -z "$2" ] || [ "$1" = "$2" ] ||
1020 die "programmer error: invalid checkout_symref_full \"$1\" \"$2\""
1021 set -- HEAD "$1"
1024 die "programmer error: invalid checkout_symref_full \"$1\""
1026 esac
1027 _seedrev="$(git rev-parse --quiet --verify "${2:-$1}^0" --)" ||
1028 die "invalid committish: \"${2:-$1}\""
1029 # We have to do all the hard work ourselves :/
1030 # This is like git checkout -b "$1" "$2"
1031 # (or just git checkout "$1"),
1032 # but never creates a detached HEAD (unless $1 is a hash)
1033 git read-tree -u $_mode HEAD "$_seedrev" &&
1035 [ -z "$2" ] && [ "$(git cat-file -t "$1")" = "commit" ] ||
1036 git update-ref "$1" "$_seedrev"
1037 } && {
1038 [ -n "$_ishash" ] || git symbolic-ref HEAD "$1"
1042 # switch_to_base NAME [SEED]
1043 switch_to_base()
1045 checkout_symref_full "refs/$topbases/$1" "$2"
1048 # run editor with arguments
1049 # the editor setting will be cached in $tg_editor (which is eval'd)
1050 # result non-zero if editor fails or GIT_EDITOR cannot be determined
1051 run_editor()
1053 tg_editor="$GIT_EDITOR"
1054 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
1055 eval "$tg_editor" '"$@"'
1058 # Show the help messages.
1059 do_help()
1061 _www=
1062 if [ "$1" = "-w" ]; then
1063 _www=1
1064 shift
1066 if [ -z "$1" ] ; then
1067 # This is currently invoked in all kinds of circumstances,
1068 # including when the user made a usage error. Should we end up
1069 # providing more than a short help message, then we should
1070 # differentiate.
1071 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
1073 ## Build available commands list for help output
1075 cmds=
1076 sep=
1077 for cmd in "$TG_INST_CMDDIR"/tg-[!-]*; do
1078 ! [ -r "$cmd" ] && continue
1079 # strip directory part and "tg-" prefix
1080 cmd="${cmd##*/}"
1081 cmd="${cmd#tg-}"
1082 [ "$cmd" != "migrate-bases" ] || continue
1083 [ "$cmd" != "summary" ] || cmd="st[atus]|$cmd"
1084 cmds="$cmds$sep$cmd"
1085 sep="|"
1086 done
1088 echo "TopGit version $TG_VERSION - A different patch queue manager"
1089 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
1090 echo " Or: $tgname help [-w] [<command>]"
1091 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
1092 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1093 if [ -n "$_www" ]; then
1094 nohtml=
1095 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
1096 echo "${0##*/}: missing html help file:" \
1097 "$TG_INST_SHAREDIR/topgit.html" 1>&2
1098 nohtml=1
1100 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
1101 echo "${0##*/}: missing html help file:" \
1102 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
1103 nohtml=1
1105 if [ -n "$nohtml" ]; then
1106 echo "${0##*/}: use" \
1107 "\"${0##*/} help $1\" instead" 1>&2
1108 exit 1
1110 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
1111 exit
1113 output()
1115 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
1116 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
1117 echo
1118 elif [ "$1" = "help" ]; then
1119 echo "Usage: ${tgname:-tg} help [-w] [<command>]"
1120 echo
1121 elif [ "$1" = "status" ] || [ "$1" = "st" ]; then
1122 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1123 echo
1125 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
1126 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1129 page output "$1"
1130 else
1131 echo "${0##*/}: no help for $1" 1>&2
1132 do_help
1133 exit 1
1137 check_status()
1139 git_state=
1140 git_remove=
1141 if [ -e "$git_dir/MERGE_HEAD" ]; then
1142 git_state="merge"
1143 elif [ -e "$git_dir/rebase-apply/applying" ]; then
1144 git_state="am"
1145 git_remove="$git_dir/rebase-apply"
1146 elif [ -e "$git_dir/rebase-apply" ]; then
1147 git_state="rebase"
1148 git_remove="$git_dir/rebase-apply"
1149 elif [ -e "$git_dir/rebase-merge" ]; then
1150 git_state="rebase"
1151 git_remove="$git_dir/rebase-merge"
1152 elif [ -e "$git_dir/CHERRY_PICK_HEAD" ]; then
1153 git_state="cherry-pick"
1154 elif [ -e "$git_dir/BISECT_LOG" ]; then
1155 git_state="bisect"
1156 elif [ -e "$git_dir/REVERT_HEAD" ]; then
1157 git_state="revert"
1159 git_remove="${git_remove#./}"
1161 tg_state=
1162 tg_remove=
1163 if [ -e "$git_dir/tg-update" ]; then
1164 tg_state="update"
1165 tg_remove="$git_dir/tg-update"
1167 tg_remove="${tg_remove#./}"
1170 # Show status information
1171 do_status()
1173 do_status_result=0
1174 do_status_verbose=
1175 do_status_help=
1176 abbrev=refs
1177 pfx=
1178 while [ $# -gt 0 ] && case "$1" in
1179 --help|-h)
1180 do_status_help=1
1181 break;;
1182 -vv)
1183 # kludge in this common bundling option
1184 abbrev=
1185 do_status_verbose=1
1186 pfx="## "
1188 --verbose|-v)
1189 [ -z "$do_status_verbose" ] || abbrev=
1190 do_status_verbose=1
1191 pfx="## "
1193 --exit-code)
1194 do_status_result=2
1197 die "unknown status argument: $1"
1199 esac; do shift; done
1200 if [ -n "$do_status_help" ]; then
1201 echo "Usage: ${tgname:-tg} @tgsthelpusage@"
1202 return
1204 check_status
1205 symref="$(git symbolic-ref --quiet HEAD)" || :
1206 headrv="$(git rev-parse --quiet --verify ${abbrev:+--short} HEAD --)" || :
1207 if [ -n "$symref" ]; then
1208 uprefpart=
1209 if [ -n "$headrv" ]; then
1210 upref="$(git rev-parse --symbolic-full-name @{upstream} 2>/dev/null)" || :
1211 if [ -n "$upref" ]; then
1212 uprefpart=" ... ${upref#$abbrev/remotes/}"
1213 mbase="$(git merge-base HEAD "$upref")" || :
1214 ahead="$(git rev-list --count HEAD ${mbase:+--not $mbase})" || ahead=0
1215 behind="$(git rev-list --count "$upref" ${mbase:+--not $mbase})" || behind=0
1216 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart ["
1217 [ "$ahead" = "0" ] || uprefpart="${uprefpart}ahead $ahead"
1218 [ "$ahead" = "0" ] || [ "$behind" = "0" ] || uprefpart="$uprefpart, "
1219 [ "$behind" = "0" ] || uprefpart="${uprefpart}behind $behind"
1220 [ "$ahead$behind" = "00" ] || uprefpart="$uprefpart]"
1223 echol "${pfx}HEAD -> ${symref#$abbrev/heads/} [${headrv:-unborn}]$uprefpart"
1224 else
1225 echol "${pfx}HEAD -> ${headrv:-?}"
1227 if [ -n "$tg_state" ]; then
1228 extra=
1229 if [ "$tg_state" = "update" ]; then
1230 IFS= read -r uname <"$git_dir/tg-update/name" || :
1231 [ -z "$uname" ] ||
1232 extra="; currently updating branch '$uname'"
1234 echol "${pfx}tg $tg_state in progress$extra"
1235 if [ -s "$git_dir/tg-update/fullcmd" ] && [ -s "$git_dir/tg-update/names" ]; then
1236 printf "${pfx}You are currently updating as a result of:\n${pfx} "
1237 cat "$git_dir/tg-update/fullcmd"
1238 bcnt="$(( $(wc -w < "$git_dir/tg-update/names") ))"
1239 if [ $bcnt -gt 1 ]; then
1240 pcnt=0
1241 ! [ -s "$git_dir/tg-update/processed" ] ||
1242 pcnt="$(( $(wc -w < "$git_dir/tg-update/processed") ))"
1243 echo "${pfx}$pcnt of $bcnt branches updated so far"
1246 if [ "$tg_state" = "update" ]; then
1247 echol "${pfx}"' (use "tg update --continue" to continue)'
1248 echol "${pfx}"' (use "tg update --skip" to skip this branch and continue)'
1249 echol "${pfx}"' (use "tg update --stop" to stop and retain updates so far)'
1250 echol "${pfx}"' (use "tg update --abort" to restore pre-update state)'
1253 [ -z "$git_state" ] || echo "${pfx}git $git_state in progress"
1254 if [ "$git_state" = "merge" ]; then
1255 ucnt="$(( $(git ls-files --unmerged --full-name --abbrev :/ | wc -l) ))"
1256 if [ $ucnt -gt 0 ]; then
1257 echo "${pfx}"'fix conflicts and then "git commit" the result'
1258 else
1259 echo "${pfx}"'all conflicts fixed; run "git commit" to record result'
1262 if [ -z "$git_state" ]; then
1263 gsp="$(git status --porcelain 2>/dev/null)" || return 0 # bare repository
1264 gspcnt=0
1265 [ -z "$gsp" ] ||
1266 gspcnt="$(( $(printf '%s\n' "$gsp" | LC_ALL=C sed -n '/^??/!p' | wc -l) ))"
1267 untr=
1268 if [ "$gspcnt" -eq 0 ]; then
1269 [ -z "$gsp" ] || untr="; non-ignored, untracked files present"
1270 echo "${pfx}working directory is clean$untr"
1271 [ -n "$tg_state" ] || do_status_result=0
1272 else
1273 echo "${pfx}working directory is DIRTY"
1274 [ -z "$do_status_verbose" ] || git status --short --untracked-files=no
1279 ## Pager stuff
1281 # isatty FD
1282 isatty()
1284 test -t $1
1287 # pass "diff" to get pager.diff
1288 # if pager.$1 is a boolean false returns cat
1289 # if set to true or unset fails
1290 # otherwise succeeds and returns the value
1291 get_pager()
1293 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1294 [ "$_x" != "true" ] || return 1
1295 echo "cat"
1296 return 0
1298 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1299 echol "$_x"
1300 return 0
1302 return 1
1305 # setup_pager
1306 # Set TG_PAGER to a valid executable
1307 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1308 # See also the following "page" function for ease of use
1309 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1310 # Preference is (same as Git):
1311 # 1. GIT_PAGER
1312 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1313 # 3. core.pager (only if set)
1314 # 4. PAGER
1315 # 5. git var GIT_PAGER
1316 # 6. less
1317 setup_pager()
1319 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1321 emptypager=
1322 if [ -z "$TG_PAGER_IN_USE" ]; then
1323 # TG_PAGER = GIT_PAGER | PAGER | less
1324 # NOTE: GIT_PAGER='' is significant
1325 if [ -n "${GIT_PAGER+set}" ]; then
1326 TG_PAGER="$GIT_PAGER"
1327 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1328 TG_PAGER="$_dp"
1329 elif _cp="$(git config core.pager 2>/dev/null)"; then
1330 TG_PAGER="$_cp"
1331 elif [ -n "${PAGER+set}" ]; then
1332 TG_PAGER="$PAGER"
1333 else
1334 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1335 [ "$_gp" != ":" ] || _gp=
1336 TG_PAGER="${_gp:-less}"
1338 if [ -z "$TG_PAGER" ]; then
1339 emptypager=1
1340 TG_PAGER=cat
1342 else
1343 emptypager=1
1344 TG_PAGER=cat
1347 # Set pager default environment variables
1348 # see pager.c:setup_pager
1349 if [ -z "${LESS+set}" ]; then
1350 LESS="-FRX"
1351 export LESS
1353 if [ -z "${LV+set}" ]; then
1354 LV="-c"
1355 export LV
1358 # this is needed so e.g. $(git diff) will still colorize it's output if
1359 # requested in ~/.gitconfig with color.diff=auto
1360 GIT_PAGER_IN_USE=1
1361 export GIT_PAGER_IN_USE
1363 # this is needed so we don't get nested pagers
1364 TG_PAGER_IN_USE=1
1365 export TG_PAGER_IN_USE
1368 # page eval_arg [arg ...]
1370 # Calls setup_pager then evals the first argument passing it all the rest
1371 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1372 # by setup_pager (in which case the output is left as-is).
1374 # To handle arbitrary paging duties, collect lines to be paged into a
1375 # function and then call page with the function name or perhaps func_name "$@".
1377 # If no arguments at all are passed in do nothing (return with success).
1378 page()
1380 [ $# -gt 0 ] || return 0
1381 setup_pager
1382 _evalarg="$1"; shift
1383 if [ -n "$emptypager" ]; then
1384 eval "$_evalarg" '"$@"'
1385 else
1386 eval "$_evalarg" '"$@"' | eval "$TG_PAGER"
1390 # get_temp NAME [-d]
1391 # creates a new temporary file (or directory with -d) in the global
1392 # temporary directory $tg_tmp_dir with pattern prefix NAME
1393 get_temp()
1395 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1398 # automatically called by strftime
1399 # does nothing if already setup
1400 # may be called explicitly if the first call would otherwise be in a subshell
1401 # so that the setup is only done once before subshells start being spawned
1402 setup_strftime()
1404 [ -z "$strftime_is_setup" ] || return 0
1406 # date option to format raw epoch seconds values
1407 daterawopt=
1408 _testes='951807788'
1409 _testdt='2000-02-29 07:03:08 UTC'
1410 _testfm='%Y-%m-%d %H:%M:%S %Z'
1411 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1412 daterawopt='-d@'
1413 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1414 daterawopt='-r'
1416 strftime_is_setup=1
1419 # $1 => strftime format string to use
1420 # $2 => raw timestamp as seconds since epoch
1421 # $3 => optional time zone string (empty/absent for local time zone)
1422 strftime()
1424 setup_strftime
1425 if [ -n "$daterawopt" ]; then
1426 if [ -n "$3" ]; then
1427 TZ="$3" date "$daterawopt$2" "+$1"
1428 else
1429 date "$daterawopt$2" "+$1"
1431 else
1432 if [ -n "$3" ]; then
1433 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1434 else
1435 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1440 setup_git_dirs()
1442 [ -n "$git_dir" ] || git_dir="$(git rev-parse --git-dir)"
1443 if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
1444 git_dir="$(cd "$git_dir" && pwd)"
1446 if [ -z "$git_common_dir" ]; then
1447 if vcmp "$git_version" '>=' "2.5"; then
1448 # rev-parse --git-common-dir is broken and may give
1449 # an incorrect result unless the current directory is
1450 # already set to the top level directory
1451 git_common_dir="$(cd "./$(git rev-parse --show-cdup)" && cd "$(git rev-parse --git-common-dir)" && pwd)"
1452 else
1453 git_common_dir="$git_dir"
1456 [ -n "$git_dir" ] && [ -n "$git_common_dir" ] &&
1457 [ -d "$git_dir" ] && [ -d "$git_common_dir" ] || die "Not a git repository"
1458 git_hooks_dir="$git_common_dir/hooks"
1459 if vcmp "$git_version" '>=' "2.9" && gchp="$(git config --path --get core.hooksPath 2>/dev/null)" && [ -n "$gchp" ]; then
1460 case "$gchp" in
1461 /[!/]*)
1462 git_hooks_dir="$gchp"
1465 [ -n "$1" ] || warn "ignoring non-absolute core.hooksPath: $gchp"
1467 esac
1468 unset gchp
1472 basic_setup()
1474 setup_git_dirs $1
1475 [ -n "$base_remote" ] || base_remote="$(git config topgit.remote 2>/dev/null)" || :
1476 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1477 tgnosequester=
1478 [ "$tgsequester" != "false" ] || tgnosequester=1
1479 unset tgsequester
1481 # catch errors if topbases is used without being set
1482 unset tg_topbases_set
1483 topbases="programmer*:error"
1484 topbasesrx="programmer*:error}"
1485 oldbases="$topbases"
1488 ## Initial setup
1489 initial_setup()
1491 # suppress the merge log editor feature since git 1.7.10
1493 GIT_MERGE_AUTOEDIT=no
1494 export GIT_MERGE_AUTOEDIT
1496 basic_setup $1
1497 iowopt=
1498 ! vcmp "$git_version" '>=' "2.5" || iowopt="--ignore-other-worktrees"
1499 auhopt=
1500 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1501 root_dir="$(git rev-parse --show-cdup)"; root_dir="${root_dir:-.}"
1502 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1503 [ "$logrefupdates" = "true" ] || logrefupdates=
1505 # make sure root_dir doesn't end with a trailing slash.
1507 root_dir="${root_dir%/}"
1509 # make sure global cache directory exists inside GIT_DIR
1511 tg_cache_dir="$git_common_dir/tg-cache"
1512 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir"
1514 # create global temporary directories, inside GIT_DIR
1516 tg_tmp_dir=
1517 trap 'rm -rf "$tg_tmp_dir"' EXIT
1518 trap 'exit 129' HUP
1519 trap 'exit 130' INT
1520 trap 'exit 131' QUIT
1521 trap 'exit 134' ABRT
1522 trap 'exit 143' TERM
1523 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX")"
1524 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1527 set_topbases()
1529 # refer to "top-bases" in a refname with $topbases
1531 [ -z "$tg_topbases_set" ] || return 0
1533 topbases_implicit_default=1
1534 # See if topgit.top-bases is set to heads or refs
1535 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
1536 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
1537 if [ -n "$1" ]; then
1538 # never die on the hook script
1539 unset tgtb
1540 else
1541 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
1544 if [ -n "$tgtb" ]; then
1545 case "$tgtb" in
1546 heads)
1547 topbases="heads/{top-bases}"
1548 topbasesrx="heads/[{]top-bases[}]"
1549 oldbases="top-bases";;
1550 refs)
1551 topbases="top-bases"
1552 topbasesrx="top-bases"
1553 oldbases="heads/{top-bases}";;
1554 esac
1555 # MUST NOT be exported
1556 unset tgtb tg_topbases_set topbases_implicit_default
1557 tg_topbases_set=1
1558 return 0
1560 unset tgtb
1562 # check heads and top-bases and see what state the current
1563 # repository is in. remotes are ignored.
1565 hblist=" "
1566 topbases=
1567 both=
1568 newtb="heads/{top-bases}"
1569 while read -r rn && [ -n "$rn" ]; do case "$rn" in
1570 "refs/heads/{top-bases}"/*)
1571 case "$hblist" in *" ${rn#refs/$newtb/} "*)
1572 if [ "$topbases" != "heads/{top-bases}" ] && [ -n "$topbases" ]; then
1573 both=1
1574 break;
1575 else
1576 topbases="heads/{top-bases}"
1577 topbasesrx="heads/[{]top-bases[}]"
1578 oldbases="top-bases"
1580 esac;;
1581 "refs/top-bases"/*)
1582 case "$hblist" in *" ${rn#refs/top-bases/} "*)
1583 if [ "$topbases" != "top-bases" ] && [ -n "$topbases" ]; then
1584 both=1
1585 break;
1586 else
1587 topbases="top-bases"
1588 topbasesrx="top-bases"
1589 oldbases="heads/{top-bases}"
1591 esac;;
1592 "refs/heads"/*)
1593 hblist="$hblist${rn#refs/heads/} ";;
1594 esac; done <<-EOT
1595 $(git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases" 2>/dev/null)
1597 if [ -n "$both" ]; then
1598 if [ -n "$1" ]; then
1599 # hook script always prefers newer without complaint
1600 topbases="heads/{top-bases}"
1601 topbasesrx="heads/[{]top-bases[}]"
1602 oldbases="top-bases"
1603 else
1604 # Complain and die
1605 err "repository contains existing TopGit branches"
1606 err "but some use refs/top-bases/... for the base"
1607 err "and some use refs/heads/{top-bases}/... for the base"
1608 err "with the latter being the new, preferred location"
1609 err "set \"topgit.top-bases\" to either \"heads\" to use"
1610 err "the new heads/{top-bases} location or \"refs\" to use"
1611 err "the old top-bases location."
1612 err "(the tg migrate-bases command can also resolve this issue)"
1613 die "schizophrenic repository requires topgit.top-bases setting"
1615 elif [ -n "$topbases" ]; then
1616 unset topbases_implicit_default
1619 [ -n "$topbases" ] || {
1620 # default is still top-bases for now
1621 topbases="top-bases"
1622 topbasesrx="top-bases"
1623 oldbases="heads/{top-bases}"
1625 # MUST NOT be exported
1626 unset hblist both newtb rn tg_topases_set
1627 tg_topbases_set=1
1628 return 0
1631 # init_reflog "ref"
1632 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
1633 # an empty log file to exist so that ref changes will be logged
1634 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
1635 # However, if "$1" is "refs/tgstash" then always make the reflog
1636 # The only ref not under refs/ that Git will write a reflog for is HEAD;
1637 # no matter what, it will NOT update a reflog for any other bare refs so
1638 # just quietly succeed when passed TG_STASH without doing anything.
1639 init_reflog()
1641 [ -n "$1" ] && [ "$1" != "TG_STASH" ] || return 0
1642 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
1643 case "$1" in refs/heads/*|HEAD) return 0;; refs/*[!/]);; *) return 1; esac
1644 mkdir -p "$git_common_dir/logs/${1%/*}" 2>/dev/null || :
1645 { >>"$git_common_dir/logs/$1" || :; } 2>/dev/null
1648 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
1649 # a symbolic link. The directory part must exist, but the basename need not.
1650 v_get_abs_path()
1652 [ -n "$1" ] && [ -n "$2" ] || return 1
1653 set -- "$1" "$2" "${2%/}"
1654 case "$3" in
1655 */*) set -- "$1" "$2" "${3%/*}";;
1656 * ) set -- "$1" "$2" ".";;
1657 esac
1658 [ -d "$3" ] || return 1
1659 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}"'
1662 ## Startup
1664 : "${TG_INST_CMDDIR:=@cmddir@}"
1665 : "${TG_INST_SHAREDIR:=@sharedir@}"
1666 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1668 [ -d "$TG_INST_CMDDIR" ] ||
1669 die "No command directory: '$TG_INST_CMDDIR'"
1671 if [ -n "$tg__include" ]; then
1673 # We were sourced from another script for our utility functions;
1674 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1675 # work as expected in every shell. See http://bugs.debian.org/516188
1677 # ensure setup happens
1679 initial_setup 1
1680 set_topbases 1
1682 else
1684 set -e
1686 tg="$0"
1687 tgdir="${tg%/}"
1688 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
1689 tgdir="${tgdir%/*}/"
1690 tgname="${tg##*/}"
1691 [ "$0" != "$tgname" ] || tgdir=""
1693 # If tg contains a '/' but does not start with one then replace it with an absolute path
1695 case "$0" in /*) ;; */*)
1696 tgdir="$(cd "${0%/*}" && pwd -P)/"
1697 tg="$tgdir$tgname"
1698 esac
1700 # If the tg in the PATH is the same as "$tg" just display the basename
1701 # tgdisplay will include any explicit -C <dir> option whereas tg will not
1703 tgdisplaydir="$tgdir"
1704 tgdisplay="$tg"
1706 v_get_abs_path _tgabs "$tg" &&
1707 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
1708 [ "$_tgabs" = "$_tgnameabs" ]
1709 then
1710 tgdisplaydir=""
1711 tgdisplay="$tgname"
1713 unset _tgabs _tgnameabs
1715 explicit_remote=
1716 explicit_dir=
1717 gitcdopt=
1718 noremote=
1720 cmd=
1721 while :; do case "$1" in
1723 help|--help|-h)
1724 cmd=help
1725 shift
1726 break;;
1728 status|--status)
1729 cmd=status
1730 shift
1731 break;;
1733 --hooks-path)
1734 cmd=hooks-path
1735 shift
1736 break;;
1738 --top-bases)
1739 cmd=top-bases
1740 shift
1741 break;;
1744 shift
1745 if [ -z "$1" ]; then
1746 echo "Option -r requires an argument." >&2
1747 do_help
1748 exit 1
1750 unset noremote
1751 base_remote="$1"
1752 explicit_remote="$base_remote"
1753 tg="$tgdir$tgname -r $explicit_remote"
1754 tgdisplay="$tgdisplaydir$tgname"
1755 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1756 tgdisplay="$tgdisplay -r $explicit_remote"
1757 shift;;
1760 unset base_remote explicit_remote
1761 noremote=1
1762 tg="$tgdir$tgname -u"
1763 tgdisplay="$tgdisplaydir$tgname"
1764 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1765 tgdisplay="$tgdisplay -u"
1766 shift;;
1769 shift
1770 if [ -z "$1" ]; then
1771 echo "Option -C requires an argument." >&2
1772 do_help
1773 exit 1
1775 cd "$1"
1776 unset GIT_DIR GIT_COMMON_DIR
1777 explicit_dir="$1"
1778 gitcdopt=" -C \"$explicit_dir\""
1779 tg="$tgdir$tgname"
1780 tgdisplay="$tgdisplaydir$tgname -C \"$explicit_dir\""
1781 [ -z "$explicit_remote" ] || tg="$tg -r $explicit_remote"
1782 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
1783 [ -z "$noremote" ] || tg="$tg -u"
1784 [ -z "$noremote" ] || tg="$tgdisplay -u"
1785 shift;;
1788 shift
1789 if [ -z "$1" ]; then
1790 echo "Option -c requires an argument." >&2
1791 do_help
1792 exit 1
1794 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
1795 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
1796 export GIT_CONFIG_PARAMETERS
1797 shift;;
1800 shift
1801 break;;
1804 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
1805 do_help
1806 exit 1;;
1809 break;;
1811 esac; done
1813 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
1815 ## Dispatch
1817 [ -n "$cmd" ] || { do_help; exit 1; }
1819 case "$cmd" in
1821 help)
1822 do_help "$@"
1823 exit 0;;
1825 status|st)
1826 unset base_remote
1827 basic_setup
1828 set_topbases
1829 do_status "$@"
1830 exit ${do_status_result:-0};;
1832 hooks-path)
1833 # Internal command
1834 echol "$TG_INST_HOOKSDIR";;
1836 top-bases)
1837 # Maintenance command
1838 ! git rev-parse --git-dir >/dev/null 2>&1 || setup_git_dirs
1839 set_topbases
1840 echol "refs/$topbases";;
1843 isutil=
1844 case "$cmd" in index-merge-one-file)
1845 isutil="-"
1846 esac
1847 [ -r "$TG_INST_CMDDIR"/tg-$isutil$cmd ] || {
1848 looplevel="$TG_ALIAS_DEPTH"
1849 [ "${looplevel#[1-9]}" != "$looplevel" ] &&
1850 [ "${looplevel%%[!0-9]*}" = "$looplevel" ] ||
1851 looplevel=0
1852 tgalias="$(git config "topgit.alias.$cmd" 2>/dev/null)" || :
1853 [ -n "$tgalias" ] || {
1854 echo "Unknown subcommand: $cmd" >&2
1855 do_help
1856 exit 1
1858 looplevel=$(( $looplevel + 1 ))
1859 [ $looplevel -le 10 ] || die "topgit.alias nesting level 10 exceeded"
1860 TG_ALIAS_DEPTH="$looplevel"
1861 export TG_ALIAS_DEPTH
1862 if [ "!${tgalias#?}" = "$tgalias" ]; then
1863 unset GIT_PREFIX
1864 if pfx="$(git rev-parse --show-prefix 2>/dev/null)"; then
1865 GIT_PREFIX="$pfx"
1866 export GIT_PREFIX
1868 cd "./$(git rev-parse --show-cdup 2>/dev/null)"
1869 exec @SHELL_PATH@ -c "${tgalias#?} \"\$@\"" @SHELL_PATH@ "$@"
1870 else
1871 eval 'exec "$tgbin"' "$tgalias" '"$@"'
1873 die "alias execution failed for: $tgalias"
1875 unset TG_ALIAS_DEPTH
1877 showing_help=
1878 if [ "$*" = "-h" ] || [ "$*" = "--help" ]; then
1879 showing_help=1
1882 [ -n "$showing_help" ] || initial_setup
1883 [ -z "$noremote" ] || unset base_remote
1885 nomergesetup="$showing_help"
1886 case "$cmd" in base|contains|info|log|rebase|revert|summary|tag)
1887 # avoid merge setup where not necessary
1889 nomergesetup=1
1890 esac
1892 if [ -z "$nomergesetup" ]; then
1893 # make sure merging the .top* files will always behave sanely
1895 setup_ours
1896 setup_hook "pre-commit"
1899 # everything but rebase needs topbases set
1900 carefully="$showing_help"
1901 [ "$cmd" != "migrate-bases" ] || carefully=1
1902 [ "$cmd" = "rebase" ] || set_topbases $carefully
1904 _use_ref_cache=
1905 tg_read_only=1
1906 case "$cmd$showing_help" in
1907 contains|export|info|summary|tag)
1908 _use_ref_cache=1;;
1909 annihilate|create|delete|depend|import|update)
1910 tg_read_only=;;
1911 esac
1912 [ -z "$_use_ref_cache" ] || v_create_ref_cache
1914 fullcmd="${tgname:-tg} $cmd $*"
1915 . "$TG_INST_CMDDIR"/tg-$isutil$cmd;;
1916 esac