tg-create: support new options and behavior
[topgit/pro.git] / tg.sh
blob9bdefd13aa89a0b3157dd0e7ef7a62f395ed531a
1 #!/bin/sh
2 # TopGit - A different patch queue manager
3 # (C) Petr Baudis <pasky@suse.cz> 2008
4 # (C) Kyle J. McKay <mackyle@gmail.com> 2014,2015
5 # GPLv2
7 TG_VERSION=0.18.1
9 # Update if you add any code that requires a newer version of git
10 GIT_MINIMUM_VERSION=1.7.7.2
12 ## SHA-1 pattern
14 octet='[0-9a-f][0-9a-f]'
15 octet4="$octet$octet$octet$octet"
16 octet19="$octet4$octet4$octet4$octet4$octet$octet$octet"
17 octet20="$octet4$octet4$octet4$octet4$octet4"
19 ## Auxiliary functions
21 info()
23 echo "${TG_RECURSIVE}${tgname:-tg}: $*"
26 warn()
28 info "warning: $*" >&2
31 die()
33 info "fatal: $*" >&2
34 exit 1
37 wc_l()
39 echo $(wc -l)
42 compare_versions()
44 separator="$1"
45 echo "$3" | tr "${separator}" '\n' | (for l in $(echo "$2"|tr "${separator}" ' '); do
46 read r || return 0
47 [ $l -ge $r ] || return 1
48 [ $l -gt $r ] && return 0
49 done)
52 precheck() {
53 git_ver="$(git version | sed -e 's/^[^0-9][^0-9]*//')"
54 compare_versions . "${git_ver%%[!0-9.]*}" "${GIT_MINIMUM_VERSION}" \
55 || die "git version >= ${GIT_MINIMUM_VERSION} required"
58 case "$1" in version|--version|-V)
59 echo "TopGit version $TG_VERSION"
60 exit 0
61 esac
63 precheck
64 [ "$1" = "precheck" ] && exit 0
67 cat_depsmsg_internal()
69 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
70 if [ -s "$tg_cache_dir/$1/.$2" ]; then
71 if read _rev_match && [ "$_rev" = "$_rev_match" ]; then
72 _line=
73 while IFS= read -r _line || [ -n "$_line" ]; do
74 printf '%s\n' "$_line"
75 done
76 return 0
77 fi <"$tg_cache_dir/$1/.$2"
79 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null || :
80 if [ -d "$tg_cache_dir/$1" ]; then
81 printf '%s\n' "$_rev" >"$tg_cache_dir/$1/.$2"
82 _line=
83 git cat-file blob "$_rev:.$2" 2>/dev/null |
84 while IFS= read -r _line || [ -n "$_line" ]; do
85 printf '%s\n' "$_line" >&3
86 printf '%s\n' "$_line"
87 done 3>>"$tg_cache_dir/$1/.$2"
88 else
89 git cat-file blob "$_rev:.$2" 2>/dev/null
93 # cat_deps BRANCHNAME
94 # Caches result
95 cat_deps()
97 cat_depsmsg_internal "$1" topdeps
100 # cat_msg BRANCHNAME
101 # Caches result
102 cat_msg()
104 cat_depsmsg_internal "$1" topmsg
107 # cat_file TOPIC:PATH [FROM]
108 # cat the file PATH from branch TOPIC when FROM is empty.
109 # FROM can be -i or -w, than the file will be from the index or worktree,
110 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
111 cat_file()
113 path="$1"
114 case "$2" in
116 cat "$root_dir/${path#*:}"
119 # ':file' means cat from index
120 git cat-file blob ":${path#*:}"
123 case "$path" in
124 refs/heads/*:.topdeps)
125 _temp="${path%:.topdeps}"
126 cat_deps "${_temp#refs/heads/}"
128 refs/heads/*:.topmsg)
129 _temp="${path%:.topmsg}"
130 cat_msg "${_temp#refs/heads/}"
133 git cat-file blob "$path"
135 esac
138 die "Wrong argument to cat_file: '$2'"
140 esac
143 # get tree for the committed topic
144 get_tree_()
146 echo "refs/heads/$1"
149 # get tree for the base
150 get_tree_b()
152 echo "refs/top-bases/$1"
155 # get tree for the index
156 get_tree_i()
158 git write-tree
161 # get tree for the worktree
162 get_tree_w()
164 i_tree=$(git write-tree)
166 # the file for --index-output needs to sit next to the
167 # current index file
168 cd "$root_dir"
169 : ${GIT_INDEX_FILE:="$git_dir/index"}
170 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
171 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
172 GIT_INDEX_FILE="$TMP_INDEX" &&
173 export GIT_INDEX_FILE &&
174 git diff --name-only -z HEAD |
175 git update-index -z --add --remove --stdin &&
176 git write-tree &&
177 rm -f "$TMP_INDEX"
181 # strip_ref "$(git symbolic-ref HEAD)"
182 # Output will have a leading refs/heads/ or refs/top-bases/ stripped if present
183 strip_ref()
185 case "$1" in
186 refs/heads/*)
187 echo "${1#refs/heads/}"
189 refs/top-bases/*)
190 echo "${1#refs/top-bases/}"
193 echo "$1"
194 esac
197 # pretty_tree NAME [-b | -i | -w]
198 # Output tree ID of a cleaned-up tree without tg's artifacts.
199 # NAME will be ignored for -i and -w, but needs to be present
200 pretty_tree()
202 name=$1
203 source=${2#?}
204 git ls-tree --full-tree "$(get_tree_$source "$name")" |
205 LC_ALL=C sed -ne '/ \.top.*$/!p' |
206 git mktree
209 # setup_hook NAME
210 setup_hook()
212 tgname="$(basename "$0")"
213 hook_call="\"\$(\"$tgname\" --hooks-path)\"/$1 \"\$@\""
214 if [ -f "$git_dir/hooks/$1" ] && fgrep -q "$hook_call" "$git_dir/hooks/$1"; then
215 # Another job well done!
216 return
218 # Prepare incantation
219 hook_chain=
220 if [ -s "$git_dir/hooks/$1" -a -x "$git_dir/hooks/$1" ]; then
221 hook_call="$hook_call"' || exit $?'
222 if ! LC_ALL=C sed -n 1p <"$git_dir/hooks/$1" | LC_ALL=C fgrep -qx "#!@SHELL_PATH@"; then
223 chain_num=
224 while [ -e "$git_dir/hooks/$1-chain$chain_num" ]; do
225 chain_num=$(( $chain_num + 1 ))
226 done
227 cp -p "$git_dir/hooks/$1" "$git_dir/hooks/$1-chain$chain_num"
228 hook_chain=1
230 else
231 hook_call="exec $hook_call"
233 # Don't call hook if tg is not installed
234 hook_call="if which \"$tgname\" > /dev/null; then $hook_call; fi"
235 # Insert call into the hook
237 echo "#!@SHELL_PATH@"
238 echo "$hook_call"
239 if [ -n "$hook_chain" ]; then
240 echo "exec \"\$0-chain$chain_num\" \"\$@\""
241 else
242 [ ! -s "$git_dir/hooks/$1" ] || cat "$git_dir/hooks/$1"
244 } >"$git_dir/hooks/$1+"
245 chmod a+x "$git_dir/hooks/$1+"
246 mv "$git_dir/hooks/$1+" "$git_dir/hooks/$1"
249 # setup_ours (no arguments)
250 setup_ours()
252 if [ ! -s "$git_dir/info/attributes" ] || ! grep -q topmsg "$git_dir/info/attributes"; then
253 [ -d "$git_dir/info" ] || mkdir "$git_dir/info"
255 echo ".topmsg merge=ours"
256 echo ".topdeps merge=ours"
257 } >>"$git_dir/info/attributes"
259 if ! git config merge.ours.driver >/dev/null; then
260 git config merge.ours.name '"always keep ours" merge driver'
261 git config merge.ours.driver 'touch %A'
265 # measure_branch NAME [BASE]
266 measure_branch()
268 _bname="$1"; _base="$2"
269 [ -n "$_base" ] || _base="refs/top-bases/$_bname"
270 # The caller should've verified $name is valid
271 _commits="$(git rev-list "$_bname" ^"$_base" -- | wc_l)"
272 _nmcommits="$(git rev-list --no-merges "$_bname" ^"$_base" -- | wc_l)"
273 if [ $_commits -ne 1 ]; then
274 _suffix="commits"
275 else
276 _suffix="commit"
278 echo "$_commits/$_nmcommits $_suffix"
281 # branch_contains B1 B2
282 # Whether B1 is a superset of B2.
283 branch_contains()
285 _revb1="$(ref_exists_rev "$1")" || return 0
286 _revb2="$(ref_exists_rev "$2")" || return 0
287 if [ -s "$tg_cache_dir/$1/.bc/$2/.d" ]; then
288 if read _result _rev_matchb1 _rev_matchb2 && \
289 [ "$_revb1" = "$_rev_matchb1" -a "$_revb2" = "$_rev_matchb2" ]; then
290 return $_result
291 fi <"$tg_cache_dir/$1/.bc/$2/.d"
293 [ -d "$tg_cache_dir/$1/.bc/$2" ] || mkdir -p "$tg_cache_dir/$1/.bc/$2" 2>/dev/null || :
294 _result=0
295 [ -z "$(git rev-list --max-count=1 ^"$_revb1" "$_revb2" --)" ] || _result=$?
296 if [ -d "$tg_cache_dir/$1/.bc/$2" ]; then
297 echo "$_result" "$_revb1" "$_revb2" >"$tg_cache_dir/$1/.bc/$2/.d"
299 return $_result
302 create_ref_dirs()
304 [ ! -s "$tg_tmp_dir/tg~ref-dirs-created" -a -s "$tg_ref_cache" ] || return 0
305 sed -e 's/ .*$//;'"s~^~$tg_tmp_dir/cached/~" <"$tg_ref_cache" | xargs mkdir -p
306 echo 1 >"$tg_tmp_dir/tg~ref-dirs-created"
309 # If the first argument is non-empty, outputs "1" if this call created the cache
310 create_ref_cache()
312 [ -n "$tg_ref_cache" -a ! -s "$tg_ref_cache" ] || return 0
313 _remotespec=
314 [ -z "$base_remote" ] || _remotespec="refs/remotes/$base_remote"
315 [ -z "$1" ] || printf '1'
316 git for-each-ref --format='%(refname) %(objectname)' \
317 refs/heads refs/top-bases $_remotespec >"$tg_ref_cache"
318 create_ref_dirs
321 remove_ref_cache()
323 [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ] || return 0
324 >"$tg_ref_cache"
327 # setting tg_ref_cache_only to non-empty will force non-$tg_ref_cache lookups to fail
328 rev_parse()
330 if [ -n "$tg_ref_cache" -a -s "$tg_ref_cache" ]; then
331 LC_ALL=C awk -v r="$1" 'BEGIN {e=1}; $1 == r {print $2; e=0; exit}; END {exit e}' <"$tg_ref_cache"
332 else
333 [ -z "$tg_ref_cache_only" ] || return 1
334 git rev-parse --quiet --verify "$1" -- 2>/dev/null
338 # ref_exists_rev REF
339 # Whether REF is a valid ref name
340 # REF must be fully qualified and start with refs/heads/, refs/top-bases/
341 # or, if $base_remote is set, refs/remotes/$base_remote/
342 # Caches result if $tg_read_only and outputs HASH on success
343 ref_exists_rev()
345 case "$1" in
346 refs/*)
348 $octet20)
349 printf '%s' "$1"
350 return;;
352 die "ref_exists_rev requires fully-qualified ref name"
353 esac
354 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify "$1" -- 2>/dev/null; return; }
355 _result=
356 _result_rev=
357 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.ref"; } 2>/dev/null || :
358 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
359 _result_rev="$(rev_parse "$1")"
360 _result=$?
361 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
362 [ ! -d "$tg_tmp_dir/cached/$1" ] || \
363 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.ref" 2>/dev/null || :
364 printf '%s' "$_result_rev"
365 return $_result
368 # Same as ref_exists_rev but output is abbreviated hash
369 ref_exists_rev_short()
371 case "$1" in
372 refs/*)
374 $octet20)
377 die "ref_exists_rev_short requires fully-qualified ref name"
378 esac
379 [ -n "$tg_read_only" ] || { git rev-parse --quiet --verify --short "$1" -- 2>/dev/null; return; }
380 _result=
381 _result_rev=
382 { read -r _result _result_rev <"$tg_tmp_dir/cached/$1/.rfs"; } 2>/dev/null || :
383 [ -z "$_result" ] || { printf '%s' "$_result_rev"; return $_result; }
384 _result_rev="$(rev_parse "$1")"
385 _result=$?
386 if [ $_result -eq 0 ]; then
387 _result_rev="$(git rev-parse --verify --short --quiet "$_result_rev" --)"
388 _result=$?
390 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null
391 [ ! -d "$tg_tmp_dir/cached/$1" ] || \
392 echo $_result $_result_rev >"$tg_tmp_dir/cached/$1/.rfs" 2>/dev/null || :
393 printf '%s' "$_result_rev"
394 return $_result
397 # ref_exists REF
398 # Whether REF is a valid ref name
399 # REF must be fully qualified and start with refs/heads/, refs/top-bases/
400 # or, if $base_remote is set, refs/remotes/$base_remote/
401 # Caches result
402 ref_exists()
404 ref_exists_rev "$1" >/dev/null
407 # rev_parse_tree REF
408 # Runs git rev-parse REF^{tree}
409 # Caches result if $tg_read_only
410 rev_parse_tree()
412 [ -n "$tg_read_only" ] || { git rev-parse --verify "$1^{tree}" -- 2>/dev/null; return; }
413 if [ -f "$tg_tmp_dir/cached/$1/.rpt" ]; then
414 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
415 printf '%s\n' "$_result"
416 return 0
418 return 1
420 [ -d "$tg_tmp_dir/cached/$1" ] || mkdir -p "$tg_tmp_dir/cached/$1" 2>/dev/null || :
421 if [ -d "$tg_tmp_dir/cached/$1" ]; then
422 git rev-parse --verify "$1^{tree}" -- >"$tg_tmp_dir/cached/$1/.rpt" 2>/dev/null || :
423 if IFS= read -r _result <"$tg_tmp_dir/cached/$1/.rpt"; then
424 printf '%s\n' "$_result"
425 return 0
427 return 1
429 git rev-parse --verify "$1^{tree}" -- 2>/dev/null
432 # has_remote BRANCH
433 # Whether BRANCH has a remote equivalent (accepts top-bases/ too)
434 has_remote()
436 [ -n "$base_remote" ] && ref_exists "refs/remotes/$base_remote/$1"
439 # Return the verified TopGit branch name or die with an error.
440 # As a convenience, if HEAD is given and HEAD is a symbolic ref to
441 # refs/heads/... then ... will be verified instead.
442 # if "$2" = "-f" then return an error rather than dying.
443 verify_topgit_branch()
445 case "$1" in
446 refs/heads/*)
447 _verifyname="${1#refs/heads/}"
449 refs/top-bases/*)
450 _verifyname="${1#refs/top-bases/}"
452 HEAD)
453 _verifyname="$(git symbolic-ref HEAD 2>/dev/null || :)"
454 [ -n "$_verifyname" ] || die "HEAD is not a symbolic ref"
455 case "$_verifyname" in refs/heads/*) :;; *)
456 [ "$2" != "-f" ] || return 1
457 die "HEAD is not a symbolic ref to the refs/heads namespace"
458 esac
459 _verifyname="${_verifyname#refs/heads/}"
462 _verifyname="$1"
464 esac
465 if ! ref_exists "refs/heads/$_verifyname"; then
466 [ "$2" != "-f" ] || return 1
467 die "no such branch: $_verifyname"
469 if ! ref_exists "refs/top-bases/$_verifyname"; then
470 [ "$2" != "-f" ] || return 1
471 die "not a TopGit-controlled branch: $_verifyname"
473 printf '%s' "$_verifyname"
476 # Caches result
477 # $1 = branch name (i.e. "t/foo/bar")
478 # $2 = optional result of rev-parse "refs/heads/$1"
479 # $3 = optional result of rev-parse "refs/top-bases/$1"
480 branch_annihilated()
482 _branch_name="$1"
483 _rev="${2:-$(ref_exists_rev "refs/heads/$_branch_name")}"
484 _rev_base="${3:-$(ref_exists_rev "refs/top-bases/$_branch_name")}"
486 _result=
487 _result_rev=
488 _result_rev_base=
489 { read -r _result _result_rev _result_rev_base <"$tg_cache_dir/$_branch_name/.ann"; } 2>/dev/null || :
490 [ -z "$_result" -o "$_result_rev" != "$_rev" -o "$_result_rev_base" != "$_rev_base" ] || return $_result
492 # use the merge base in case the base is ahead.
493 mb="$(git merge-base "$_rev_base" "$_rev" 2>/dev/null)"
495 test -z "$mb" || test "$(rev_parse_tree "$mb")" = "$(rev_parse_tree "$_rev")"
496 _result=$?
497 [ -d "$tg_cache_dir/$_branch_name" ] || mkdir -p "$tg_cache_dir/$_branch_name" 2>/dev/null
498 [ ! -d "$tg_cache_dir/$_branch_name" ] || \
499 echo $_result $_rev $_rev_base >"$tg_cache_dir/$_branch_name/.ann" 2>/dev/null || :
500 return $_result
503 non_annihilated_branches()
505 git for-each-ref --format='%(objectname) %(refname)' refs/top-bases |
506 while read rev ref; do
507 name="${ref#refs/top-bases/}"
508 if branch_annihilated "$name" "" "$rev"; then
509 continue
511 echo "$name"
512 done
515 # Make sure our tree is clean
516 ensure_clean_tree()
518 git update-index --ignore-submodules --refresh ||
519 die "the working directory has uncommitted changes (see above) - first commit or reset them"
520 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
521 die "the index has uncommited changes"
524 # is_sha1 REF
525 # Whether REF is a SHA1 (compared to a symbolic name).
526 is_sha1()
528 case "$1" in $octet20) return 0;; esac
529 return 1
532 # recurse_deps_internal NAME [BRANCHPATH...]
533 # get recursive list of dependencies with leading 0 if branch exists 1 if missing
534 # followed by a 1 if the branch is "tgish" or a 0 if not
535 # then the branch name followed by its depedency chain (which might be empty)
536 # An output line might look like this:
537 # 0 1 t/foo/leaf t/foo/int t/stage
538 # If no_remotes is non-empty, exclude remotes
539 # If recurse_preorder is non-empty, do a preorder rather than postorder traversal
540 # any branch names in the space-separated recurse_deps_exclude variable
541 # are skipped (along with their dependencies)
542 recurse_deps_internal()
544 case " $recurse_deps_exclude " in *" $1 "*) return 0; esac
545 _ref_hash=
546 if ! _ref_hash="$(ref_exists_rev "refs/heads/$1")"; then
547 [ -z "$2" ] || echo "1 0 $*"
548 return
551 # If no_remotes is unset also check our base against remote base.
552 # Checking our head against remote head has to be done in the helper.
553 if test -z "$no_remotes" && has_remote "top-bases/$1"; then
554 echo "0 0 refs/remotes/$base_remote/top-bases/$1 $*"
557 _is_tgish=0
558 _ref_hash_base=
559 ! _ref_hash_base="$(ref_exists_rev "refs/top-bases/$1")" || _is_tgish=1
560 [ -z "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
562 # if the branch was annihilated, it is considered to have no dependencies
563 if [ -n "$_is_tgish" ] && ! branch_annihilated "$1" "$_ref_hash" "$_ref_hash_base"; then
564 #TODO: handle nonexisting .topdeps?
565 cat_deps "$1" |
566 while read _dname; do
567 # Shoo shoo, leave our environment alone!
568 (recurse_deps_internal "$_dname" "$@")
569 done
572 [ -n "$recurse_preorder" -o -z "$2" ] || echo "0 $_is_tgish $*"
575 # do_eval CMD
576 # helper for recurse_deps so that a return statement executed inside CMD
577 # does not return from recurse_deps. This shouldn't be necessary, but it
578 # seems that it actually is.
579 do_eval()
581 eval "$@"
584 # becomes read-only for caching purposes
585 # assigns new value to tg_read_only
586 # become_cacheable/undo_become_cacheable calls may be nested
587 become_cacheable()
589 _old_tg_read_only="$tg_read_only"
590 if [ -z "$tg_read_only" ]; then
591 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
592 tg_read_only=1
594 _my_ref_cache="$(create_ref_cache 1)"
595 _my_ref_cache="${_my_ref_cache:+1}"
596 tg_read_only="undo${_my_ref_cache:-0}-$_old_tg_read_only"
599 # restores tg_read_only and ref_cache to state before become_cacheable call
600 # become_cacheable/undo_bocome_cacheable calls may be nested
601 undo_become_cacheable()
603 case "$tg_read_only" in
604 "undo"[01]"-"*)
605 _suffix="${tg_read_only#undo?-}"
606 [ "${tg_read_only%$_suffix}" = "undo0-" ] || remove_ref_cache
607 tg_read_only="$_suffix"
608 esac
611 # just call this, no undo, sets tg_read_only= and removes ref cache and cached results
612 become_non_cacheable()
614 remove_ref_cache
615 tg_read_only=
616 rm -rf "$tg_tmp_dir/cached" "$tg_tmp_dir/tg~ref-dirs-created"
619 # recurse_deps CMD NAME [BRANCHPATH...]
620 # Recursively eval CMD on all dependencies of NAME.
621 # Dependencies are visited in topological order.
622 # CMD can refer to $_name for queried branch name,
623 # $_dep for dependency name,
624 # $_depchain for space-seperated branch backtrace,
625 # $_dep_missing boolean to check whether $_dep is present
626 # and the $_dep_is_tgish boolean.
627 # It can modify $_ret to affect the return value
628 # of the whole function.
629 # If recurse_deps() hits missing dependencies, it will append
630 # them to space-separated $missing_deps list and skip them
631 # after calling CMD with _dep_missing set.
632 # remote dependencies are processed if no_remotes is unset.
633 # any branch names in the space-separated recurse_deps_exclude variable
634 # are skipped (along with their dependencies)
635 recurse_deps()
637 _cmd="$1"; shift
639 become_cacheable
640 _depsfile="$(get_temp tg-depsfile)"
641 recurse_deps_internal "$@" >>"$_depsfile"
642 undo_become_cacheable
644 _ret=0
645 while read _ismissing _istgish _dep _name _deppath; do
646 _depchain="$_name${_deppath:+ $_deppath}"
647 _dep_is_tgish=
648 [ "$_istgish" = "0" ] || _dep_is_tgish=1
649 _dep_missing=
650 if [ "$_ismissing" != "0" ]; then
651 _dep_missing=1
652 case " $missing_deps " in *" $_dep "*) :;; *)
653 missing_deps="${missing_deps:+$missing_deps }$_dep"
654 esac
656 do_eval "$_cmd"
657 done <"$_depsfile"
658 rm -f "$_depsfile"
659 return $_ret
662 # branch_needs_update
663 # This is a helper function for determining whether given branch
664 # is up-to-date wrt. its dependencies. It expects input as if it
665 # is called as a recurse_deps() helper.
666 # In case the branch does need update, it will echo it together
667 # with the branch backtrace on the output (see needs_update()
668 # description for details) and set $_ret to non-zero.
669 branch_needs_update()
671 if [ -n "$_dep_missing" ]; then
672 echo "! $_dep $_depchain"
673 return 0
676 _dep_base_update=
677 if [ -n "$_dep_is_tgish" ]; then
678 branch_annihilated "$_dep" && return 0
680 if has_remote "$_dep"; then
681 branch_contains "refs/heads/$_dep" "refs/remotes/$base_remote/$_dep" || _dep_base_update=%
683 # This can possibly override the remote check result;
684 # we want to sync with our base first
685 branch_contains "refs/heads/$_dep" "refs/top-bases/$_dep" || _dep_base_update=:
688 if [ -n "$_dep_base_update" ]; then
689 # _dep needs to be synced with its base/remote
690 echo "$_dep_base_update $_dep $_depchain"
691 _ret=1
692 elif [ -n "$_name" ]; then
693 case "$_dep" in refs/*) _fulldep="$_dep";; *) _fulldep="refs/heads/$_dep";; esac
694 if ! branch_contains "refs/top-bases/$_name" "$_fulldep"; then
695 # Some new commits in _dep
696 echo "$_dep $_depchain"
697 _ret=1
702 # needs_update NAME
703 # This function is recursive; it outputs reverse path from NAME
704 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
705 # inner paths first. Innermost name can be ':' if the head is
706 # not in sync with the base, '%' if the head is not in sync
707 # with the remote (in this order of priority) or '!' if depednecy
708 # is missing.
709 # It will also return non-zero status if NAME needs update.
710 # If needs_update() hits missing dependencies, it will append
711 # them to space-separated $missing_deps list and skip them.
712 needs_update()
714 recurse_deps branch_needs_update "$1"
717 # branch_empty NAME [-i | -w]
718 branch_empty()
720 if [ -z "$2" ]; then
721 _rev="$(ref_exists_rev "refs/heads/$1")" || return 0
722 _result=
723 _result_rev=
724 { read -r _result _result_rev <"$tg_cache_dir/$1/.mt"; } 2>/dev/null || :
725 [ -z "$_result" -o "$_result_rev" != "$_rev" ] || return $_result
726 _result=0
727 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ] || _result=$?
728 [ -d "$tg_cache_dir/$1" ] || mkdir -p "$tg_cache_dir/$1" 2>/dev/null
729 [ ! -d "$tg_cache_dir/$1" ] || echo $_result $_rev >"$tg_cache_dir/$1/.mt"
730 return $_result
731 else
732 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" $2)" ]
736 # list_deps [-i | -w] [BRANCH]
737 # -i/-w apply only to HEAD
738 list_deps()
740 head_from=
741 [ "$1" != "-i" -a "$1" != "-w" ] || { head_from="$1"; shift; }
742 head="$(git symbolic-ref -q HEAD)" ||
743 head="..detached.."
745 git for-each-ref --format='%(objectname) %(refname)' refs/top-bases"${1:+/$1}" |
746 while read rev ref; do
747 name="${ref#refs/top-bases/}"
748 if branch_annihilated "$name" "" "$rev"; then
749 continue
752 from=$head_from
753 [ "refs/heads/$name" = "$head" ] ||
754 from=
755 cat_file "refs/heads/$name:.topdeps" $from | while read dep; do
756 dep_is_tgish=true
757 ref_exists "refs/top-bases/$dep" ||
758 dep_is_tgish=false
759 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
760 echo "$name $dep"
762 done
763 done
766 # switch_to_base NAME [SEED]
767 switch_to_base()
769 _base="refs/top-bases/$1"; _seed="$2"
770 # We have to do all the hard work ourselves :/
771 # This is like git checkout -b "$_base" "$_seed"
772 # (or just git checkout "$_base"),
773 # but does not create a detached HEAD.
774 git read-tree -u -m HEAD "${_seed:-$_base}"
775 [ -z "$_seed" ] || git update-ref "$_base" "$_seed"
776 git symbolic-ref HEAD "$_base"
779 # run editor with arguments
780 # the editor setting will be cached in $tg_editor (which is eval'd)
781 # result non-zero if editor fails or GIT_EDITOR cannot be determined
782 run_editor()
784 tg_editor="$GIT_EDITOR"
785 [ -n "$tg_editor" ] || tg_editor="$(git var GIT_EDITOR)" || return $?
786 eval "$tg_editor" '"$@"'
789 # Show the help messages.
790 do_help()
792 _www=
793 if [ "$1" = "-w" ]; then
794 _www=1
795 shift
797 if [ -z "$1" ] ; then
798 # This is currently invoked in all kinds of circumstances,
799 # including when the user made a usage error. Should we end up
800 # providing more than a short help message, then we should
801 # differentiate.
802 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
804 ## Build available commands list for help output
806 cmds=
807 sep=
808 for cmd in "@cmddir@"/tg-*; do
809 ! [ -r "$cmd" ] && continue
810 # strip directory part and "tg-" prefix
811 cmd="$(basename "$cmd")"
812 cmd="${cmd#tg-}"
813 cmds="$cmds$sep$cmd"
814 sep="|"
815 done
817 echo "TopGit version $TG_VERSION - A different patch queue manager"
818 echo "Usage: $tgname [-C <dir>] [-r <remote> | -u] [-c <name>=<val>] ($cmds) ..."
819 echo " Or: $tgname help [-w] [<command>]"
820 echo "Use \"$tgdisplaydir$tgname help tg\" for overview of TopGit"
821 elif [ -r "@cmddir@"/tg-$1 -o -r "@sharedir@/tg-$1.txt" ] ; then
822 if [ -n "$_www" ]; then
823 nohtml=
824 if ! [ -r "@sharedir@/topgit.html" ]; then
825 echo "`basename $0`: missing html help file:" \
826 "@sharedir@/topgit.html" 1>&2
827 nohtml=1
829 if ! [ -r "@sharedir@/tg-$1.html" ]; then
830 echo "`basename $0`: missing html help file:" \
831 "@sharedir@/tg-$1.html" 1>&2
832 nohtml=1
834 if [ -n "$nohtml" ]; then
835 echo "`basename $0`: use" \
836 "\"`basename $0` help $1\" instead" 1>&2
837 exit 1
839 git web--browse -c help.browser "@sharedir@/tg-$1.html"
840 exit
842 setup_pager
844 if [ -r "@cmddir@"/tg-$1 ] ; then
845 "@cmddir@"/tg-$1 -h 2>&1 || :
846 echo
848 if [ -r "@sharedir@/tg-$1.txt" ] ; then
849 cat "@sharedir@/tg-$1.txt"
851 } | eval "$TG_PAGER"
852 else
853 echo "`basename $0`: no help for $1" 1>&2
854 do_help
855 exit 1
859 ## Pager stuff
861 # isatty FD
862 isatty()
864 test -t $1
867 # pass "diff" to get pager.diff
868 # if pager.$1 is a boolean false returns cat
869 # if set to true or unset fails
870 # otherwise succeeds and returns the value
871 get_pager()
873 if _x="$(git config --bool "pager.$1" 2>/dev/null)"; then
874 [ "$_x" != "true" ] || return 1
875 echo "cat"
876 return 0
878 if _x="$(git config "pager.$1" 2>/dev/null)"; then
879 echo "$_x"
880 return 0
882 return 1
885 # setup_pager
886 # Set TG_PAGER to a valid executable
887 # After calling, code to be paged should be surrounded with {...} | eval "$TG_PAGER"
888 # Preference is (same as Git):
889 # 1. GIT_PAGER
890 # 2. pager.$USE_PAGER_TYPE (but only if USE_PAGER_TYPE is set and so is pager.$USE_PAGER_TYPE)
891 # 3. core.pager (only if set)
892 # 4. PAGER
893 # 5. less
894 setup_pager()
896 isatty 1 || { TG_PAGER=cat; return 0; }
898 if [ -z "$TG_PAGER_IN_USE" ]; then
899 # TG_PAGER = GIT_PAGER | PAGER | less
900 # NOTE: GIT_PAGER='' is significant
901 if [ -n "${GIT_PAGER+set}" ]; then
902 TG_PAGER="$GIT_PAGER"
903 elif [ -n "$USE_PAGER_TYPE" ] && _dp="$(get_pager "$USE_PAGER_TYPE")"; then
904 TG_PAGER="$_dp"
905 elif _cp="$(git config core.pager 2>/dev/null)"; then
906 TG_PAGER="$_cp"
907 elif [ -n "${PAGER+set}" ]; then
908 TG_PAGER="$PAGER"
909 else
910 TG_PAGER="less"
912 : ${TG_PAGER:=cat}
913 else
914 TG_PAGER=cat
917 # Set pager default environment variables
918 # see pager.c:setup_pager
919 if [ -z "${LESS+set}" ]; then
920 LESS="-FRX"
921 export LESS
923 if [ -z "${LV+set}" ]; then
924 LV="-c"
925 export LV
928 # this is needed so e.g. `git diff` will still colorize it's output if
929 # requested in ~/.gitconfig with color.diff=auto
930 GIT_PAGER_IN_USE=1
931 export GIT_PAGER_IN_USE
933 # this is needed so we don't get nested pagers
934 TG_PAGER_IN_USE=1
935 export TG_PAGER_IN_USE
938 # get_temp NAME [-d]
939 # creates a new temporary file (or directory with -d) in the global
940 # temporary directory $tg_tmp_dir with pattern prefix NAME
941 get_temp()
943 mktemp $2 "$tg_tmp_dir/$1.XXXXXX"
946 # $1 => strftime format string to use
947 # $2 => raw timestamp as seconds since epoch
948 # $3 => optional time zone string (empty/absent for local time zone)
949 strftime()
951 if [ -n "$daterawopt" ]; then
952 if [ -n "$3" ]; then
953 TZ="$3" date "$daterawopt$2" "+$1"
954 else
955 date "$daterawopt$2" "+$1"
957 else
958 if [ -n "$3" ]; then
959 TZ="$3" perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
960 else
961 perl -MPOSIX=strftime -le 'print strftime($ARGV[0],localtime($ARGV[1]))' "$1" "$2"
966 ## Initial setup
967 initial_setup()
969 # suppress the merge log editor feature since git 1.7.10
971 GIT_MERGE_AUTOEDIT=no
972 export GIT_MERGE_AUTOEDIT
973 git_dir="$(git rev-parse --git-dir)"
974 root_dir="$(git rev-parse --show-cdup)"; root_dir="${root_dir:-.}"
975 logrefupdates="$(git config --bool core.logallrefupdates 2>/dev/null || :)"
976 [ "$logrefupdates" = "true" ] || logrefupdates=
978 # date option to format raw epoch seconds values
979 daterawopt=
980 _testes='951807788'
981 _testdt='2000-02-29 07:03:08 UTC'
982 _testfm='%Y-%m-%d %H:%M:%S %Z'
983 if [ "$(TZ=UTC date "-d@$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
984 daterawopt='-d@'
985 elif [ "$(TZ=UTC date "-r$_testes" "+$_testfm" 2>/dev/null)" = "$_testdt" ]; then
986 daterawopt='-r'
989 # make sure root_dir doesn't end with a trailing slash.
991 root_dir="${root_dir%/}"
992 [ -n "$base_remote" ] || base_remote="$(git config topgit.remote 2>/dev/null)" || :
994 # make sure global cache directory exists inside GIT_DIR
996 tg_cache_dir="$git_dir/tg-cache"
997 [ -d "$tg_cache_dir" ] || mkdir "$tg_cache_dir"
999 # create global temporary directories, inside GIT_DIR
1001 tg_tmp_dir=
1002 trap 'rm -rf "$tg_tmp_dir"' EXIT
1003 trap 'exit 129' HUP
1004 trap 'exit 130' INT
1005 trap 'exit 131' QUIT
1006 trap 'exit 134' ABRT
1007 trap 'exit 143' TERM
1008 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX")"
1009 tg_ref_cache="$tg_tmp_dir/tg~ref-cache"
1012 # return the "realpath" for the item except the leaf is not resolved if it's
1013 # a symbolic link. The directory part must exist, but the basename need not.
1014 get_abs_path()
1016 [ -n "$1" -a -d "$(dirname -- "$1")" ] || return 1
1017 printf '%s' "$(cd -- "$(dirname -- "$1")" && pwd -P)/$(basename -- "$1")"
1020 ## Startup
1022 [ -d "@cmddir@" ] ||
1023 die "No command directory: '@cmddir@'"
1025 if [ -n "$tg__include" ]; then
1027 # We were sourced from another script for our utility functions;
1028 # this is set by hooks. Skip the rest of the file. A simple return doesn't
1029 # work as expected in every shell. See http://bugs.debian.org/516188
1031 # ensure setup happens
1033 initial_setup
1035 else
1037 set -e
1039 tg="$0"
1040 tgdir="$(dirname -- "$tg")/"
1041 tgname="$(basename -- "$tg")"
1042 [ "$0" != "$tgname" ] || tgdir=""
1044 # If tg contains a '/' but does not start with one then replace it with an absolute path
1046 case "$0" in /*) :;; */*)
1047 tgdir="$(cd "$(dirname -- "$0")" && pwd -P)/"
1048 tg="$tgdir$tgname"
1049 esac
1051 # If the tg in the PATH is the same as "$tg" just display the basename
1052 # tgdisplay will include any explicit -C <dir> option whereas tg will not
1054 tgdisplaydir="$tgdir"
1055 tgdisplay="$tg"
1056 if [ "$(get_abs_path "$tg")" = "$(get_abs_path "$(which "$tgname" || :)" || :)" ]; then
1057 tgdisplaydir=""
1058 tgdisplay="$tgname"
1061 explicit_remote=
1062 explicit_dir=
1063 gitcdopt=
1064 noremote=
1066 cmd=
1067 while :; do case "$1" in
1069 help|--help|-h)
1070 cmd=help
1071 shift
1072 break;;
1074 --hooks-path)
1075 cmd=hooks-path
1076 shift
1077 break;;
1080 shift
1081 if [ -z "$1" ]; then
1082 echo "Option -r requires an argument." >&2
1083 do_help
1084 exit 1
1086 unset noremote
1087 base_remote="$1"
1088 explicit_remote="$base_remote"
1089 tg="$tgdir$tgname -r $explicit_remote"
1090 tgdisplay="$tgdisplaydir$tgname"
1091 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1092 tgdisplay="$tgdisplay -r $explicit_remote"
1093 shift;;
1096 unset base_remote explicit_remote
1097 noremote=1
1098 tg="$tgdir$tgname -u"
1099 tgdisplay="$tgdisplaydir$tgname"
1100 [ -z "$explicit_dir" ] || tgdisplay="$tgdisplay -C \"$explicit_dir\""
1101 tgdisplay="$tgdisplay -u"
1102 shift;;
1105 shift
1106 if [ -z "$1" ]; then
1107 echo "Option -C requires an argument." >&2
1108 do_help
1109 exit 1
1111 cd "$1"
1112 unset GIT_DIR
1113 explicit_dir="$1"
1114 gitcdopt=" -C \"$explicit_dir\""
1115 tg="$tgdir$tgname"
1116 tgdisplay="$tgdisplaydir$tgname -C \"$explicit_dir\""
1117 [ -z "$explicit_remote" ] || tg="$tg -r $explicit_remote"
1118 [ -z "$explicit_remote" ] || tgdisplay="$tgdisplay -r $explicit_remote"
1119 [ -z "$noremote" ] || tg="$tg -u"
1120 [ -z "$noremote" ] || tg="$tgdisplay -u"
1121 shift;;
1124 shift
1125 if [ -z "$1" ]; then
1126 echo "Option -c requires an argument." >&2
1127 do_help
1128 exit 1
1130 param="'$(printf '%s\n' "$1" | sed "s/[']/'\\\\''/g")'"
1131 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }$param"
1132 export GIT_CONFIG_PARAMETERS
1133 shift;;
1136 shift
1137 break;;
1140 echo "Invalid option $1 (subcommand options must appear AFTER the subcommand)." >&2
1141 do_help
1142 exit 1;;
1145 break;;
1147 esac; done
1149 [ -n "$cmd" -o $# -lt 1 ] || { cmd="$1"; shift; }
1151 ## Dispatch
1153 [ -n "$cmd" ] || { do_help; exit 1; }
1155 case "$cmd" in
1157 help)
1158 do_help "$@"
1159 exit 0;;
1161 hooks-path)
1162 # Internal command
1163 echo "@hooksdir@";;
1166 [ -r "@cmddir@"/tg-$cmd ] || {
1167 echo "Unknown subcommand: $cmd" >&2
1168 do_help
1169 exit 1
1172 initial_setup
1173 [ -z "$noremote" ] || unset base_remote
1175 nomergesetup=
1176 case "$cmd" in info|log|summary|rebase|revert|tag)
1177 # avoid merge setup where not necessary
1179 nomergesetup=1
1180 esac
1182 if [ -z "$nomergesetup" ]; then
1183 # make sure merging the .top* files will always behave sanely
1185 setup_ours
1186 setup_hook "pre-commit"
1189 _use_ref_cache=
1190 tg_read_only=1
1191 case "$cmd" in
1192 summary|info|export|tag)
1193 _use_ref_cache=1;;
1194 annihilate|create|delete|depend|import|update)
1195 tg_read_only=;;
1196 esac
1197 [ -z "$_use_ref_cache" ] || create_ref_cache
1199 . "@cmddir@"/tg-$cmd;;
1200 esac
1204 # vim:noet