help: make tg help tg work
[topgit/pro.git] / tg.sh
blob3a0f15844bbfe41c1bdd3675e2f1c69bf9122f05
1 #!/bin/sh
2 # TopGit - A different patch queue manager
3 # (c) Petr Baudis <pasky@suse.cz> 2008
4 # GPLv2
6 TG_VERSION=0.11
8 # Update if you add any code that requires a newer version of git
9 GIT_MINIMUM_VERSION=1.7.7.2
11 ## Auxiliary functions
13 info()
15 echo "${TG_RECURSIVE}tg: $*"
18 die()
20 info "fatal: $*" >&2
21 exit 1
24 compare_versions()
26 separator="$1"
27 echo "$3" | tr "${separator}" '\n' | (for l in $(echo "$2"|tr "${separator}" ' '); do
28 read r || return 0
29 [ $l -ge $r ] || return 1
30 [ $l -gt $r ] && return 0
31 done)
34 precheck() {
35 git_ver="$(git version | sed -e 's/^[^0-9][^0-9]*//')"
36 compare_versions . "${git_ver%%[!0-9.]*}" "${GIT_MINIMUM_VERSION}" \
37 || die "git version >= ${GIT_MINIMUM_VERSION} required"
40 case "$1" in version|--version|-V)
41 echo "TopGit version $TG_VERSION"
42 exit 0
43 esac
45 precheck
46 [ "$1" = "precheck" ] && exit 0
48 # cat_file TOPIC:PATH [FROM]
49 # cat the file PATH from branch TOPIC when FROM is empty.
50 # FROM can be -i or -w, than the file will be from the index or worktree,
51 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
52 cat_file()
54 path="$1"
55 case "${2-}" in
56 -w)
57 cat "$root_dir/${path#*:}"
59 -i)
60 # ':file' means cat from index
61 git cat-file blob ":${path#*:}"
63 '')
64 git cat-file blob "$path"
67 die "Wrong argument to cat_file: '$2'"
69 esac
72 # get tree for the committed topic
73 get_tree_()
75 echo "$1"
78 # get tree for the base
79 get_tree_b()
81 echo "refs/top-bases/$1"
84 # get tree for the index
85 get_tree_i()
87 git write-tree
90 # get tree for the worktree
91 get_tree_w()
93 i_tree=$(git write-tree)
95 # the file for --index-output needs to sit next to the
96 # current index file
97 : ${GIT_INDEX_FILE:="$git_dir/index"}
98 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
99 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
100 GIT_INDEX_FILE="$TMP_INDEX" &&
101 export GIT_INDEX_FILE &&
102 git diff --name-only -z HEAD |
103 git update-index -z --add --remove --stdin &&
104 git write-tree &&
105 rm -f "$TMP_INDEX"
109 # strip_ref "$(git symbolic-ref HEAD)"
110 # Output will have a leading refs/heads/ or refs/top-bases/ stripped if present
111 strip_ref()
113 case "$1" in
114 refs/heads/*)
115 echo "${1#refs/heads/}"
117 refs/top-bases/*)
118 echo "${1#refs/top-bases/}"
121 echo "$1"
122 esac
125 # pretty_tree NAME [-b | -i | -w]
126 # Output tree ID of a cleaned-up tree without tg's artifacts.
127 # NAME will be ignored for -i and -w, but needs to be present
128 pretty_tree()
130 name=$1
131 source=${2#?}
132 git ls-tree --full-tree "$(get_tree_$source "$name")" |
133 awk -F ' ' '$2 !~ /^.top/' |
134 git mktree
137 # setup_hook NAME
138 setup_hook()
140 hook_call="\"\$($tg --hooks-path)\"/$1 \"\$@\""
141 if [ -f "$git_dir/hooks/$1" ] &&
142 fgrep -q "$hook_call" "$git_dir/hooks/$1"; then
143 # Another job well done!
144 return
146 # Prepare incantation
147 if [ -x "$git_dir/hooks/$1" ]; then
148 hook_call="$hook_call"' || exit $?'
149 else
150 hook_call="exec $hook_call"
152 # Don't call hook if tg is not installed
153 hook_call="if which \"$tg\" > /dev/null; then $hook_call; fi"
154 # Insert call into the hook
156 echo "#!/bin/sh"
157 echo "$hook_call"
158 [ ! -s "$git_dir/hooks/$1" ] || cat "$git_dir/hooks/$1"
159 } >"$git_dir/hooks/$1+"
160 chmod a+x "$git_dir/hooks/$1+"
161 mv "$git_dir/hooks/$1+" "$git_dir/hooks/$1"
164 # setup_ours (no arguments)
165 setup_ours()
167 if [ ! -s "$git_dir/info/attributes" ] || ! grep -q topmsg "$git_dir/info/attributes"; then
169 echo ".topmsg merge=ours"
170 echo ".topdeps merge=ours"
171 } >>"$git_dir/info/attributes"
173 if ! git config merge.ours.driver >/dev/null; then
174 git config merge.ours.name '"always keep ours" merge driver'
175 git config merge.ours.driver 'touch %A'
179 # measure_branch NAME [BASE]
180 measure_branch()
182 _bname="$1"; _base="$2"
183 [ -n "$_base" ] || _base="refs/top-bases/$_bname"
184 # The caller should've verified $name is valid
185 _commits="$(git rev-list "$_bname" ^"$_base" -- | wc -l)"
186 _nmcommits="$(git rev-list --no-merges "$_bname" ^"$_base" -- | wc -l)"
187 if [ $_commits -gt 1 ]; then
188 _suffix="commits"
189 else
190 _suffix="commit"
192 echo "$_commits/$_nmcommits $_suffix"
195 # branch_contains B1 B2
196 # Whether B1 is a superset of B2.
197 branch_contains()
199 [ -z "$(git rev-list --max-count=1 ^"$1" "$2" --)" ]
202 # ref_exists REF
203 # Whether REF is a valid ref name
204 ref_exists()
206 git rev-parse --verify "$@" >/dev/null 2>&1
209 # has_remote BRANCH
210 # Whether BRANCH has a remote equivalent (accepts top-bases/ too)
211 has_remote()
213 [ -n "$base_remote" ] && ref_exists "remotes/$base_remote/$1"
216 branch_annihilated()
218 _branch_name="$1";
220 # use the merge base in case the base is ahead.
221 mb="$(git merge-base "refs/top-bases/$_branch_name" "$_branch_name" 2> /dev/null)";
223 test -z "$mb" || test "$(git rev-parse "$mb^{tree}")" = "$(git rev-parse "$_branch_name^{tree}")";
226 non_annihilated_branches()
228 _pattern="$@"
229 git for-each-ref ${_pattern:-refs/top-bases} |
230 while read rev type ref; do
231 name="${ref#refs/top-bases/}"
232 if branch_annihilated "$name"; then
233 continue
235 echo "$name"
236 done
239 # Make sure our tree is clean
240 ensure_clean_tree()
242 git update-index --ignore-submodules --refresh ||
243 die "the working directory has uncommitted changes (see above) - first commit or reset them"
244 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
245 die "the index has uncommited changes"
248 # is_sha1 REF
249 # Whether REF is a SHA1 (compared to a symbolic name).
250 is_sha1()
252 [ "$(git rev-parse "$1")" = "$1" ]
255 # recurse_deps CMD NAME [BRANCHPATH...]
256 # Recursively eval CMD on all dependencies of NAME.
257 # CMD can refer to $_name for queried branch name,
258 # $_dep for dependency name,
259 # $_depchain for space-seperated branch backtrace,
260 # $_dep_missing boolean to check whether $_dep is present
261 # and the $_dep_is_tgish boolean.
262 # It can modify $_ret to affect the return value
263 # of the whole function.
264 # If recurse_deps() hits missing dependencies, it will append
265 # them to space-separated $missing_deps list and skip them
266 # affter calling CMD with _dep_missing set.
267 # remote dependencies are processed if no_remotes is unset.
268 recurse_deps()
270 _cmd="$1"; shift
271 _name="$1"; # no shift
272 _depchain="$*"
274 _depsfile="$(get_temp tg-depsfile)"
275 # If no_remotes is unset check also our base against remote base.
276 # Checking our head against remote head has to be done in the helper.
277 if test -z "$no_remotes" && has_remote "top-bases/$_name"; then
278 echo "refs/remotes/$base_remote/top-bases/$_name" >>"$_depsfile"
281 # if the branch was annihilated, it is considered to have no dependencies
282 if ! branch_annihilated "$_name"; then
283 #TODO: handle nonexisting .topdeps?
284 git cat-file blob "$_name:.topdeps" >>"$_depsfile";
287 _ret=0
288 while read _dep; do
289 _dep_missing=
290 if ! ref_exists "$_dep" ; then
291 # All hope is lost. Inform driver and continue
292 missing_deps="$missing_deps $_dep"
293 _dep_missing=1
294 eval "$_cmd"
295 continue
298 _dep_is_tgish=1
299 ref_exists "refs/top-bases/$_dep" ||
300 _dep_is_tgish=
302 # Shoo shoo, keep our environment alone!
303 [ -z "$_dep_is_tgish" ] ||
304 (recurse_deps "$_cmd" "$_dep" "$@") ||
305 _ret=$?
307 eval "$_cmd"
308 done <"$_depsfile"
309 missing_deps="${missing_deps# }"
310 return $_ret
313 # branch_needs_update
314 # This is a helper function for determining whether given branch
315 # is up-to-date wrt. its dependencies. It expects input as if it
316 # is called as a recurse_deps() helper.
317 # In case the branch does need update, it will echo it together
318 # with the branch backtrace on the output (see needs_update()
319 # description for details) and set $_ret to non-zero.
320 branch_needs_update()
322 if [ -n "$_dep_missing" ]; then
323 echo "! $_depchain"
324 return 0
327 _dep_base_update=
328 if [ -n "$_dep_is_tgish" ]; then
329 branch_annihilated "$_dep" && return 0
331 if has_remote "$_dep"; then
332 branch_contains "$_dep" "refs/remotes/$base_remote/$_dep" || _dep_base_update=%
334 # This can possibly override the remote check result;
335 # we want to sync with our base first
336 branch_contains "$_dep" "refs/top-bases/$_dep" || _dep_base_update=:
339 if [ -n "$_dep_base_update" ]; then
340 # _dep needs to be synced with its base/remote
341 echo "$_dep_base_update $_dep $_depchain"
342 _ret=1
343 elif [ -n "$_name" ] && ! branch_contains "refs/top-bases/$_name" "$_dep"; then
344 # Some new commits in _dep
345 echo "$_dep $_depchain"
346 _ret=1
350 # needs_update NAME
351 # This function is recursive; it outputs reverse path from NAME
352 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
353 # inner paths first. Innermost name can be ':' if the head is
354 # not in sync with the base, '%' if the head is not in sync
355 # with the remote (in this order of priority) or '!' if depednecy
356 # is missing.
357 # It will also return non-zero status if NAME needs update.
358 # If needs_update() hits missing dependencies, it will append
359 # them to space-separated $missing_deps list and skip them.
360 needs_update()
362 recurse_deps branch_needs_update "$@"
365 # branch_empty NAME [-i | -w]
366 branch_empty()
368 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" ${2-})" ]
371 # list_deps [-i | -w]
372 # -i/-w apply only to HEAD
373 list_deps()
375 head_from=${1-}
376 head="$(git symbolic-ref -q HEAD)" ||
377 head="..detached.."
379 git for-each-ref refs/top-bases |
380 while read rev type ref; do
381 name="${ref#refs/top-bases/}"
382 if branch_annihilated "$name"; then
383 continue;
386 from=$head_from
387 [ "refs/heads/$name" = "$head" ] ||
388 from=
389 cat_file "$name:.topdeps" $from | while read dep; do
390 dep_is_tgish=true
391 ref_exists "refs/top-bases/$dep" ||
392 dep_is_tgish=false
393 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
394 echo "$name $dep"
396 done
397 done
400 # switch_to_base NAME [SEED]
401 switch_to_base()
403 _base="refs/top-bases/$1"; _seed="$2"
404 # We have to do all the hard work ourselves :/
405 # This is like git checkout -b "$_base" "$_seed"
406 # (or just git checkout "$_base"),
407 # but does not create a detached HEAD.
408 git read-tree -u -m HEAD "${_seed:-$_base}"
409 [ -z "$_seed" ] || git update-ref "$_base" "$_seed"
410 git symbolic-ref HEAD "$_base"
413 # Show the help messages.
414 do_help()
416 if [ -z "$1" ] ; then
417 # This is currently invoked in all kinds of circumstances,
418 # including when the user made a usage error. Should we end up
419 # providing more than a short help message, then we should
420 # differentiate.
421 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
423 ## Build available commands list for help output
425 cmds=
426 sep=
427 for cmd in "@cmddir@"/tg-*; do
428 ! [ -r "$cmd" ] && continue
429 # strip directory part and "tg-" prefix
430 cmd="$(basename "$cmd")"
431 cmd="${cmd#tg-}"
432 cmds="$cmds$sep$cmd"
433 sep="|"
434 done
436 echo "TopGit version $TG_VERSION - A different patch queue manager"
437 echo "Usage: tg ( help [<command>] | [-r <remote>] ($cmds) ...)"
438 echo "Use \"tg help tg\" for overview of TopGit"
439 elif [ -r "@cmddir@"/tg-$1 -o -r "@sharedir@/tg-$1.txt" ] ; then
440 setup_pager
442 if [ -r "@cmddir@"/tg-$1 ] ; then
443 "@cmddir@"/tg-$1 -h 2>&1 || :
444 echo
446 if [ -r "@sharedir@/tg-$1.txt" ] ; then
447 cat "@sharedir@/tg-$1.txt"
449 } | "$TG_PAGER"
450 else
451 echo "`basename $0`: no help for $1" 1>&2
452 do_help
453 exit 1
457 ## Pager stuff
459 # isatty FD
460 isatty()
462 test -t $1
465 # setup_pager
466 # Set TG_PAGER to a valid executable
467 # After calling, code to be paged should be surrounded with {...} | "$TG_PAGER"
468 setup_pager()
470 isatty 1 || { TG_PAGER=cat; return 0; }
472 if [ -z "$TG_PAGER_IN_USE" ]; then
473 # TG_PAGER = GIT_PAGER | PAGER | less
474 # NOTE: GIT_PAGER='' is significant
475 if [ -n "${GIT_PAGER+set}" ]; then
476 TG_PAGER="$GIT_PAGER"
477 elif [ -n "${PAGER+set}" ]; then
478 TG_PAGER="$PAGER"
479 else
480 TG_PAGER="less"
482 : ${TG_PAGER:=cat}
483 else
484 TG_PAGER=cat
487 # Set pager default environment variables
488 # see pager.c:setup_pager
489 if [ -z "${LESS+set}" ]; then
490 export LESS="-FRSX"
492 if [ -z "${LV+set}" ]; then
493 export LV="-c"
496 # this is needed so e.g. `git diff` will still colorize it's output if
497 # requested in ~/.gitconfig with color.diff=auto
498 export GIT_PAGER_IN_USE=1
500 # this is needed so we don't get nested pagers
501 export TG_PAGER_IN_USE=1
504 # get_temp NAME [-d]
505 # creates a new temporary file (or directory with -d) in the global
506 # temporary directory $tg_tmp_dir with pattern prefix NAME
507 get_temp()
509 mktemp ${2-} "$tg_tmp_dir/$1.XXXXXX"
512 ## Startup
514 [ -d "@cmddir@" ] ||
515 die "No command directory: '@cmddir@'"
517 ## Initial setup
519 cmd="$1"
520 [ -z "$tg__include" ] || cmd="include" # ensure setup happens
521 case "$cmd" in
522 help|--help|-h)
525 if [ -n "$cmd" ]; then
526 set -e
527 # suppress the merge log editor feature since git 1.7.10
528 export GIT_MERGE_AUTOEDIT=no
529 git_dir="$(git rev-parse --git-dir)"
530 root_dir="$(git rev-parse --show-cdup)"; root_dir="${root_dir:-.}"
531 # Make sure root_dir doesn't end with a trailing slash.
532 root_dir="${root_dir%/}"
533 base_remote="$(git config topgit.remote 2>/dev/null)" || :
534 tg="tg"
535 # make sure merging the .top* files will always behave sanely
536 setup_ours
537 setup_hook "pre-commit"
538 # create global temporary directories, inside GIT_DIR
539 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX")"
540 trap "rm -rf \"$tg_tmp_dir\"" EXIT
542 esac
544 ## Dispatch
546 # We were sourced from another script for our utility functions;
547 # this is set by hooks. Skip the rest of the file. A simple return doesn't
548 # work as expected in every shell. See http://bugs.debian.org/516188
549 if [ -z "$tg__include" ]; then
551 if [ "$1" = "-r" ]; then
552 shift
553 if [ -z "$1" ]; then
554 echo "Option -r requires an argument." >&2
555 do_help
556 exit 1
558 base_remote="$1"; shift
559 tg="$tg -r $base_remote"
560 cmd="$1"
563 [ -n "$cmd" ] || { do_help; exit 1; }
564 shift
566 case "$cmd" in
567 help|--help|-h)
568 do_help "$1"
569 exit 0;;
570 --hooks-path)
571 # Internal command
572 echo "@hooksdir@";;
574 [ -r "@cmddir@"/tg-$cmd ] || {
575 echo "Unknown subcommand: $cmd" >&2
576 do_help
577 exit 1
579 . "@cmddir@"/tg-$cmd;;
580 esac
584 # vim:noet