tg-update.sh: reduce number of checkouts slightly
[topgit/pro.git] / tg.sh
blob5a8a6cbaad15ca9622233c7c0d221a147775fef4
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.4
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"
21 ## Auxiliary functions
23 # Preserves current $? value while triggering a non-zero set -e exit if active
24 # This works even for shells that sometimes fail to correctly trigger a -e exit
25 check_exit_code()
27 return $?
30 # This is the POSIX equivalent of which
31 cmd_path()
33 { "unset" -f command unset unalias "$1"; } >/dev/null 2>&1 || :
34 { "unalias" -a; } >/dev/null 2>&1 || :
35 command -v "$1"
38 # Output arguments without any possible interpretation
39 # (Avoid misinterpretation of '\' characters or leading "-n", "-E" or "-e")
40 echol()
42 printf '%s\n' "$*"
45 info()
47 echol "${TG_RECURSIVE}${tgname:-tg}: $*"
50 warn()
52 info "warning: $*" >&2
55 err()
57 info "error: $*" >&2
60 die()
62 info "fatal: $*" >&2
63 exit 1
66 # shift off first arg then return "$*" properly quoted in single-quotes
67 # if $1 was '' output goes to stdout otherwise it's assigned to $1
68 # the final \n, if any, is omitted from the result but any others are included
69 v_quotearg()
71 _quotearg_v="$1"
72 shift
73 set -- "$_quotearg_v" \
74 "sed \"s/'/'\\\\\\''/g;1s/^/'/;\\\$s/\\\$/'/;s/'''/'/g;1s/^''\\(.\\)/\\1/\"" "$*"
75 unset _quotearg_v
76 if [ -z "$3" ]; then
77 if [ -z "$1" ]; then
78 echo "''"
79 else
80 eval "$1=\"''\""
82 else
83 if [ -z "$1" ]; then
84 printf "%s$4" "$3" | eval "$2"
85 else
86 eval "$1="'"$(printf "%s$4" "$3" | eval "$2")"'
91 # same as v_quotearg except there's no extra $1 so output always goes to stdout
92 quotearg()
94 v_quotearg '' "$@"
97 vcmp()
99 # Compare $1 to $3 each of which must match ^[^0-9]*\d*(\.\d*)*.*$
100 # where only the "\d*" parts in the regex participate in the comparison
101 # Since EVERY string matches that regex this function is easy to use
102 # An empty string ('') for $1 or $3 or any "\d*" part is treated as 0
103 # $2 is a compare op '<', '<=', '=', '==', '!=', '>=', '>'
104 # Return code is 0 for true, 1 for false (or unknown compare op)
105 # There is NO difference in behavior between '=' and '=='
106 # Note that "vcmp 1.8 == 1.8.0.0.0.0" correctly returns 0
107 set -- "$1" "$2" "$3" "${1%%[0-9]*}" "${3%%[0-9]*}"
108 set -- "${1#"$4"}" "$2" "${3#"$5"}"
109 set -- "${1%%[!0-9.]*}" "$2" "${3%%[!0-9.]*}"
110 while
111 vcmp_a_="${1%%.*}"
112 vcmp_b_="${3%%.*}"
113 [ "z$vcmp_a_" != "z" -o "z$vcmp_b_" != "z" ]
115 if [ "${vcmp_a_:-0}" -lt "${vcmp_b_:-0}" ]; then
116 unset vcmp_a_ vcmp_b_
117 case "$2" in "<"|"<="|"!=") return 0; esac
118 return 1
119 elif [ "${vcmp_a_:-0}" -gt "${vcmp_b_:-0}" ]; then
120 unset vcmp_a_ vcmp_b_
121 case "$2" in ">"|">="|"!=") return 0; esac
122 return 1;
124 vcmp_a_="${1#$vcmp_a_}"
125 vcmp_b_="${3#$vcmp_b_}"
126 set -- "${vcmp_a_#.}" "$2" "${vcmp_b_#.}"
127 done
128 unset vcmp_a_ vcmp_b_
129 case "$2" in "="|"=="|"<="|">=") return 0; esac
130 return 1
133 precheck() {
134 if ! git_version="$(git version)"; then
135 die "'git version' failed"
137 case "$git_version" in [Gg]"it version "*);;*)
138 die "'git version' output does not start with 'git version '"
139 esac
141 vcmp "$git_version" '>=' "$GIT_MINIMUM_VERSION" ||
142 die "git version >= $GIT_MINIMUM_VERSION required but found $git_version instead"
145 case "$1" in version|--version|-V)
146 echo "TopGit version $TG_VERSION"
147 exit 0
148 esac
150 precheck
151 [ "$1" = "precheck" ] && exit 0
154 cat_depsmsg_internal()
156 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
157 if [ -s "$tg_cache_dir/$1/.$2" ]; then
158 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
159 _line=
160 while IFS= read -r _line || [ -n "$_line" ]; do
161 printf '%s\n' "$_line"
162 done
163 return 0
164 fi <"$tg_cache_dir/$1/.$2"
166 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null || :
167 if [ -d "$tg_cache_dir/$1" ]; then
168 printf '%s\n' "$_rev" >"$tg_cache_dir/$1/.$2"
169 _line=
170 git cat-file blob "$_rev:.$2" 2>/dev/null |
171 while IFS= read -r _line || [ -n "$_line" ]; do
172 printf '%s\n' "$_line" >&3
173 printf '%s\n' "$_line"
174 done 3>>"$tg_cache_dir/$1/.$2"
175 else
176 git cat-file blob "$_rev:.$2" 2>/dev/null
180 # cat_deps BRANCHNAME
181 # Caches result
182 cat_deps()
184 cat_depsmsg_internal "$1" topdeps
187 # cat_msg BRANCHNAME
188 # Caches result
189 cat_msg()
191 cat_depsmsg_internal "$1" topmsg
194 # cat_file TOPIC:PATH [FROM]
195 # cat the file PATH from branch TOPIC when FROM is empty.
196 # FROM can be -i or -w, than the file will be from the index or worktree,
197 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
198 cat_file()
200 path="$1"
201 case "$2" in
203 cat "$root_dir/${path#*:}"
206 # ':file' means cat from index
207 git cat-file blob ":${path#*:}"
210 case "$path" in
211 refs/heads/*:.topdeps)
212 _temp="${path%:.topdeps}"
213 cat_deps "${_temp#refs/heads/}"
215 refs/heads/*:.topmsg)
216 _temp="${path%:.topmsg}"
217 cat_msg "${_temp#refs/heads/}"
220 git cat-file blob "$path"
222 esac
225 die "Wrong argument to cat_file: '$2'"
227 esac
230 # get tree for the committed topic
231 get_tree_()
233 echo "refs/heads/$1"
236 # get tree for the base
237 get_tree_b()
239 echo "refs/$topbases/$1"
242 # get tree for the index
243 get_tree_i()
245 git write-tree
248 # get tree for the worktree
249 get_tree_w()
251 i_tree=$(git write-tree)
253 # the file for --index-output needs to sit next to the
254 # current index file
255 cd "$root_dir"
256 : ${GIT_INDEX_FILE:="$git_dir/index"}
257 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
258 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
259 GIT_INDEX_FILE="$TMP_INDEX" &&
260 export GIT_INDEX_FILE &&
261 git diff --name-only -z HEAD |
262 git update-index -z --add --remove --stdin &&
263 git write-tree &&
264 rm -f "$TMP_INDEX"
268 # strip_ref "$(git symbolic-ref HEAD)"
269 # Output will have a leading refs/heads/ or refs/$topbases/ stripped if present
270 strip_ref()
272 case "$1" in
273 refs/"$topbases"/*)
274 echol "${1#refs/$topbases/}"
276 refs/heads/*)
277 echol "${1#refs/heads/}"
280 echol "$1"
281 esac
284 # pretty_tree NAME [-b | -i | -w]
285 # Output tree ID of a cleaned-up tree without tg's artifacts.
286 # NAME will be ignored for -i and -w, but needs to be present
287 pretty_tree()
289 name=$1
290 source=${2#?}
291 git ls-tree --full-tree "$(get_tree_$source "$name")" |
292 LC_ALL=C sed -ne '/ \.top.*$/!p' |
293 git mktree
296 # return an empty-tree root commit -- date is either passed in or current
297 # If passed in "$*" must be epochsecs followed by optional hhmm offset (+0000 default)
298 # An invalid secs causes the current date to be used, an invalid zone offset
299 # causes +0000 to be used
300 make_empty_commit()
302 # the empty tree is guaranteed to always be there even in a repo with
303 # zero objects, but for completeness we force it to exist as a real object
304 SECS=
305 read -r SECS ZONE JUNK <<-EOT || :
308 case "$SECS" in *[!0-9]*) SECS=; esac
309 if [ -z "$SECS" ]; then
310 MTDATE="$(date '+%s %z')"
311 else
312 case "$ZONE" in
313 -[01][0-9][0-5][0-9]|+[01][0-9][0-5][0-9])
315 [01][0-9][0-5][0-9])
316 ZONE="+$ZONE"
319 ZONE="+0000"
320 esac
321 MTDATE="$SECS $ZONE"
323 EMPTYID="- <-> $MTDATE"
324 EMPTYTREE="$(git hash-object -t tree -w --stdin < /dev/null)"
325 printf '%s\n' "tree $EMPTYTREE" "author $EMPTYID" "committer $EMPTYID" '' |
326 git hash-object -t commit -w --stdin
329 # setup_hook NAME
330 setup_hook()
332 tgname="${0##*/}"
333 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
334 if [ -f "$git_dir/hooks/$1" ] && LC_ALL=C grep -Fq "$hook_call" "$git_dir/hooks/$1"; then
335 # Another job well done!
336 return
338 # Prepare incantation
339 hook_chain=
340 if [ -s "$git_dir/hooks/$1" -a -x "$git_dir/hooks/$1" ]; then
341 hook_call="$hook_call"' || exit $?'
342 if [ -L "$git_dir/hooks/$1" ] || ! LC_ALL=C sed -n 1p <"$git_dir/hooks/$1" | LC_ALL=C grep -Fqx "#!@SHELL_PATH@"; then
343 chain_num=
344 while [ -e "$git_dir/hooks/$1-chain$chain_num" ]; do
345 chain_num=$(( $chain_num + 1 ))
346 done
347 mv -f "$git_dir/hooks/$1" "$git_dir/hooks/$1-chain$chain_num"
348 hook_chain=1
350 else
351 hook_call="exec $hook_call"
352 [ -d "$git_dir/hooks" ] || mkdir "$git_dir/hooks" || :
354 # Don't call hook if tg is not installed
355 hook_call="if command -v \"$tgname\" >/dev/null 2>&1; then $hook_call; fi"
356 # Insert call into the hook
358 echol "#!@SHELL_PATH@"
359 echol "$hook_call"
360 if [ -n "$hook_chain" ]; then
361 echol "exec \"\$0-chain$chain_num\" \"\$@\""
362 else
363 [ ! -s "$git_dir/hooks/$1" ] || cat "$git_dir/hooks/$1"
365 } >"$git_dir/hooks/$1+"
366 chmod a+x "$git_dir/hooks/$1+"
367 mv "$git_dir/hooks/$1+" "$git_dir/hooks/$1"
370 # setup_ours (no arguments)
371 setup_ours()
373 if [ ! -s "$git_dir/info/attributes" ] || ! grep -q topmsg "$git_dir/info/attributes"; then
374 [ -d "$git_dir/info" ] || mkdir "$git_dir/info"
376 echo ".topmsg merge=ours"
377 echo ".topdeps merge=ours"
378 } >>"$git_dir/info/attributes"
380 if ! git config merge.ours.driver >/dev/null; then
381 git config merge.ours.name '"always keep ours" merge driver'
382 git config merge.ours.driver 'touch %A'
386 # measure_branch NAME [BASE] [EXTRAHEAD...]
387 measure_branch()
389 _bname="$1"; _base="$2"
390 shift; shift
391 [ -n "$_base" ] || _base="refs/$topbases/$(strip_ref "$_bname")"
392 # The caller should've verified $name is valid
393 _commits="$(git rev-list --count "$_bname" "$@" ^"$_base" --)"
394 _nmcommits="$(git rev-list --count --no-merges "$_bname" "$@" ^"$_base" --)"
395 if [ $_commits -ne 1 ]; then
396 _suffix="commits"
397 else
398 _suffix="commit"
400 echo "$_commits/$_nmcommits $_suffix"
403 # branch_contains B1 B2
404 # Whether B1 is a superset of B2.
405 branch_contains()
407 _revb1="$(ref_exists_rev "$1")" || return 0
408 _revb2="$(ref_exists_rev "$2")" || return 0
409 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
410 if read _result _rev_matchb1 _rev_matchb2 &&
411 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
412 return $_result
413 fi <"$tg_cache_dir/$1/.bc/$2/.d"
415 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
416 _result=0
417 [ "$(git rev-list --count --max-count=1 "$_revb2" --not "$_revb1" --)" = "0" ] || _result=1
418 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
419 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
421 return $_result
424 create_ref_dirs()
426 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
427 sed -e 's/ .*$//;'"s~^~$tg_tmp_dir/cached/~" <"$tg_ref_cache" | xargs mkdir -p
428 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
431 # If the first argument is non-empty, stores "1" there if this call created the cache
432 v_create_ref_cache()
434 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
435 _remotespec=
436 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
437 [ -z "$1" ] || eval "$1=1"
438 git for-each-ref --format='%(refname) %(objectname)' \
439 refs/heads "refs/$topbases" $_remotespec >"$tg_ref_cache"
440 create_ref_dirs
443 remove_ref_cache()
445 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
446 >"$tg_ref_cache"
449 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
450 rev_parse()
452 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
453 LC_ALL=C awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
454 else
455 [ -z "$tg_ref_cache_only" ] || return 1
456 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
460 # ref_exists_rev REF
461 # Whether REF is a valid ref name
462 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
463 # or, if $base_remote is set, refs/remotes/$base_remote/
464 # Caches result if $tg_read_only and outputs HASH on success
465 ref_exists_rev()
467 case "$1" in
468 refs/*)
470 $octet20)
471 printf '%s' "$1"
472 return;;
474 die "ref_exists_rev requires fully-qualified ref name"
475 esac
476 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
477 _result=
478 _result_rev=
479 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
480 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
481 _result_rev="$(rev_parse "$1")"
482 _result=$?
483 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
484 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
485 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
486 printf '%s' "$_result_rev"
487 return $_result
490 # Same as ref_exists_rev but output is abbreviated hash
491 # Optional second argument defaults to --short but may be any --short=.../--no-short option
492 ref_exists_rev_short()
494 case "$1" in
495 refs/*)
497 $octet20)
500 die "ref_exists_rev_short requires fully-qualified ref name"
501 esac
502 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify ${2:---short} "$1^0" -- 2>/dev/null; return; }
503 _result=
504 _result_rev=
505 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
506 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
507 _result_rev="$(rev_parse "$1")"
508 _result=$?
509 if [ $_result -eq 0 ]; then
510 _result_rev="$(git rev-parse --verify ${2:---short} --quiet "$_result_rev" --)"
511 _result=$?
513 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
514 [ ! -d "$tg_tmp_dir/cached/$1" ] ||
515 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
516 printf '%s' "$_result_rev"
517 return $_result
520 # ref_exists REF
521 # Whether REF is a valid ref name
522 # REF must be fully qualified and start with refs/heads/, refs/$topbases/
523 # or, if $base_remote is set, refs/remotes/$base_remote/
524 # Caches result
525 ref_exists()
527 ref_exists_rev "$1" >/dev/null
530 # rev_parse_tree REF
531 # Runs git rev-parse REF^{tree}
532 # Caches result if $tg_read_only
533 rev_parse_tree()
535 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
536 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
537 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
538 printf '%s\n' "$_result"
539 return 0
541 return 1
543 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
544 if [ -d "$tg_tmp_dir/cached/$1" ]; then
545 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
546 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
547 printf '%s\n' "$_result"
548 return 0
550 return 1
552 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
555 # has_remote BRANCH
556 # Whether BRANCH has a remote equivalent (accepts $topbases/ too)
557 has_remote()
559 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
562 # Return the verified TopGit branch name or die with an error.
563 # As a convenience, if HEAD is given and HEAD is a symbolic ref to
564 # refs/heads/... then ... will be verified instead.
565 # if "$2" = "-f" (for fail) then return an error rather than dying.
566 verify_topgit_branch()
568 case "$1" in
569 refs/"$topbases"/*)
570 _verifyname="${1#refs/$topbases/}"
572 refs/heads/*)
573 _verifyname="${1#refs/heads/}"
575 HEAD)
576 _verifyname="$(git symbolic-ref HEAD 2>/dev/null)" || :
577 [ -n "$_verifyname" -o "$2" = "-f" ] || die "HEAD is not a symbolic ref"
578 case "$_verifyname" in refs/heads/*);;*)
579 [ "$2" != "-f" ] || return 1
580 die "HEAD is not a symbolic ref to the refs/heads namespace"
581 esac
582 _verifyname="${_verifyname#refs/heads/}"
585 _verifyname="$1"
587 esac
588 if ! ref_exists "refs/heads/$_verifyname"; then
589 [ "$2" != "-f" ] || return 1
590 die "no such branch: $_verifyname"
592 if ! ref_exists "refs/$topbases/$_verifyname"; then
593 [ "$2" != "-f" ] || return 1
594 die "not a TopGit-controlled branch: $_verifyname"
596 printf '%s' "$_verifyname"
599 # Caches result
600 # $1 = branch name (i.e. "t/foo/bar")
601 # $2 = optional result of rev-parse "refs/heads/$1"
602 # $3 = optional result of rev-parse "refs/$topbases/$1"
603 branch_annihilated()
605 _branch_name="$1"
606 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
607 _rev_base="${3:-$(ref_exists_rev "refs/$topbases/$_branch_name")}"
609 _result=
610 _result_rev=
611 _result_rev_base=
612 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/$_branch_name/.ann"; } 2>/dev/null || :
613 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
615 # use the merge base in case the base is ahead.
616 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
618 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
619 _result=$?
620 [ -d "$tg_cache_dir/$_branch_name" ] || mkdir -p "$tg_cache_dir/$_branch_name" 2>/dev/null
621 [ ! -d "$tg_cache_dir/$_branch_name" ] ||
622 echo $_result $_rev $_rev_base >"$tg_cache_dir/$_branch_name/.ann" 2>/dev/null || :
623 return $_result
626 non_annihilated_branches()
628 [ $# -gt 0 ] || set -- "refs/$topbases"
629 git for-each-ref --format='%(objectname) %(refname)' "$@" |
630 while read rev ref; do
631 name="${ref#refs/$topbases/}"
632 if branch_annihilated "$name" "" "$rev"; then
633 continue
635 echol "$name"
636 done
639 # Make sure our tree is clean
640 ensure_clean_tree()
642 git update-index --ignore-submodules --refresh ||
643 die "the working directory has uncommitted changes (see above) - first commit or reset them"
644 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
645 die "the index has uncommited changes"
648 # is_sha1 REF
649 # Whether REF is a SHA1 (compared to a symbolic name).
650 is_sha1()
652 case "$1" in $octet20) return 0;; esac
653 return 1
656 # recurse_deps_internal NAME [BRANCHPATH...]
657 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
658 # followed by a 1 if the branch is "tgish" or a 0 if not
659 # then the branch name followed by its depedency chain (which might be empty)
660 # An output line might look like this:
661 # 0 1 t/foo/leaf t/foo/int t/stage
662 # If no_remotes is non-empty, exclude remotes
663 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
664 # any branch names in the space-separated recurse_deps_exclude variable
665 # are skipped (along with their dependencies)
666 recurse_deps_internal()
668 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
669 _ref_hash=
670 if ! _ref_hash="$(ref_exists_rev "refs/heads/$1")"; then
671 [ -z "$2" ] || echo "1 0 $*"
672 return
675 _is_tgish=0
676 _ref_hash_base=
677 ! _ref_hash_base="$(ref_exists_rev "refs/$topbases/$1")" || _is_tgish=1
678 [ -z "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
680 # If no_remotes is unset also check our base against remote base.
681 # Checking our head against remote head has to be done in the helper.
682 if [ -n "$_is_tgish" -a -z "$no_remotes" ] && has_remote "$topbases/$1"; then
683 echo "0 0 refs/remotes/$base_remote/$topbases/$1 $*"
686 # if the branch was annihilated, it is considered to have no dependencies
687 if [ -n "$_is_tgish" ] && ! branch_annihilated "$1" "$_ref_hash" "$_ref_hash_base"; then
688 #TODO: handle nonexisting .topdeps?
689 cat_deps "$1" |
690 while read _dname; do
691 # Avoid depedency loops
692 case " $* " in *" $_dname "*)
693 warn "dependency loop detected in branch $_dname"
694 continue
695 esac
696 # Shoo shoo, leave our environment alone!
697 (recurse_deps_internal "$_dname" "$@")
698 done
701 [ -n "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
704 # do_eval CMD
705 # helper for recurse_deps so that a return statement executed inside CMD
706 # does not return from recurse_deps. This shouldn't be necessary, but it
707 # seems that it actually is.
708 do_eval()
710 eval "$@"
713 # becomes read-only for caching purposes
714 # assigns new value to tg_read_only
715 # become_cacheable/undo_become_cacheable calls may be nested
716 become_cacheable()
718 _old_tg_read_only="$tg_read_only"
719 if [ -z "$tg_read_only" ]; then
720 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
721 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
722 tg_read_only=1
724 _my_ref_cache=
725 v_create_ref_cache _my_ref_cache
726 _my_ref_cache="${_my_ref_cache:+1}"
727 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
730 # restores tg_read_only and ref_cache to state before become_cacheable call
731 # become_cacheable/undo_bocome_cacheable calls may be nested
732 undo_become_cacheable()
734 case "$tg_read_only" in
735 "undo"[01]"-"*)
736 _suffix="${tg_read_only#undo?-}"
737 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
738 tg_read_only="$_suffix"
739 esac
742 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
743 become_non_cacheable()
745 remove_ref_cache
746 tg_read_only=
747 ! [ -e "$tg_tmp_dir/cached" ] && ! [ -e "$tg_tmp_dir/tg~ref-dirs-created" ] ||
748 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
751 # call this to make sure Git will not complain about a missing user/email
752 # result is cached in TG_IDENT_CHECKED and a non-empty value suppresses the check
753 ensure_ident_available()
755 [ -z "$TG_IDENT_CHECKED" ] || return 0
756 git var GIT_AUTHOR_IDENT >/dev/null &&
757 git var GIT_COMMITTER_IDENT >/dev/null || exit
758 TG_IDENT_CHECKED=1
759 export TG_IDENT_CHECKED
760 return 0
763 # recurse_deps CMD NAME [BRANCHPATH...]
764 # Recursively eval CMD on all dependencies of NAME.
765 # Dependencies are visited in topological order.
766 # CMD can refer to $_name for queried branch name,
767 # $_dep for dependency name,
768 # $_depchain for space-seperated branch backtrace,
769 # $_dep_missing boolean to check whether $_dep is present
770 # and the $_dep_is_tgish boolean.
771 # It can modify $_ret to affect the return value
772 # of the whole function.
773 # If recurse_deps() hits missing dependencies, it will append
774 # them to space-separated $missing_deps list and skip them
775 # after calling CMD with _dep_missing set.
776 # remote dependencies are processed if no_remotes is unset.
777 # any branch names in the space-separated recurse_deps_exclude variable
778 # are skipped (along with their dependencies)
779 recurse_deps()
781 _cmd="$1"; shift
783 become_cacheable
784 _depsfile="$(get_temp tg-depsfile)"
785 recurse_deps_internal "$@" >>"$_depsfile"
786 undo_become_cacheable
788 _ret=0
789 while read _ismissing _istgish _dep _name _deppath; do
790 _depchain="$_name${_deppath:+ $_deppath}"
791 _dep_is_tgish=
792 [ "$_istgish" = "0" ] || _dep_is_tgish=1
793 _dep_missing=
794 if [ "$_ismissing" != "0" ]; then
795 _dep_missing=1
796 case " $missing_deps " in *" $_dep "*);;*)
797 missing_deps="${missing_deps:+$missing_deps }$_dep"
798 esac
800 do_eval "$_cmd"
801 done <"$_depsfile"
802 rm -f "$_depsfile"
803 return $_ret
806 # branch_needs_update
807 # This is a helper function for determining whether given branch
808 # is up-to-date wrt. its dependencies. It expects input as if it
809 # is called as a recurse_deps() helper.
810 # In case the branch does need update, it will echo it together
811 # with the branch backtrace on the output (see needs_update()
812 # description for details) and set $_ret to non-zero.
813 branch_needs_update()
815 if [ -n "$_dep_missing" ]; then
816 echo "! $_dep $_depchain"
817 return 0
820 if [ -n "$_dep_is_tgish" ]; then
821 branch_annihilated "$_dep" && return 0
823 if has_remote "$_dep"; then
824 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" ||
825 echo "refs/remotes/$base_remote/$_dep $_dep $_depchain"
827 # We want to sync with our base first and should output this before
828 # the remote branch, but the order does not actually matter to tg-update
829 # as it just recurses regardless, but it does matter for tg-info (which
830 # treats out-of-date bases as though they were already merged in) so
831 # we output the remote before the base.
832 branch_contains "refs/heads/$_dep" "refs/$topbases/$_dep" || {
833 echo ": $_dep $_depchain"
834 _ret=1
835 return
839 if [ -n "$_name" ]; then
840 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
841 if ! branch_contains "refs/$topbases/$_name" "$_fulldep"; then
842 # Some new commits in _dep
843 echo "$_dep $_depchain"
844 _ret=1
849 # needs_update NAME
850 # This function is recursive; it outputs reverse path from NAME
851 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
852 # inner paths first. Innermost name can be refs/remotes/<remote>/<name>
853 # if the head is not in sync with the <remote> branch <name>, ':' if
854 # the head is not in sync with the base (in this order of priority)
855 # or '!' if dependency is missing. Note that the remote branch, base
856 # order is reversed from the order they will actually be updated in
857 # order to accomodate tg info which treats out-of-date items that are
858 # only in the base as already being in the head for status purposes.
859 # It will also return non-zero status if NAME needs update.
860 # If needs_update() hits missing dependencies, it will append
861 # them to space-separated $missing_deps list and skip them.
862 needs_update()
864 recurse_deps branch_needs_update "$1"
867 # branch_empty NAME [-i | -w]
868 branch_empty()
870 if [ -z "$2" ]; then
871 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
872 _result=
873 _result_rev=
874 { read -r _result _result_rev <"$tg_cache_dir/$1/.mt"; } 2>/dev/null || :
875 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
876 _result=0
877 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ] || _result=$?
878 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null
879 [ ! -d "$tg_cache_dir/$1" ] || echo $_result $_rev >"$tg_cache_dir/$1/.mt"
880 return $_result
881 else
882 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ]
886 # list_deps [-i | -w] [BRANCH]
887 # -i/-w apply only to HEAD
888 list_deps()
890 head_from=
891 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
892 head="$(git symbolic-ref -q HEAD)" ||
893 head="..detached.."
895 git for-each-ref --format='%(objectname) %(refname)' "refs/$topbases${1:+/$1}" |
896 while read rev ref; do
897 name="${ref#refs/$topbases/}"
898 if branch_annihilated "$name" "" "$rev"; then
899 continue
902 from=$head_from
903 [ "refs/heads/$name" = "$head" ] ||
904 from=
905 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
906 dep_is_tgish=true
907 ref_exists "refs/$topbases/$dep" ||
908 dep_is_tgish=false
909 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
910 echo "$name $dep"
912 done
913 done
916 # switch_to_base NAME [SEED]
917 switch_to_base()
919 _base="refs/$topbases/$1"; _seed="$2"
920 # We have to do all the hard work ourselves :/
921 # This is like git checkout -b "$_base" "$_seed"
922 # (or just git checkout "$_base"),
923 # but does not create a detached HEAD.
924 git read-tree -u -m HEAD "${_seed:-$_base}"
925 [ -z "$_seed" ] || git update-ref "$_base" "$_seed"
926 git symbolic-ref HEAD "$_base"
929 # run editor with arguments
930 # the editor setting will be cached in $tg_editor (which is eval'd)
931 # result non-zero if editor fails or GIT_EDITOR cannot be determined
932 run_editor()
934 tg_editor="$GIT_EDITOR"
935 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
936 eval "$tg_editor" '"$@"'
939 # Show the help messages.
940 do_help()
942 _www=
943 if [ "$1" = "-w" ]; then
944 _www=1
945 shift
947 if [ -z "$1" ] ; then
948 # This is currently invoked in all kinds of circumstances,
949 # including when the user made a usage error. Should we end up
950 # providing more than a short help message, then we should
951 # differentiate.
952 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
954 ## Build available commands list for help output
956 cmds=
957 sep=
958 for cmd in "$TG_INST_CMDDIR"/tg-*; do
959 ! [ -r "$cmd" ] && continue
960 # strip directory part and "tg-" prefix
961 cmd="${cmd##*/}"
962 cmd="${cmd#tg-}"
963 cmds="$cmds$sep$cmd"
964 sep="|"
965 done
967 echo "TopGit version $TG_VERSION - A different patch queue manager"
968 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
969 echo " Or: $tgname help [-w] [<command>]"
970 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
971 elif [ -r "$TG_INST_CMDDIR"/tg-$1 -o -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
972 if [ -n "$_www" ]; then
973 nohtml=
974 if ! [ -r "$TG_INST_SHAREDIR/topgit.html" ]; then
975 echo "${0##*/}: missing html help file:" \
976 "$TG_INST_SHAREDIR/topgit.html" 1>&2
977 nohtml=1
979 if ! [ -r "$TG_INST_SHAREDIR/tg-$1.html" ]; then
980 echo "${0##*/}: missing html help file:" \
981 "$TG_INST_SHAREDIR/tg-$1.html" 1>&2
982 nohtml=1
984 if [ -n "$nohtml" ]; then
985 echo "${0##*/}: use" \
986 "\"${0##*/} help $1\" instead" 1>&2
987 exit 1
989 git web--browse -c help.browser "$TG_INST_SHAREDIR/tg-$1.html"
990 exit
992 output()
994 if [ -r "$TG_INST_CMDDIR"/tg-$1 ] ; then
995 "$TG_INST_CMDDIR"/tg-$1 -h 2>&1 || :
996 echo
998 if [ -r "$TG_INST_SHAREDIR/tg-$1.txt" ] ; then
999 cat "$TG_INST_SHAREDIR/tg-$1.txt"
1002 page output "$1"
1003 else
1004 echo "${0##*/}: no help for $1" 1>&2
1005 do_help
1006 exit 1
1010 ## Pager stuff
1012 # isatty FD
1013 isatty()
1015 test -t $1
1018 # pass "diff" to get pager.diff
1019 # if pager.$1 is a boolean false returns cat
1020 # if set to true or unset fails
1021 # otherwise succeeds and returns the value
1022 get_pager()
1024 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
1025 [ "$_x" != "true" ] || return 1
1026 echo "cat"
1027 return 0
1029 if _x="$(git config "pager.$1" 2>/dev/null)"; then
1030 echol "$_x"
1031 return 0
1033 return 1
1036 # setup_pager
1037 # Set TG_PAGER to a valid executable
1038 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
1039 # See also the following "page" function for ease of use
1040 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
1041 # Preference is (same as Git):
1042 # 1. GIT_PAGER
1043 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
1044 # 3. core.pager (only if set)
1045 # 4. PAGER
1046 # 5. git var GIT_PAGER
1047 # 6. less
1048 setup_pager()
1050 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
1052 emptypager=
1053 if [ -z "$TG_PAGER_IN_USE" ]; then
1054 # TG_PAGER = GIT_PAGER | PAGER | less
1055 # NOTE: GIT_PAGER='' is significant
1056 if [ -n "${GIT_PAGER+set}" ]; then
1057 TG_PAGER="$GIT_PAGER"
1058 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
1059 TG_PAGER="$_dp"
1060 elif _cp="$(git config core.pager 2>/dev/null)"; then
1061 TG_PAGER="$_cp"
1062 elif [ -n "${PAGER+set}" ]; then
1063 TG_PAGER="$PAGER"
1064 else
1065 _gp="$(git var GIT_PAGER 2>/dev/null)" || :
1066 [ "$_gp" != ":" ] || _gp=
1067 TG_PAGER="${_gp:-less}"
1069 if [ -z "$TG_PAGER" ]; then
1070 emptypager=1
1071 TG_PAGER=cat
1073 else
1074 emptypager=1
1075 TG_PAGER=cat
1078 # Set pager default environment variables
1079 # see pager.c:setup_pager
1080 if [ -z "${LESS+set}" ]; then
1081 LESS="-FRX"
1082 export LESS
1084 if [ -z "${LV+set}" ]; then
1085 LV="-c"
1086 export LV
1089 # this is needed so e.g. $(git diff) will still colorize it's output if
1090 # requested in ~/.gitconfig with color.diff=auto
1091 GIT_PAGER_IN_USE=1
1092 export GIT_PAGER_IN_USE
1094 # this is needed so we don't get nested pagers
1095 TG_PAGER_IN_USE=1
1096 export TG_PAGER_IN_USE
1099 # page eval_arg [arg ...]
1101 # Calls setup_pager then evals the first argument passing it all the rest
1102 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
1103 # by setup_pager (in which case the output is left as-is).
1105 # To handle arbitrary paging duties, collect lines to be paged into a
1106 # function and then call page with the function name or perhaps func_name "$@".
1108 # If no arguments at all are passed in do nothing (return with success).
1109 page()
1111 [ $# -gt 0 ] || return 0
1112 setup_pager
1113 _evalarg="$1"; shift
1114 if [ -n "$emptypager" ]; then
1115 eval "$_evalarg" '"$@"'
1116 else
1117 eval "$_evalarg" '"$@"' | eval "$TG_PAGER"
1121 # get_temp NAME [-d]
1122 # creates a new temporary file (or directory with -d) in the global
1123 # temporary directory $tg_tmp_dir with pattern prefix NAME
1124 get_temp()
1126 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
1129 # automatically called by strftime
1130 # does nothing if already setup
1131 # may be called explicitly if the first call would otherwise be in a subshell
1132 # so that the setup is only done once before subshells start being spawned
1133 setup_strftime()
1135 [ -z "$strftime_is_setup" ] || return 0
1137 # date option to format raw epoch seconds values
1138 daterawopt=
1139 _testes='951807788'
1140 _testdt='2000-02-29 07:03:08 UTC'
1141 _testfm='%Y-%m-%d %H:%M:%S %Z'
1142 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1143 daterawopt='-d@'
1144 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1145 daterawopt='-r'
1147 strftime_is_setup=1
1150 # $1 => strftime format string to use
1151 # $2 => raw timestamp as seconds since epoch
1152 # $3 => optional time zone string (empty/absent for local time zone)
1153 strftime()
1155 setup_strftime
1156 if [ -n "$daterawopt" ]; then
1157 if [ -n "$3" ]; then
1158 TZ="$3" date "$daterawopt$2" "+$1"
1159 else
1160 date "$daterawopt$2" "+$1"
1162 else
1163 if [ -n "$3" ]; then
1164 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1165 else
1166 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1171 ## Initial setup
1172 initial_setup()
1174 # suppress the merge log editor feature since git 1.7.10
1176 GIT_MERGE_AUTOEDIT=no
1177 export GIT_MERGE_AUTOEDIT
1179 auhopt=
1180 ! vcmp "$git_version" '>=' "2.9" || auhopt="--allow-unrelated-histories"
1181 git_dir="$(git rev-parse --git-dir)"
1182 root_dir="$(git rev-parse --show-cdup)"; root_dir="${root_dir:-.}"
1183 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null)" || :
1184 [ "$logrefupdates" = "true" ] || logrefupdates=
1185 tgsequester="$(git config --bool topgit.sequester 2>/dev/null)" || :
1186 tgnosequester=
1187 [ "$tgsequester" != "false" ] || tgnosequester=1
1188 unset tgsequester
1190 # make sure root_dir doesn't end with a trailing slash.
1192 root_dir="${root_dir%/}"
1193 [ -n "$base_remote" ] || base_remote="$(git config topgit.remote 2>/dev/null)" || :
1195 # make sure global cache directory exists inside GIT_DIR
1197 tg_cache_dir="$git_dir/tg-cache"
1198 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir"
1200 # create global temporary directories, inside GIT_DIR
1202 tg_tmp_dir=
1203 trap 'rm -rf "$tg_tmp_dir"' EXIT
1204 trap 'exit 129' HUP
1205 trap 'exit 130' INT
1206 trap 'exit 131' QUIT
1207 trap 'exit 134' ABRT
1208 trap 'exit 143' TERM
1209 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX")"
1210 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1212 # catch errors if topbases is used without being set
1213 unset tg_topbases_set
1214 topbases="programmer*:error"
1215 oldbases="$topbases"
1218 set_topbases()
1220 # refer to "top-bases" in a refname with $topbases
1222 [ -z "$tg_topbases_set" ] || return 0
1224 # See if topgit.top-bases is set to heads or refs
1225 tgtb="$(git config "topgit.top-bases" 2>/dev/null)" || :
1226 if [ -n "$tgtb" ] && [ "$tgtb" != "heads" ] && [ "$tgtb" != "refs" ]; then
1227 if [ -n "$1" ]; then
1228 # never die on the hook script
1229 unset tgtb
1230 else
1231 die "invalid \"topgit.top-bases\" setting (must be \"heads\" or \"refs\")"
1234 if [ -n "$tgtb" ]; then
1235 case "$tgtb" in
1236 heads)
1237 topbases="heads/{top-bases}"
1238 oldbases="top-bases";;
1239 refs)
1240 topbases="top-bases"
1241 oldbases="heads/{top-bases}";;
1242 esac
1243 # MUST NOT be exported
1244 unset tgtb tg_topbases_set
1245 tg_topbases_set=1
1246 return 0
1248 unset tgtb
1250 # check heads and top-bases and see what state the current
1251 # repository is in. remotes are ignored.
1253 hblist=" "
1254 topbases=
1255 both=
1256 newtb="heads/{top-bases}"
1257 while read -r rn && [ -n "$rn" ]; do case "$rn" in
1258 "refs/heads/{top-bases}"/*)
1259 case "$hblist" in *" ${rn#refs/$newtb/} "*)
1260 if [ "$topbases" != "heads/{top-bases}" ] && [ -n "$topbases" ]; then
1261 both=1
1262 break;
1263 else
1264 topbases="heads/{top-bases}"
1265 oldbases="top-bases"
1267 esac;;
1268 "refs/top-bases"/*)
1269 case "$hblist" in *" ${rn#refs/top-bases/} "*)
1270 if [ "$topbases" != "top-bases" ] && [ -n "$topbases" ]; then
1271 both=1
1272 break;
1273 else
1274 topbases="top-bases"
1275 oldbases="heads/{top-bases}"
1277 esac;;
1278 "refs/heads"/*)
1279 hblist="$hblist${rn#refs/heads/} ";;
1280 esac; done <<-EOT
1281 $(git for-each-ref --format='%(refname)' "refs/heads" "refs/top-bases")
1283 if [ -n "$both" ]; then
1284 if [ -n "$1" ]; then
1285 # hook script always prefers newer without complaint
1286 topbases="heads/{top-bases}"
1287 oldbases="top-bases"
1288 else
1289 # Complain and die
1290 err "repository contains existing TopGit branches"
1291 err "but some use refs/top-bases/... for the base"
1292 err "and some use refs/heads/{top-bases}/... for the base"
1293 err "with the latter being the new, preferred location"
1294 err "set \"topgit.top-bases\" to either \"heads\" to use"
1295 err "the new heads/{top-bases} location or \"refs\" to use"
1296 err "the old top-bases location."
1297 die "schizophrenic repository requires topgit.top-bases setting"
1301 [ -n "$topbases" ] || {
1302 # default is still top-bases for now
1303 topbases="top-bases"
1304 oldbases="heads/{top-bases}"
1306 # MUST NOT be exported
1307 unset hblist both newtb rn tg_topases_set
1308 tg_topbases_set=1
1309 return 0
1312 # init_reflog "ref"
1313 # if "$logrefupdates" is set and ref is not under refs/heads/ then force
1314 # an empty log file to exist so that ref changes will be logged
1315 # "$1" must be a fully-qualified refname (i.e. start with "refs/")
1316 # However, if "$1" is "refs/tgstash" then always make the reflog
1317 init_reflog()
1319 [ -n "$1" ] || return 0
1320 [ -n "$logrefupdates" ] || [ "$1" = "refs/tgstash" ] || return 0
1321 case "$1" in refs/heads/*) return 0;; refs/*[!/]);; *) return 1; esac
1322 mkdir -p "$git_dir/logs/${1%/*}" 2>/dev/null || :
1323 { >>"$git_dir/logs/$1" || :; } 2>/dev/null
1326 # store the "realpath" for "$2" in "$1" except the leaf is not resolved if it's
1327 # a symbolic link. The directory part must exist, but the basename need not.
1328 v_get_abs_path()
1330 [ -n "$1" ] && [ -n "$2" ] || return 1
1331 set -- "$1" "$2" "${2%/}"
1332 case "$3" in
1333 */*) set -- "$1" "$2" "${3%/*}";;
1334 * ) set -- "$1" "$2" ".";;
1335 esac
1336 [ -d "$3" ] || return 1
1337 eval "$1="'"$(cd "$3" && pwd -P)/${2##*/}"'
1340 ## Startup
1342 : "${TG_INST_CMDDIR:=@cmddir@}"
1343 : "${TG_INST_SHAREDIR:=@sharedir@}"
1344 : "${TG_INST_HOOKSDIR:=@hooksdir@}"
1346 [ -d "$TG_INST_CMDDIR" ] ||
1347 die "No command directory: '$TG_INST_CMDDIR'"
1349 if [ -n "$tg__include" ]; then
1351 # We were sourced from another script for our utility functions;
1352 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1353 # work as expected in every shell. See http://bugs.debian.org/516188
1355 # ensure setup happens
1357 initial_setup
1358 set_topbases 1
1360 else
1362 set -e
1364 tg="$0"
1365 tgdir="${tg%/}"
1366 case "$tgdir" in */*);;*) tgdir="./$tgdir"; esac
1367 tgdir="${tgdir%/*}/"
1368 tgname="${tg##*/}"
1369 [ "$0" != "$tgname" ] || tgdir=""
1371 # If tg contains a '/' but does not start with one then replace it with an absolute path
1373 case "$0" in /*) ;; */*)
1374 tgdir="$(cd "${0%/*}" && pwd -P)/"
1375 tg="$tgdir$tgname"
1376 esac
1378 # If the tg in the PATH is the same as "$tg" just display the basename
1379 # tgdisplay will include any explicit -C <dir> option whereas tg will not
1381 tgdisplaydir="$tgdir"
1382 tgdisplay="$tg"
1384 v_get_abs_path _tgabs "$tg" &&
1385 v_get_abs_path _tgnameabs "$(cmd_path "$tgname")" &&
1386 [ "$_tgabs" = "$_tgnameabs" ]
1387 then
1388 tgdisplaydir=""
1389 tgdisplay="$tgname"
1391 unset _tgabs _tgnameabs
1393 explicit_remote=
1394 explicit_dir=
1395 gitcdopt=
1396 noremote=
1398 cmd=
1399 while :; do case "$1" in
1401 help|--help|-h)
1402 cmd=help
1403 shift
1404 break;;
1406 --hooks-path)
1407 cmd=hooks-path
1408 shift
1409 break;;
1411 --top-bases)
1412 cmd=top-bases
1413 shift
1414 break;;
1417 shift
1418 if [ -z "$1" ]; then
1419 echo "Option -r requires an argument." >&2
1420 do_help
1421 exit 1
1423 unset noremote
1424 base_remote="$1"
1425 explicit_remote="$base_remote"
1426 tg="$tgdir$tgname -r $explicit_remote"
1427 tgdisplay="$tgdisplaydir$tgname"
1428 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1429 tgdisplay="$tgdisplay -r $explicit_remote"
1430 shift;;
1433 unset base_remote explicit_remote
1434 noremote=1
1435 tg="$tgdir$tgname -u"
1436 tgdisplay="$tgdisplaydir$tgname"
1437 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1438 tgdisplay="$tgdisplay -u"
1439 shift;;
1442 shift
1443 if [ -z "$1" ]; then
1444 echo "Option -C requires an argument." >&2
1445 do_help
1446 exit 1
1448 cd "$1"
1449 unset GIT_DIR
1450 explicit_dir="$1"
1451 gitcdopt=" -C \"$explicit_dir\""
1452 tg="$tgdir$tgname"
1453 tgdisplay="$tgdisplaydir$tgname -C \"$explicit_dir\""
1454 [ -z "$explicit_remote" ] || tg="$tg -r $explicit_remote"
1455 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
1456 [ -z "$noremote" ] || tg="$tg -u"
1457 [ -z "$noremote" ] || tg="$tgdisplay -u"
1458 shift;;
1461 shift
1462 if [ -z "$1" ]; then
1463 echo "Option -c requires an argument." >&2
1464 do_help
1465 exit 1
1467 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
1468 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
1469 export GIT_CONFIG_PARAMETERS
1470 shift;;
1473 shift
1474 break;;
1477 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
1478 do_help
1479 exit 1;;
1482 break;;
1484 esac; done
1486 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
1488 ## Dispatch
1490 [ -n "$cmd" ] || { do_help; exit 1; }
1492 case "$cmd" in
1494 help)
1495 do_help "$@"
1496 exit 0;;
1498 hooks-path)
1499 # Internal command
1500 echol "$TG_INST_HOOKSDIR";;
1502 top-bases)
1503 # Maintenance command
1504 git_dir="$(git rev-parse --git-dir)"
1505 set_topbases
1506 echol "refs/$topbases";;
1509 [ -r "$TG_INST_CMDDIR"/tg-$cmd ] || {
1510 echo "Unknown subcommand: $cmd" >&2
1511 do_help
1512 exit 1
1515 initial_setup
1516 [ -z "$noremote" ] || unset base_remote
1518 nomergesetup=
1519 case "$cmd" in info|log|summary|rebase|revert|tag)
1520 # avoid merge setup where not necessary
1522 nomergesetup=1
1523 esac
1525 if [ -z "$nomergesetup" ]; then
1526 # make sure merging the .top* files will always behave sanely
1528 setup_ours
1529 setup_hook "pre-commit"
1532 # everything but rebase needs topbases set
1533 [ "$cmd" = "rebase" ] || set_topbases
1535 _use_ref_cache=
1536 tg_read_only=1
1537 case "$cmd" in
1538 summary|info|export|tag)
1539 _use_ref_cache=1;;
1540 annihilate|create|delete|depend|import|update)
1541 tg_read_only=;;
1542 esac
1543 [ -z "$_use_ref_cache" ] || v_create_ref_cache
1545 . "$TG_INST_CMDDIR"/tg-$cmd;;
1546 esac
1550 # vim:noet