Build improvments
[topgit/pro.git] / tg.sh
blob3186a4796e4c6ffd284d5a05623bcfd5db9222d4
1 #!/bin/sh
2 # TopGit - A different patch queue manager
3 # (c) Petr Baudis <pasky@suse.cz> 2008
4 # GPLv2
6 TG_VERSION=0.9
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)
36 compare_versions . ${git_ver#git version} ${GIT_MINIMUM_VERSION} \
37 || die "git version >= " ${GIT_MINIMUM_VERSION} required
40 precheck
41 [ "$1" = "precheck" ] && exit 0
43 # cat_file TOPIC:PATH [FROM]
44 # cat the file PATH from branch TOPIC when FROM is empty.
45 # FROM can be -i or -w, than the file will be from the index or worktree,
46 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
47 cat_file()
49 path="$1"
50 case "${2-}" in
51 -w)
52 cat "$root_dir/${path#*:}"
54 -i)
55 # ':file' means cat from index
56 git cat-file blob ":${path#*:}"
58 '')
59 git cat-file blob "$path"
62 die "Wrong argument to cat_file: '$2'"
64 esac
67 # get tree for the committed topic
68 get_tree_()
70 echo "$1"
73 # get tree for the base
74 get_tree_b()
76 echo "refs/top-bases/$1"
79 # get tree for the index
80 get_tree_i()
82 git write-tree
85 # get tree for the worktree
86 get_tree_w()
88 i_tree=$(git write-tree)
90 # the file for --index-output needs to sit next to the
91 # current index file
92 : ${GIT_INDEX_FILE:="$git_dir/index"}
93 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
94 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
95 GIT_INDEX_FILE="$TMP_INDEX" &&
96 export GIT_INDEX_FILE &&
97 git diff --name-only -z HEAD |
98 git update-index -z --add --remove --stdin &&
99 git write-tree &&
100 rm -f "$TMP_INDEX"
104 # strip_ref "$(git symbolic-ref HEAD)"
105 # Output will have a leading refs/heads/ or refs/top-bases/ stripped if present
106 strip_ref()
108 case "$1" in
109 refs/heads/*)
110 echo "${1#refs/heads/}"
112 refs/top-bases/*)
113 echo "${1#refs/top-bases/}"
116 echo "$1"
117 esac
120 # pretty_tree NAME [-b | -i | -w]
121 # Output tree ID of a cleaned-up tree without tg's artifacts.
122 # NAME will be ignored for -i and -w, but needs to be present
123 pretty_tree()
125 name=$1
126 source=${2#?}
127 git ls-tree --full-tree "$(get_tree_$source "$name")" |
128 awk -F ' ' '$2 !~ /^.top/' |
129 git mktree
132 # setup_hook NAME
133 setup_hook()
135 hook_call="\"\$($tg --hooks-path)\"/$1 \"\$@\""
136 if [ -f "$git_dir/hooks/$1" ] &&
137 fgrep -q "$hook_call" "$git_dir/hooks/$1"; then
138 # Another job well done!
139 return
141 # Prepare incantation
142 if [ -x "$git_dir/hooks/$1" ]; then
143 hook_call="$hook_call"' || exit $?'
144 else
145 hook_call="exec $hook_call"
147 # Don't call hook if tg is not installed
148 hook_call="if which \"$tg\" > /dev/null; then $hook_call; fi"
149 # Insert call into the hook
151 echo "#!/bin/sh"
152 echo "$hook_call"
153 [ ! -s "$git_dir/hooks/$1" ] || cat "$git_dir/hooks/$1"
154 } >"$git_dir/hooks/$1+"
155 chmod a+x "$git_dir/hooks/$1+"
156 mv "$git_dir/hooks/$1+" "$git_dir/hooks/$1"
159 # setup_ours (no arguments)
160 setup_ours()
162 if [ ! -s "$git_dir/info/attributes" ] || ! grep -q topmsg "$git_dir/info/attributes"; then
164 echo ".topmsg merge=ours"
165 echo ".topdeps merge=ours"
166 } >>"$git_dir/info/attributes"
168 if ! git config merge.ours.driver >/dev/null; then
169 git config merge.ours.name '"always keep ours" merge driver'
170 git config merge.ours.driver 'touch %A'
174 # measure_branch NAME [BASE]
175 measure_branch()
177 _bname="$1"; _base="$2"
178 [ -n "$_base" ] || _base="refs/top-bases/$_bname"
179 # The caller should've verified $name is valid
180 _commits="$(git rev-list "$_bname" ^"$_base" -- | wc -l)"
181 _nmcommits="$(git rev-list --no-merges "$_bname" ^"$_base" -- | wc -l)"
182 if [ $_commits -gt 1 ]; then
183 _suffix="commits"
184 else
185 _suffix="commit"
187 echo "$_commits/$_nmcommits $_suffix"
190 # branch_contains B1 B2
191 # Whether B1 is a superset of B2.
192 branch_contains()
194 [ -z "$(git rev-list --max-count=1 ^"$1" "$2" --)" ]
197 # ref_exists REF
198 # Whether REF is a valid ref name
199 ref_exists()
201 git rev-parse --verify "$@" >/dev/null 2>&1
204 # has_remote BRANCH
205 # Whether BRANCH has a remote equivalent (accepts top-bases/ too)
206 has_remote()
208 [ -n "$base_remote" ] && ref_exists "remotes/$base_remote/$1"
211 branch_annihilated()
213 _branch_name="$1";
215 # use the merge base in case the base is ahead.
216 mb="$(git merge-base "refs/top-bases/$_branch_name" "$_branch_name" 2> /dev/null)";
218 test -z "$mb" || test "$(git rev-parse "$mb^{tree}")" = "$(git rev-parse "$_branch_name^{tree}")";
221 non_annihilated_branches()
223 _pattern="$@"
224 git for-each-ref ${_pattern:-refs/top-bases} |
225 while read rev type ref; do
226 name="${ref#refs/top-bases/}"
227 if branch_annihilated "$name"; then
228 continue
230 echo "$name"
231 done
234 # Make sure our tree is clean
235 ensure_clean_tree()
237 git update-index --ignore-submodules --refresh ||
238 die "the working directory has uncommitted changes (see above) - first commit or reset them"
239 [ -z "$(git diff-index --cached --name-status -r --ignore-submodules HEAD --)" ] ||
240 die "the index has uncommited changes"
243 # is_sha1 REF
244 # Whether REF is a SHA1 (compared to a symbolic name).
245 is_sha1()
247 [ "$(git rev-parse "$1")" = "$1" ]
250 # recurse_deps CMD NAME [BRANCHPATH...]
251 # Recursively eval CMD on all dependencies of NAME.
252 # CMD can refer to $_name for queried branch name,
253 # $_dep for dependency name,
254 # $_depchain for space-seperated branch backtrace,
255 # $_dep_missing boolean to check whether $_dep is present
256 # and the $_dep_is_tgish boolean.
257 # It can modify $_ret to affect the return value
258 # of the whole function.
259 # If recurse_deps() hits missing dependencies, it will append
260 # them to space-separated $missing_deps list and skip them
261 # affter calling CMD with _dep_missing set.
262 # remote dependencies are processed if no_remotes is unset.
263 recurse_deps()
265 _cmd="$1"; shift
266 _name="$1"; # no shift
267 _depchain="$*"
269 _depsfile="$(get_temp tg-depsfile)"
270 # If no_remotes is unset check also our base against remote base.
271 # Checking our head against remote head has to be done in the helper.
272 if test -z "$no_remotes" && has_remote "top-bases/$_name"; then
273 echo "refs/remotes/$base_remote/top-bases/$_name" >>"$_depsfile"
276 # if the branch was annihilated, it is considered to have no dependencies
277 if ! branch_annihilated "$_name"; then
278 #TODO: handle nonexisting .topdeps?
279 git cat-file blob "$_name:.topdeps" >>"$_depsfile";
282 _ret=0
283 while read _dep; do
284 _dep_missing=
285 if ! ref_exists "$_dep" ; then
286 # All hope is lost. Inform driver and continue
287 missing_deps="$missing_deps $_dep"
288 _dep_missing=1
289 eval "$_cmd"
290 continue
293 _dep_is_tgish=1
294 ref_exists "refs/top-bases/$_dep" ||
295 _dep_is_tgish=
297 # Shoo shoo, keep our environment alone!
298 [ -z "$_dep_is_tgish" ] ||
299 (recurse_deps "$_cmd" "$_dep" "$@") ||
300 _ret=$?
302 eval "$_cmd"
303 done <"$_depsfile"
304 missing_deps="${missing_deps# }"
305 return $_ret
308 # branch_needs_update
309 # This is a helper function for determining whether given branch
310 # is up-to-date wrt. its dependencies. It expects input as if it
311 # is called as a recurse_deps() helper.
312 # In case the branch does need update, it will echo it together
313 # with the branch backtrace on the output (see needs_update()
314 # description for details) and set $_ret to non-zero.
315 branch_needs_update()
317 if [ -n "$_dep_missing" ]; then
318 echo "! $_depchain"
319 return 0
322 _dep_base_update=
323 if [ -n "$_dep_is_tgish" ]; then
324 branch_annihilated "$_dep" && return 0
326 if has_remote "$_dep"; then
327 branch_contains "$_dep" "refs/remotes/$base_remote/$_dep" || _dep_base_update=%
329 # This can possibly override the remote check result;
330 # we want to sync with our base first
331 branch_contains "$_dep" "refs/top-bases/$_dep" || _dep_base_update=:
334 if [ -n "$_dep_base_update" ]; then
335 # _dep needs to be synced with its base/remote
336 echo "$_dep_base_update $_dep $_depchain"
337 _ret=1
338 elif [ -n "$_name" ] && ! branch_contains "refs/top-bases/$_name" "$_dep"; then
339 # Some new commits in _dep
340 echo "$_dep $_depchain"
341 _ret=1
345 # needs_update NAME
346 # This function is recursive; it outputs reverse path from NAME
347 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
348 # inner paths first. Innermost name can be ':' if the head is
349 # not in sync with the base, '%' if the head is not in sync
350 # with the remote (in this order of priority) or '!' if depednecy
351 # is missing.
352 # It will also return non-zero status if NAME needs update.
353 # If needs_update() hits missing dependencies, it will append
354 # them to space-separated $missing_deps list and skip them.
355 needs_update()
357 recurse_deps branch_needs_update "$@"
360 # branch_empty NAME [-i | -w]
361 branch_empty()
363 [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" ${2-})" ]
366 # list_deps [-i | -w]
367 # -i/-w apply only to HEAD
368 list_deps()
370 head_from=${1-}
371 head="$(git symbolic-ref -q HEAD)" ||
372 head="..detached.."
374 git for-each-ref refs/top-bases |
375 while read rev type ref; do
376 name="${ref#refs/top-bases/}"
377 if branch_annihilated "$name"; then
378 continue;
381 from=$head_from
382 [ "refs/heads/$name" = "$head" ] ||
383 from=
384 cat_file "$name:.topdeps" $from | while read dep; do
385 dep_is_tgish=true
386 ref_exists "refs/top-bases/$dep" ||
387 dep_is_tgish=false
388 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
389 echo "$name $dep"
391 done
392 done
395 # switch_to_base NAME [SEED]
396 switch_to_base()
398 _base="refs/top-bases/$1"; _seed="$2"
399 # We have to do all the hard work ourselves :/
400 # This is like git checkout -b "$_base" "$_seed"
401 # (or just git checkout "$_base"),
402 # but does not create a detached HEAD.
403 git read-tree -u -m HEAD "${_seed:-$_base}"
404 [ -z "$_seed" ] || git update-ref "$_base" "$_seed"
405 git symbolic-ref HEAD "$_base"
408 # Show the help messages.
409 do_help()
411 if [ -z "$1" ] ; then
412 # This is currently invoked in all kinds of circumstances,
413 # including when the user made a usage error. Should we end up
414 # providing more than a short help message, then we should
415 # differentiate.
416 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
418 ## Build available commands list for help output
420 cmds=
421 sep=
422 for cmd in "@cmddir@"/tg-*; do
423 ! [ -r "$cmd" ] && continue
424 # strip directory part and "tg-" prefix
425 cmd="$(basename "$cmd")"
426 cmd="${cmd#tg-}"
427 cmds="$cmds$sep$cmd"
428 sep="|"
429 done
431 echo "TopGit v$TG_VERSION - A different patch queue manager"
432 echo "Usage: tg ( help [<command>] | [-r <remote>] ($cmds) ...)"
433 elif [ -r "@cmddir@"/tg-$1 ] ; then
434 setup_pager
435 @cmddir@/tg-$1 -h 2>&1 || :
436 echo
437 if [ -r "@sharedir@/tg-$1.txt" ] ; then
438 cat "@sharedir@/tg-$1.txt"
440 else
441 echo "`basename $0`: no help for $1" 1>&2
442 do_help
443 exit 1
447 ## Pager stuff
449 # isatty FD
450 isatty()
452 test -t $1
455 # setup_pager
456 # Spawn pager process and redirect the rest of our output to it
457 setup_pager()
459 isatty 1 || return 0
461 # TG_PAGER = GIT_PAGER | PAGER | less
462 # NOTE: GIT_PAGER='' is significant
463 TG_PAGER=${GIT_PAGER-${PAGER-less}}
465 [ -z "$TG_PAGER" -o "$TG_PAGER" = "cat" ] && return 0
468 # now spawn pager
469 export LESS="${LESS:-FRSX}" # as in pager.c:pager_preexec()
471 # setup_pager should be called only once per command
472 pager_fifo="${tg_tmp_dir:-${HOME}}/.tg-pager"
473 mkfifo -m 600 "$pager_fifo"
475 "$TG_PAGER" < "$pager_fifo" &
476 exec > "$pager_fifo" # dup2(pager_fifo.in, 1)
478 # this is needed so e.g. `git diff` will still colorize it's output if
479 # requested in ~/.gitconfig with color.diff=auto
480 export GIT_PAGER_IN_USE=1
482 # atexit(close(1); wait pager)
483 # deliberately overwrites the global EXIT trap
484 trap "exec >&-; rm -rf \"${tg_tmp_dir:-${HOME}/.tg-pager}\"; wait" EXIT
487 # get_temp NAME [-d]
488 # creates a new temporary file (or directory with -d) in the global
489 # temporary directory $tg_tmp_dir with pattern prefix NAME
490 get_temp()
492 mktemp ${2-} "$tg_tmp_dir/$1.XXXXXX"
495 ## Startup
497 [ -d "@cmddir@" ] ||
498 die "No command directory: '@cmddir@'"
500 ## Initial setup
502 cmd="$1"
503 [ -z "$tg__include" ] || cmd="include" # ensure setup happens
504 case "$cmd" in
505 help|--help|-h)
508 if [ -n "$cmd" ]; then
509 set -e
510 # suppress the merge log editor feature since git 1.7.10
511 export GIT_MERGE_AUTOEDIT=no
512 git_dir="$(git rev-parse --git-dir)"
513 root_dir="$(git rev-parse --show-cdup)"; root_dir="${root_dir:-.}"
514 # Make sure root_dir doesn't end with a trailing slash.
515 root_dir="${root_dir%/}"
516 base_remote="$(git config topgit.remote 2>/dev/null)" || :
517 tg="tg"
518 # make sure merging the .top* files will always behave sanely
519 setup_ours
520 setup_hook "pre-commit"
521 # create global temporary directories, inside GIT_DIR
522 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX")"
523 trap "rm -rf \"$tg_tmp_dir\"" EXIT
525 esac
527 ## Dispatch
529 # We were sourced from another script for our utility functions;
530 # this is set by hooks. Skip the rest of the file. A simple return doesn't
531 # work as expected in every shell. See http://bugs.debian.org/516188
532 if [ -z "$tg__include" ]; then
534 if [ "$1" = "-r" ]; then
535 shift
536 if [ -z "$1" ]; then
537 echo "Option -r requires an argument." >&2
538 do_help
539 exit 1
541 base_remote="$1"; shift
542 tg="$tg -r $base_remote"
545 [ -n "$cmd" ] || { do_help; exit 1; }
546 shift
548 case "$cmd" in
549 help|--help|-h)
550 do_help "$1"
551 exit 0;;
552 --hooks-path)
553 # Internal command
554 echo "@hooksdir@";;
556 [ -r "@cmddir@"/tg-$cmd ] || {
557 echo "Unknown subcommand: $cmd" >&2
558 do_help
559 exit 1
561 . "@cmddir@"/tg-$cmd;;
562 esac
566 # vim:noet