tg.sh: fix recurse_deps pre-order traversal with remotes enabled
[topgit/pro.git] / tg.sh
bloba93dd2c629dd76fbb9fdcb140ccf474abd829d0b
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
5 # All rights reserved.
6 # GPLv2
8 TG_VERSION=0.18.1
10 # Update if you add any code that requires a newer version of git
11 GIT_MINIMUM_VERSION=1.7.7.2
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 info()
25 echo "${TG_RECURSIVE}${tgname:-tg}: $*"
28 warn()
30 info "warning: $*" >&2
33 err()
35 info "error: $*" >&2
38 die()
40 info "fatal: $*" >&2
41 exit 1
44 wc_l()
46 echo $(wc -l)
49 compare_versions()
51 separator="$1"
52 echo "$3" | tr "${separator}" '\n' | (for l in $(echo "$2"|tr "${separator}" ' '); do
53 read r || return 0
54 [ $l -ge $r ] || return 1
55 [ $l -gt $r ] && return 0
56 done)
59 precheck() {
60 git_ver="$(git version | sed -e 's/^[^0-9][^0-9]*//')"
61 compare_versions . "${git_ver%%[!0-9.]*}" "${GIT_MINIMUM_VERSION}" \
62 || die "git version >= ${GIT_MINIMUM_VERSION} required"
65 case "$1" in version|--version|-V)
66 echo "TopGit version $TG_VERSION"
67 exit 0
68 esac
70 precheck
71 [ "$1" = "precheck" ] && exit 0
74 cat_depsmsg_internal()
76 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
77 if [ -s "$tg_cache_dir/$1/.$2" ]; then
78 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
79 _line=
80 while IFS= read -r _line || [ -n "$_line" ]; do
81 printf '%s\n' "$_line"
82 done
83 return 0
84 fi <"$tg_cache_dir/$1/.$2"
86 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null || :
87 if [ -d "$tg_cache_dir/$1" ]; then
88 printf '%s\n' "$_rev" >"$tg_cache_dir/$1/.$2"
89 _line=
90 git cat-file blob "$_rev:.$2" 2>/dev/null |
91 while IFS= read -r _line || [ -n "$_line" ]; do
92 printf '%s\n' "$_line" >&3
93 printf '%s\n' "$_line"
94 done 3>>"$tg_cache_dir/$1/.$2"
95 else
96 git cat-file blob "$_rev:.$2" 2>/dev/null
100 # cat_deps BRANCHNAME
101 # Caches result
102 cat_deps()
104 cat_depsmsg_internal "$1" topdeps
107 # cat_msg BRANCHNAME
108 # Caches result
109 cat_msg()
111 cat_depsmsg_internal "$1" topmsg
114 # cat_file TOPIC:PATH [FROM]
115 # cat the file PATH from branch TOPIC when FROM is empty.
116 # FROM can be -i or -w, than the file will be from the index or worktree,
117 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
118 cat_file()
120 path="$1"
121 case "$2" in
123 cat "$root_dir/${path#*:}"
126 # ':file' means cat from index
127 git cat-file blob ":${path#*:}"
130 case "$path" in
131 refs/heads/*:.topdeps)
132 _temp="${path%:.topdeps}"
133 cat_deps "${_temp#refs/heads/}"
135 refs/heads/*:.topmsg)
136 _temp="${path%:.topmsg}"
137 cat_msg "${_temp#refs/heads/}"
140 git cat-file blob "$path"
142 esac
145 die "Wrong argument to cat_file: '$2'"
147 esac
150 # get tree for the committed topic
151 get_tree_()
153 echo "refs/heads/$1"
156 # get tree for the base
157 get_tree_b()
159 echo "refs/top-bases/$1"
162 # get tree for the index
163 get_tree_i()
165 git write-tree
168 # get tree for the worktree
169 get_tree_w()
171 i_tree=$(git write-tree)
173 # the file for --index-output needs to sit next to the
174 # current index file
175 cd "$root_dir"
176 : ${GIT_INDEX_FILE:="$git_dir/index"}
177 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
178 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
179 GIT_INDEX_FILE="$TMP_INDEX" &&
180 export GIT_INDEX_FILE &&
181 git diff --name-only -z HEAD |
182 git update-index -z --add --remove --stdin &&
183 git write-tree &&
184 rm -f "$TMP_INDEX"
188 # strip_ref "$(git symbolic-ref HEAD)"
189 # Output will have a leading refs/heads/ or refs/top-bases/ stripped if present
190 strip_ref()
192 case "$1" in
193 refs/heads/*)
194 echo "${1#refs/heads/}"
196 refs/top-bases/*)
197 echo "${1#refs/top-bases/}"
200 echo "$1"
201 esac
204 # pretty_tree NAME [-b | -i | -w]
205 # Output tree ID of a cleaned-up tree without tg's artifacts.
206 # NAME will be ignored for -i and -w, but needs to be present
207 pretty_tree()
209 name=$1
210 source=${2#?}
211 git ls-tree --full-tree "$(get_tree_$source "$name")" |
212 LC_ALL=C sed -ne '/ \.top.*$/!p' |
213 git mktree
216 # setup_hook NAME
217 setup_hook()
219 tgname="$(basename "$0")"
220 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
221 if [ -f "$git_dir/hooks/$1" ] && fgrep -q "$hook_call" "$git_dir/hooks/$1"; then
222 # Another job well done!
223 return
225 # Prepare incantation
226 hook_chain=
227 if [ -s "$git_dir/hooks/$1" -a -x "$git_dir/hooks/$1" ]; then
228 hook_call="$hook_call"' || exit $?'
229 if ! LC_ALL=C sed -n 1p <"$git_dir/hooks/$1" | LC_ALL=C fgrep -qx "#!@SHELL_PATH@"; then
230 chain_num=
231 while [ -e "$git_dir/hooks/$1-chain$chain_num" ]; do
232 chain_num=$(( $chain_num + 1 ))
233 done
234 cp -p "$git_dir/hooks/$1" "$git_dir/hooks/$1-chain$chain_num"
235 hook_chain=1
237 else
238 hook_call="exec $hook_call"
240 # Don't call hook if tg is not installed
241 hook_call="if which \"$tgname\" > /dev/null; then $hook_call; fi"
242 # Insert call into the hook
244 echo "#!@SHELL_PATH@"
245 echo "$hook_call"
246 if [ -n "$hook_chain" ]; then
247 echo "exec \"\$0-chain$chain_num\" \"\$@\""
248 else
249 [ ! -s "$git_dir/hooks/$1" ] || cat "$git_dir/hooks/$1"
251 } >"$git_dir/hooks/$1+"
252 chmod a+x "$git_dir/hooks/$1+"
253 mv "$git_dir/hooks/$1+" "$git_dir/hooks/$1"
256 # setup_ours (no arguments)
257 setup_ours()
259 if [ ! -s "$git_dir/info/attributes" ] || ! grep -q topmsg "$git_dir/info/attributes"; then
260 [ -d "$git_dir/info" ] || mkdir "$git_dir/info"
262 echo ".topmsg merge=ours"
263 echo ".topdeps merge=ours"
264 } >>"$git_dir/info/attributes"
266 if ! git config merge.ours.driver >/dev/null; then
267 git config merge.ours.name '"always keep ours" merge driver'
268 git config merge.ours.driver 'touch %A'
272 # measure_branch NAME [BASE]
273 measure_branch()
275 _bname="$1"; _base="$2"
276 [ -n "$_base" ] || _base="refs/top-bases/$_bname"
277 # The caller should've verified $name is valid
278 _commits="$(git rev-list "$_bname" ^"$_base" -- | wc_l)"
279 _nmcommits="$(git rev-list --no-merges "$_bname" ^"$_base" -- | wc_l)"
280 if [ $_commits -ne 1 ]; then
281 _suffix="commits"
282 else
283 _suffix="commit"
285 echo "$_commits/$_nmcommits $_suffix"
288 # branch_contains B1 B2
289 # Whether B1 is a superset of B2.
290 branch_contains()
292 _revb1="$(ref_exists_rev "$1")" || return 0
293 _revb2="$(ref_exists_rev "$2")" || return 0
294 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
295 if read _result _rev_matchb1 _rev_matchb2 && \
296 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
297 return $_result
298 fi <"$tg_cache_dir/$1/.bc/$2/.d"
300 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
301 _result=0
302 [ -z "$(git rev-list --max-count=1 ^"$_revb1" "$_revb2" --)" ] || _result=$?
303 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
304 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
306 return $_result
309 create_ref_dirs()
311 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
312 sed -e 's/ .*$//;'"s~^~$tg_tmp_dir/cached/~" <"$tg_ref_cache" | xargs mkdir -p
313 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
316 # If the first argument is non-empty, outputs "1" if this call created the cache
317 create_ref_cache()
319 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
320 _remotespec=
321 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
322 [ -z "$1" ] || printf '1'
323 git for-each-ref --format='%(refname) %(objectname)' \
324 refs/heads refs/top-bases $_remotespec >"$tg_ref_cache"
325 create_ref_dirs
328 remove_ref_cache()
330 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
331 >"$tg_ref_cache"
334 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
335 rev_parse()
337 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
338 LC_ALL=C awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
339 else
340 [ -z "$tg_ref_cache_only" ] || return 1
341 git rev-parse --quiet --verify "$1^0" -- 2>/dev/null
345 # ref_exists_rev REF
346 # Whether REF is a valid ref name
347 # REF must be fully qualified and start with refs/heads/, refs/top-bases/
348 # or, if $base_remote is set, refs/remotes/$base_remote/
349 # Caches result if $tg_read_only and outputs HASH on success
350 ref_exists_rev()
352 case "$1" in
353 refs/*)
355 $octet20)
356 printf '%s' "$1"
357 return;;
359 die "ref_exists_rev requires fully-qualified ref name"
360 esac
361 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1^0" -- 2>/dev/null; return; }
362 _result=
363 _result_rev=
364 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
365 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
366 _result_rev="$(rev_parse "$1")"
367 _result=$?
368 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
369 [ ! -d "$tg_tmp_dir/cached/$1" ] || \
370 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
371 printf '%s' "$_result_rev"
372 return $_result
375 # Same as ref_exists_rev but output is abbreviated hash
376 ref_exists_rev_short()
378 case "$1" in
379 refs/*)
381 $octet20)
384 die "ref_exists_rev_short requires fully-qualified ref name"
385 esac
386 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify --short "$1^0" -- 2>/dev/null; return; }
387 _result=
388 _result_rev=
389 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
390 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
391 _result_rev="$(rev_parse "$1")"
392 _result=$?
393 if [ $_result -eq 0 ]; then
394 _result_rev="$(git rev-parse --verify --short --quiet "$_result_rev" --)"
395 _result=$?
397 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
398 [ ! -d "$tg_tmp_dir/cached/$1" ] || \
399 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
400 printf '%s' "$_result_rev"
401 return $_result
404 # ref_exists REF
405 # Whether REF is a valid ref name
406 # REF must be fully qualified and start with refs/heads/, refs/top-bases/
407 # or, if $base_remote is set, refs/remotes/$base_remote/
408 # Caches result
409 ref_exists()
411 ref_exists_rev "$1" >/dev/null
414 # rev_parse_tree REF
415 # Runs git rev-parse REF^{tree}
416 # Caches result if $tg_read_only
417 rev_parse_tree()
419 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
420 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
421 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
422 printf '%s\n' "$_result"
423 return 0
425 return 1
427 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
428 if [ -d "$tg_tmp_dir/cached/$1" ]; then
429 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
430 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
431 printf '%s\n' "$_result"
432 return 0
434 return 1
436 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
439 # has_remote BRANCH
440 # Whether BRANCH has a remote equivalent (accepts top-bases/ too)
441 has_remote()
443 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
446 # Return the verified TopGit branch name or die with an error.
447 # As a convenience, if HEAD is given and HEAD is a symbolic ref to
448 # refs/heads/... then ... will be verified instead.
449 # if "$2" = "-f" then return an error rather than dying.
450 verify_topgit_branch()
452 case "$1" in
453 refs/heads/*)
454 _verifyname="${1#refs/heads/}"
456 refs/top-bases/*)
457 _verifyname="${1#refs/top-bases/}"
459 HEAD)
460 _verifyname="$(git symbolic-ref HEAD 2>/dev/null || :)"
461 [ -n "$_verifyname" ] || die "HEAD is not a symbolic ref"
462 case "$_verifyname" in refs/heads/*) :;; *)
463 [ "$2" != "-f" ] || return 1
464 die "HEAD is not a symbolic ref to the refs/heads namespace"
465 esac
466 _verifyname="${_verifyname#refs/heads/}"
469 _verifyname="$1"
471 esac
472 if ! ref_exists "refs/heads/$_verifyname"; then
473 [ "$2" != "-f" ] || return 1
474 die "no such branch: $_verifyname"
476 if ! ref_exists "refs/top-bases/$_verifyname"; then
477 [ "$2" != "-f" ] || return 1
478 die "not a TopGit-controlled branch: $_verifyname"
480 printf '%s' "$_verifyname"
483 # Caches result
484 # $1 = branch name (i.e. "t/foo/bar")
485 # $2 = optional result of rev-parse "refs/heads/$1"
486 # $3 = optional result of rev-parse "refs/top-bases/$1"
487 branch_annihilated()
489 _branch_name="$1"
490 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
491 _rev_base="${3:-$(ref_exists_rev "refs/top-bases/$_branch_name")}"
493 _result=
494 _result_rev=
495 _result_rev_base=
496 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/$_branch_name/.ann"; } 2>/dev/null || :
497 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
499 # use the merge base in case the base is ahead.
500 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
502 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
503 _result=$?
504 [ -d "$tg_cache_dir/$_branch_name" ] || mkdir -p "$tg_cache_dir/$_branch_name" 2>/dev/null
505 [ ! -d "$tg_cache_dir/$_branch_name" ] || \
506 echo $_result $_rev $_rev_base >"$tg_cache_dir/$_branch_name/.ann" 2>/dev/null || :
507 return $_result
510 non_annihilated_branches()
512 git for-each-ref --format='%(objectname) %(refname)' refs/top-bases |
513 while read rev ref; do
514 name="${ref#refs/top-bases/}"
515 if branch_annihilated "$name" "" "$rev"; then
516 continue
518 echo "$name"
519 done
522 # Make sure our tree is clean
523 ensure_clean_tree()
525 git update-index --ignore-submodules --refresh ||
526 die "the working directory has uncommitted changes (see above) - first commit or reset them"
527 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
528 die "the index has uncommited changes"
531 # is_sha1 REF
532 # Whether REF is a SHA1 (compared to a symbolic name).
533 is_sha1()
535 case "$1" in $octet20) return 0;; esac
536 return 1
539 # recurse_deps_internal NAME [BRANCHPATH...]
540 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
541 # followed by a 1 if the branch is "tgish" or a 0 if not
542 # then the branch name followed by its depedency chain (which might be empty)
543 # An output line might look like this:
544 # 0 1 t/foo/leaf t/foo/int t/stage
545 # If no_remotes is non-empty, exclude remotes
546 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
547 # any branch names in the space-separated recurse_deps_exclude variable
548 # are skipped (along with their dependencies)
549 recurse_deps_internal()
551 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
552 _ref_hash=
553 if ! _ref_hash="$(ref_exists_rev "refs/heads/$1")"; then
554 [ -z "$2" ] || echo "1 0 $*"
555 return
558 _is_tgish=0
559 _ref_hash_base=
560 ! _ref_hash_base="$(ref_exists_rev "refs/top-bases/$1")" || _is_tgish=1
561 [ -z "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
563 # If no_remotes is unset also check our base against remote base.
564 # Checking our head against remote head has to be done in the helper.
565 if [ -n "$_is_tgish" -a -z "$no_remotes" ] && has_remote "top-bases/$1"; then
566 echo "0 0 refs/remotes/$base_remote/top-bases/$1 $*"
569 # if the branch was annihilated, it is considered to have no dependencies
570 if [ -n "$_is_tgish" ] && ! branch_annihilated "$1" "$_ref_hash" "$_ref_hash_base"; then
571 #TODO: handle nonexisting .topdeps?
572 cat_deps "$1" |
573 while read _dname; do
574 # Shoo shoo, leave our environment alone!
575 (recurse_deps_internal "$_dname" "$@")
576 done
579 [ -n "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
582 # do_eval CMD
583 # helper for recurse_deps so that a return statement executed inside CMD
584 # does not return from recurse_deps. This shouldn't be necessary, but it
585 # seems that it actually is.
586 do_eval()
588 eval "$@"
591 # becomes read-only for caching purposes
592 # assigns new value to tg_read_only
593 # become_cacheable/undo_become_cacheable calls may be nested
594 become_cacheable()
596 _old_tg_read_only="$tg_read_only"
597 if [ -z "$tg_read_only" ]; then
598 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
599 tg_read_only=1
601 _my_ref_cache="$(create_ref_cache 1)"
602 _my_ref_cache="${_my_ref_cache:+1}"
603 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
606 # restores tg_read_only and ref_cache to state before become_cacheable call
607 # become_cacheable/undo_bocome_cacheable calls may be nested
608 undo_become_cacheable()
610 case "$tg_read_only" in
611 "undo"[01]"-"*)
612 _suffix="${tg_read_only#undo?-}"
613 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
614 tg_read_only="$_suffix"
615 esac
618 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
619 become_non_cacheable()
621 remove_ref_cache
622 tg_read_only=
623 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
626 # recurse_deps CMD NAME [BRANCHPATH...]
627 # Recursively eval CMD on all dependencies of NAME.
628 # Dependencies are visited in topological order.
629 # CMD can refer to $_name for queried branch name,
630 # $_dep for dependency name,
631 # $_depchain for space-seperated branch backtrace,
632 # $_dep_missing boolean to check whether $_dep is present
633 # and the $_dep_is_tgish boolean.
634 # It can modify $_ret to affect the return value
635 # of the whole function.
636 # If recurse_deps() hits missing dependencies, it will append
637 # them to space-separated $missing_deps list and skip them
638 # after calling CMD with _dep_missing set.
639 # remote dependencies are processed if no_remotes is unset.
640 # any branch names in the space-separated recurse_deps_exclude variable
641 # are skipped (along with their dependencies)
642 recurse_deps()
644 _cmd="$1"; shift
646 become_cacheable
647 _depsfile="$(get_temp tg-depsfile)"
648 recurse_deps_internal "$@" >>"$_depsfile"
649 undo_become_cacheable
651 _ret=0
652 while read _ismissing _istgish _dep _name _deppath; do
653 _depchain="$_name${_deppath:+ $_deppath}"
654 _dep_is_tgish=
655 [ "$_istgish" = "0" ] || _dep_is_tgish=1
656 _dep_missing=
657 if [ "$_ismissing" != "0" ]; then
658 _dep_missing=1
659 case " $missing_deps " in *" $_dep "*) :;; *)
660 missing_deps="${missing_deps:+$missing_deps }$_dep"
661 esac
663 do_eval "$_cmd"
664 done <"$_depsfile"
665 rm -f "$_depsfile"
666 return $_ret
669 # branch_needs_update
670 # This is a helper function for determining whether given branch
671 # is up-to-date wrt. its dependencies. It expects input as if it
672 # is called as a recurse_deps() helper.
673 # In case the branch does need update, it will echo it together
674 # with the branch backtrace on the output (see needs_update()
675 # description for details) and set $_ret to non-zero.
676 branch_needs_update()
678 if [ -n "$_dep_missing" ]; then
679 echo "! $_dep $_depchain"
680 return 0
683 _dep_base_update=
684 if [ -n "$_dep_is_tgish" ]; then
685 branch_annihilated "$_dep" && return 0
687 if has_remote "$_dep"; then
688 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" || _dep_base_update=%
690 # This can possibly override the remote check result;
691 # we want to sync with our base first
692 branch_contains "refs/heads/$_dep" "refs/top-bases/$_dep" || _dep_base_update=:
695 if [ -n "$_dep_base_update" ]; then
696 # _dep needs to be synced with its base/remote
697 echo "$_dep_base_update $_dep $_depchain"
698 _ret=1
699 elif [ -n "$_name" ]; then
700 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
701 if ! branch_contains "refs/top-bases/$_name" "$_fulldep"; then
702 # Some new commits in _dep
703 echo "$_dep $_depchain"
704 _ret=1
709 # needs_update NAME
710 # This function is recursive; it outputs reverse path from NAME
711 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
712 # inner paths first. Innermost name can be ':' if the head is
713 # not in sync with the base, '%' if the head is not in sync
714 # with the remote (in this order of priority) or '!' if depednecy
715 # is missing.
716 # It will also return non-zero status if NAME needs update.
717 # If needs_update() hits missing dependencies, it will append
718 # them to space-separated $missing_deps list and skip them.
719 needs_update()
721 recurse_deps branch_needs_update "$1"
724 # branch_empty NAME [-i | -w]
725 branch_empty()
727 if [ -z "$2" ]; then
728 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
729 _result=
730 _result_rev=
731 { read -r _result _result_rev <"$tg_cache_dir/$1/.mt"; } 2>/dev/null || :
732 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
733 _result=0
734 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ] || _result=$?
735 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null
736 [ ! -d "$tg_cache_dir/$1" ] || echo $_result $_rev >"$tg_cache_dir/$1/.mt"
737 return $_result
738 else
739 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ]
743 # list_deps [-i | -w] [BRANCH]
744 # -i/-w apply only to HEAD
745 list_deps()
747 head_from=
748 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
749 head="$(git symbolic-ref -q HEAD)" ||
750 head="..detached.."
752 git for-each-ref --format='%(objectname) %(refname)' refs/top-bases"${1:+/$1}" |
753 while read rev ref; do
754 name="${ref#refs/top-bases/}"
755 if branch_annihilated "$name" "" "$rev"; then
756 continue
759 from=$head_from
760 [ "refs/heads/$name" = "$head" ] ||
761 from=
762 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
763 dep_is_tgish=true
764 ref_exists "refs/top-bases/$dep" ||
765 dep_is_tgish=false
766 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
767 echo "$name $dep"
769 done
770 done
773 # switch_to_base NAME [SEED]
774 switch_to_base()
776 _base="refs/top-bases/$1"; _seed="$2"
777 # We have to do all the hard work ourselves :/
778 # This is like git checkout -b "$_base" "$_seed"
779 # (or just git checkout "$_base"),
780 # but does not create a detached HEAD.
781 git read-tree -u -m HEAD "${_seed:-$_base}"
782 [ -z "$_seed" ] || git update-ref "$_base" "$_seed"
783 git symbolic-ref HEAD "$_base"
786 # run editor with arguments
787 # the editor setting will be cached in $tg_editor (which is eval'd)
788 # result non-zero if editor fails or GIT_EDITOR cannot be determined
789 run_editor()
791 tg_editor="$GIT_EDITOR"
792 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
793 eval "$tg_editor" '"$@"'
796 # Show the help messages.
797 do_help()
799 _www=
800 if [ "$1" = "-w" ]; then
801 _www=1
802 shift
804 if [ -z "$1" ] ; then
805 # This is currently invoked in all kinds of circumstances,
806 # including when the user made a usage error. Should we end up
807 # providing more than a short help message, then we should
808 # differentiate.
809 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
811 ## Build available commands list for help output
813 cmds=
814 sep=
815 for cmd in "@cmddir@"/tg-*; do
816 ! [ -r "$cmd" ] && continue
817 # strip directory part and "tg-" prefix
818 cmd="$(basename "$cmd")"
819 cmd="${cmd#tg-}"
820 cmds="$cmds$sep$cmd"
821 sep="|"
822 done
824 echo "TopGit version $TG_VERSION - A different patch queue manager"
825 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
826 echo " Or: $tgname help [-w] [<command>]"
827 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
828 elif [ -r "@cmddir@"/tg-$1 -o -r "@sharedir@/tg-$1.txt" ] ; then
829 if [ -n "$_www" ]; then
830 nohtml=
831 if ! [ -r "@sharedir@/topgit.html" ]; then
832 echo "`basename $0`: missing html help file:" \
833 "@sharedir@/topgit.html" 1>&2
834 nohtml=1
836 if ! [ -r "@sharedir@/tg-$1.html" ]; then
837 echo "`basename $0`: missing html help file:" \
838 "@sharedir@/tg-$1.html" 1>&2
839 nohtml=1
841 if [ -n "$nohtml" ]; then
842 echo "`basename $0`: use" \
843 "\"`basename $0` help $1\" instead" 1>&2
844 exit 1
846 git web--browse -c help.browser "@sharedir@/tg-$1.html"
847 exit
849 output()
851 if [ -r "@cmddir@"/tg-$1 ] ; then
852 "@cmddir@"/tg-$1 -h 2>&1 || :
853 echo
855 if [ -r "@sharedir@/tg-$1.txt" ] ; then
856 cat "@sharedir@/tg-$1.txt"
859 page output "$1"
860 else
861 echo "`basename $0`: no help for $1" 1>&2
862 do_help
863 exit 1
867 ## Pager stuff
869 # isatty FD
870 isatty()
872 test -t $1
875 # pass "diff" to get pager.diff
876 # if pager.$1 is a boolean false returns cat
877 # if set to true or unset fails
878 # otherwise succeeds and returns the value
879 get_pager()
881 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
882 [ "$_x" != "true" ] || return 1
883 echo "cat"
884 return 0
886 if _x="$(git config "pager.$1" 2>/dev/null)"; then
887 echo "$_x"
888 return 0
890 return 1
893 # setup_pager
894 # Set TG_PAGER to a valid executable
895 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
896 # See also the following "page" function for ease of use
897 # emptypager will be set to 1 (otherwise empty) if TG_PAGER was set to "cat" to not be empty
898 # Preference is (same as Git):
899 # 1. GIT_PAGER
900 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
901 # 3. core.pager (only if set)
902 # 4. PAGER
903 # 5. git var GIT_PAGER
904 # 6. less
905 setup_pager()
907 isatty 1 || { emptypager=1; TG_PAGER=cat; return 0; }
909 emptypager=
910 if [ -z "$TG_PAGER_IN_USE" ]; then
911 # TG_PAGER = GIT_PAGER | PAGER | less
912 # NOTE: GIT_PAGER='' is significant
913 if [ -n "${GIT_PAGER+set}" ]; then
914 TG_PAGER="$GIT_PAGER"
915 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
916 TG_PAGER="$_dp"
917 elif _cp="$(git config core.pager 2>/dev/null)"; then
918 TG_PAGER="$_cp"
919 elif [ -n "${PAGER+set}" ]; then
920 TG_PAGER="$PAGER"
921 else
922 _gp="$(git var GIT_PAGER 2>/dev/null || :)"
923 [ "$_gp" != ":" ] || _gp=
924 TG_PAGER="${_gp:-less}"
926 if [ -z "$TG_PAGER" ]; then
927 emptypager=1
928 TG_PAGER=cat
930 else
931 emptypager=1
932 TG_PAGER=cat
935 # Set pager default environment variables
936 # see pager.c:setup_pager
937 if [ -z "${LESS+set}" ]; then
938 LESS="-FRX"
939 export LESS
941 if [ -z "${LV+set}" ]; then
942 LV="-c"
943 export LV
946 # this is needed so e.g. `git diff` will still colorize it's output if
947 # requested in ~/.gitconfig with color.diff=auto
948 GIT_PAGER_IN_USE=1
949 export GIT_PAGER_IN_USE
951 # this is needed so we don't get nested pagers
952 TG_PAGER_IN_USE=1
953 export TG_PAGER_IN_USE
956 # page eval_arg [arg ...]
958 # Calls setup_pager then evals the first argument passing it all the rest
959 # where the output is piped through eval "$TG_PAGER" unless emptypager is set
960 # by setup_pager (in which case the output is left as-is).
962 # To handle arbitrary paging duties, collect lines to be paged into a
963 # function and then call page with the function name or perhaps func_name "$@".
965 # If no arguments at all are passed in do nothing (return with success).
966 page()
968 [ $# -gt 0 ] || return 0
969 setup_pager
970 _evalarg="$1"; shift
971 if [ -n "$emptypager" ]; then
972 eval "$_evalarg" '"$@"'
973 else
974 eval "$_evalarg" '"$@"' | eval "$TG_PAGER"
978 # get_temp NAME [-d]
979 # creates a new temporary file (or directory with -d) in the global
980 # temporary directory $tg_tmp_dir with pattern prefix NAME
981 get_temp()
983 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
986 # automatically called by strftime
987 # does nothing if already setup
988 # may be called explicitly if the first call would otherwise be in a subshell
989 # so that the setup is only done once before subshells start being spawned
990 setup_strftime()
992 [ -z "$strftime_is_setup" ] || return 0
994 # date option to format raw epoch seconds values
995 daterawopt=
996 _testes='951807788'
997 _testdt='2000-02-29 07:03:08 UTC'
998 _testfm='%Y-%m-%d %H:%M:%S %Z'
999 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1000 daterawopt='-d@'
1001 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
1002 daterawopt='-r'
1004 strftime_is_setup=1
1007 # $1 => strftime format string to use
1008 # $2 => raw timestamp as seconds since epoch
1009 # $3 => optional time zone string (empty/absent for local time zone)
1010 strftime()
1012 setup_strftime
1013 if [ -n "$daterawopt" ]; then
1014 if [ -n "$3" ]; then
1015 TZ="$3" date "$daterawopt$2" "+$1"
1016 else
1017 date "$daterawopt$2" "+$1"
1019 else
1020 if [ -n "$3" ]; then
1021 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1022 else
1023 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
1028 ## Initial setup
1029 initial_setup()
1031 # suppress the merge log editor feature since git 1.7.10
1033 GIT_MERGE_AUTOEDIT=no
1034 export GIT_MERGE_AUTOEDIT
1035 git_dir="$(git rev-parse --git-dir)"
1036 root_dir="$(git rev-parse --show-cdup)"; root_dir="${root_dir:-.}"
1037 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null || :)"
1038 [ "$logrefupdates" = "true" ] || logrefupdates=
1039 tgsequester="$(git config --bool topgit.sequester 2>/dev/null || :)"
1040 tgnosequester=
1041 [ "$tgsequester" != "false" ] || tgnosequester=1
1042 unset tgsequester
1044 # make sure root_dir doesn't end with a trailing slash.
1046 root_dir="${root_dir%/}"
1047 [ -n "$base_remote" ] || base_remote="$(git config topgit.remote 2>/dev/null)" || :
1049 # make sure global cache directory exists inside GIT_DIR
1051 tg_cache_dir="$git_dir/tg-cache"
1052 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir"
1054 # create global temporary directories, inside GIT_DIR
1056 tg_tmp_dir=
1057 trap 'rm -rf "$tg_tmp_dir"' EXIT
1058 trap 'exit 129' HUP
1059 trap 'exit 130' INT
1060 trap 'exit 131' QUIT
1061 trap 'exit 134' ABRT
1062 trap 'exit 143' TERM
1063 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX")"
1064 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1067 # return the "realpath" for the item except the leaf is not resolved if it's
1068 # a symbolic link. The directory part must exist, but the basename need not.
1069 get_abs_path()
1071 [ -n "$1" -a -d "$(dirname -- "$1")" ] || return 1
1072 printf '%s' "$(cd -- "$(dirname -- "$1")" && pwd -P)/$(basename -- "$1")"
1075 ## Startup
1077 [ -d "@cmddir@" ] ||
1078 die "No command directory: '@cmddir@'"
1080 if [ -n "$tg__include" ]; then
1082 # We were sourced from another script for our utility functions;
1083 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1084 # work as expected in every shell. See http://bugs.debian.org/516188
1086 # ensure setup happens
1088 initial_setup
1090 else
1092 set -e
1094 tg="$0"
1095 tgdir="$(dirname -- "$tg")/"
1096 tgname="$(basename -- "$tg")"
1097 [ "$0" != "$tgname" ] || tgdir=""
1099 # If tg contains a '/' but does not start with one then replace it with an absolute path
1101 case "$0" in /*) :;; */*)
1102 tgdir="$(cd "$(dirname -- "$0")" && pwd -P)/"
1103 tg="$tgdir$tgname"
1104 esac
1106 # If the tg in the PATH is the same as "$tg" just display the basename
1107 # tgdisplay will include any explicit -C <dir> option whereas tg will not
1109 tgdisplaydir="$tgdir"
1110 tgdisplay="$tg"
1111 if [ "$(get_abs_path "$tg")" = "$(get_abs_path "$(which "$tgname" || :)" || :)" ]; then
1112 tgdisplaydir=""
1113 tgdisplay="$tgname"
1116 explicit_remote=
1117 explicit_dir=
1118 gitcdopt=
1119 noremote=
1121 cmd=
1122 while :; do case "$1" in
1124 help|--help|-h)
1125 cmd=help
1126 shift
1127 break;;
1129 --hooks-path)
1130 cmd=hooks-path
1131 shift
1132 break;;
1135 shift
1136 if [ -z "$1" ]; then
1137 echo "Option -r requires an argument." >&2
1138 do_help
1139 exit 1
1141 unset noremote
1142 base_remote="$1"
1143 explicit_remote="$base_remote"
1144 tg="$tgdir$tgname -r $explicit_remote"
1145 tgdisplay="$tgdisplaydir$tgname"
1146 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1147 tgdisplay="$tgdisplay -r $explicit_remote"
1148 shift;;
1151 unset base_remote explicit_remote
1152 noremote=1
1153 tg="$tgdir$tgname -u"
1154 tgdisplay="$tgdisplaydir$tgname"
1155 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1156 tgdisplay="$tgdisplay -u"
1157 shift;;
1160 shift
1161 if [ -z "$1" ]; then
1162 echo "Option -C requires an argument." >&2
1163 do_help
1164 exit 1
1166 cd "$1"
1167 unset GIT_DIR
1168 explicit_dir="$1"
1169 gitcdopt=" -C \"$explicit_dir\""
1170 tg="$tgdir$tgname"
1171 tgdisplay="$tgdisplaydir$tgname -C \"$explicit_dir\""
1172 [ -z "$explicit_remote" ] || tg="$tg -r $explicit_remote"
1173 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
1174 [ -z "$noremote" ] || tg="$tg -u"
1175 [ -z "$noremote" ] || tg="$tgdisplay -u"
1176 shift;;
1179 shift
1180 if [ -z "$1" ]; then
1181 echo "Option -c requires an argument." >&2
1182 do_help
1183 exit 1
1185 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
1186 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
1187 export GIT_CONFIG_PARAMETERS
1188 shift;;
1191 shift
1192 break;;
1195 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
1196 do_help
1197 exit 1;;
1200 break;;
1202 esac; done
1204 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
1206 ## Dispatch
1208 [ -n "$cmd" ] || { do_help; exit 1; }
1210 case "$cmd" in
1212 help)
1213 do_help "$@"
1214 exit 0;;
1216 hooks-path)
1217 # Internal command
1218 echo "@hooksdir@";;
1221 [ -r "@cmddir@"/tg-$cmd ] || {
1222 echo "Unknown subcommand: $cmd" >&2
1223 do_help
1224 exit 1
1227 initial_setup
1228 [ -z "$noremote" ] || unset base_remote
1230 nomergesetup=
1231 case "$cmd" in info|log|summary|rebase|revert|tag)
1232 # avoid merge setup where not necessary
1234 nomergesetup=1
1235 esac
1237 if [ -z "$nomergesetup" ]; then
1238 # make sure merging the .top* files will always behave sanely
1240 setup_ours
1241 setup_hook "pre-commit"
1244 _use_ref_cache=
1245 tg_read_only=1
1246 case "$cmd" in
1247 summary|info|export|tag)
1248 _use_ref_cache=1;;
1249 annihilate|create|delete|depend|import|update)
1250 tg_read_only=;;
1251 esac
1252 [ -z "$_use_ref_cache" ] || create_ref_cache
1254 . "@cmddir@"/tg-$cmd;;
1255 esac
1259 # vim:noet