chiark / gitweb /
Merge commit 'refs/top-bases/fixes/ensure-worktree' into fixes/ensure-worktree
[topgit.git] / tg.sh
1 #!/bin/sh
2 # TopGit - A different patch queue manager
3 # (c) Petr Baudis <pasky@suse.cz>  2008
4 # GPLv2
5
6 TG_VERSION=0.8
7
8 ## Auxiliary functions
9
10 info()
11 {
12         echo "${TG_RECURSIVE}tg: $*"
13 }
14
15 die()
16 {
17         info "fatal: $*" >&2
18         exit 1
19 }
20
21 # Make sure we are in the worktree, not under .git; die otherwise
22 ensure_git_repo_or_die()
23 {
24         local is_inside_repo is_inside_git_dir
25         is_inside_repo=1
26         is_inside_git_dir=$(git rev-parse --is-inside-git-dir 2>/dev/null) ||
27                 is_inside_repo=0
28
29         case "$is_inside_repo/$is_inside_git_dir" in
30         0*) die "Cannot run outside of a Git repository.";;
31         1/true) die "Cannot run from inside \`.git\` hierarchy, please switch to work-tree.";;
32         esac
33 }
34
35 # cat_file TOPIC:PATH [FROM]
36 # cat the file PATH from branch TOPIC when FROM is empty.
37 # FROM can be -i or -w, than the file will be from the index or worktree,
38 # respectively. The caller should than ensure that HEAD is TOPIC, to make sense.
39 cat_file()
40 {
41         path="$1"
42         case "${2-}" in
43         -w)
44                 cat "$root_dir/${path#*:}"
45                 ;;
46         -i)
47                 # ':file' means cat from index
48                 git cat-file blob ":${path#*:}"
49                 ;;
50         '')
51                 git cat-file blob "$path"
52                 ;;
53         *)
54                 die "Wrong argument to cat_file: '$2'"
55                 ;;
56         esac
57 }
58
59 # get tree for the committed topic
60 get_tree_()
61 {
62         echo "$1"
63 }
64
65 # get tree for the base
66 get_tree_b()
67 {
68         echo "refs/top-bases/$1"
69 }
70
71 # get tree for the index
72 get_tree_i()
73 {
74         git write-tree
75 }
76
77 # get tree for the worktree
78 get_tree_w()
79 {
80         i_tree=$(git write-tree)
81         (
82                 # the file for --index-output needs to sit next to the
83                 # current index file
84                 : ${GIT_INDEX_FILE:="$git_dir/index"}
85                 TMP_INDEX="$(mktemp "${GIT_INDEX_FILE}-tg.XXXXXX")"
86                 git read-tree -m $i_tree --index-output="$TMP_INDEX" &&
87                 GIT_INDEX_FILE="$TMP_INDEX" &&
88                 export GIT_INDEX_FILE &&
89                 git diff --name-only -z HEAD |
90                         git update-index -z --add --remove --stdin &&
91                 git write-tree &&
92                 rm -f "$TMP_INDEX"
93         )
94 }
95
96 # pretty_tree NAME [-b | -i | -w]
97 # Output tree ID of a cleaned-up tree without tg's artifacts.
98 # NAME will be ignored for -i and -w, but needs to be present
99 pretty_tree()
100 {
101         name=$1
102         source=${2#?}
103         git ls-tree --full-tree "$(get_tree_$source "$name")" |
104                 awk -F '        ' '$2 !~ /^.top/' |
105                 git mktree
106 }
107
108 # setup_hook NAME
109 setup_hook()
110 {
111         hook_call="\"\$($tg --hooks-path)\"/$1 \"\$@\""
112         if [ -f "$git_dir/hooks/$1" ] &&
113            fgrep -q "$hook_call" "$git_dir/hooks/$1"; then
114                 # Another job well done!
115                 return
116         fi
117         # Prepare incantation
118         if [ -x "$git_dir/hooks/$1" ]; then
119                 hook_call="$hook_call"' || exit $?'
120         else
121                 hook_call="exec $hook_call"
122         fi
123         # Don't call hook if tg is not installed
124         hook_call="if which \"$tg\" > /dev/null; then $hook_call; fi"
125         # Insert call into the hook
126         {
127                 echo "#!/bin/sh"
128                 echo "$hook_call"
129                 [ ! -s "$git_dir/hooks/$1" ] || cat "$git_dir/hooks/$1"
130         } >"$git_dir/hooks/$1+"
131         chmod a+x "$git_dir/hooks/$1+"
132         mv "$git_dir/hooks/$1+" "$git_dir/hooks/$1"
133 }
134
135 # setup_ours (no arguments)
136 setup_ours()
137 {
138         if [ ! -s "$git_dir/info/attributes" ] || ! grep -q topmsg "$git_dir/info/attributes"; then
139                 {
140                         echo ".topmsg   merge=ours"
141                         echo ".topdeps  merge=ours"
142                 } >>"$git_dir/info/attributes"
143         fi
144         if ! git config merge.ours.driver >/dev/null; then
145                 git config merge.ours.name '"always keep ours" merge driver'
146                 git config merge.ours.driver 'touch %A'
147         fi
148 }
149
150 # measure_branch NAME [BASE]
151 measure_branch()
152 {
153         _bname="$1"; _base="$2"
154         [ -n "$_base" ] || _base="refs/top-bases/$_bname"
155         # The caller should've verified $name is valid
156         _commits="$(git rev-list "$_bname" ^"$_base" -- | wc -l)"
157         _nmcommits="$(git rev-list --no-merges "$_bname" ^"$_base" -- | wc -l)"
158         if [ $_commits -gt 1 ]; then
159                 _suffix="commits"
160         else
161                 _suffix="commit"
162         fi
163         echo "$_commits/$_nmcommits $_suffix"
164 }
165
166 # branch_contains B1 B2
167 # Whether B1 is a superset of B2.
168 branch_contains()
169 {
170         [ -z "$(git rev-list --max-count=1 ^"$1" "$2" --)" ]
171 }
172
173 # ref_exists REF
174 # Whether REF is a valid ref name
175 ref_exists()
176 {
177         git rev-parse --verify "$@" >/dev/null 2>&1
178 }
179
180 # has_remote BRANCH
181 # Whether BRANCH has a remote equivalent (accepts top-bases/ too)
182 has_remote()
183 {
184         [ -n "$base_remote" ] && ref_exists "remotes/$base_remote/$1"
185 }
186
187 branch_annihilated()
188 {
189         _name="$1";
190
191         # use the merge base in case the base is ahead.
192         mb="$(git merge-base "refs/top-bases/$_name" "$_name")";
193
194         test "$(git rev-parse "$mb^{tree}")" = "$(git rev-parse "$_name^{tree}")";
195 }
196
197 # is_sha1 REF
198 # Whether REF is a SHA1 (compared to a symbolic name).
199 is_sha1()
200 {
201         [ "$(git rev-parse "$1")" = "$1" ]
202 }
203
204 # recurse_deps CMD NAME [BRANCHPATH...]
205 # Recursively eval CMD on all dependencies of NAME.
206 # CMD can refer to $_name for queried branch name,
207 # $_dep for dependency name,
208 # $_depchain for space-seperated branch backtrace,
209 # and the $_dep_is_tgish boolean.
210 # It can modify $_ret to affect the return value
211 # of the whole function.
212 # If recurse_deps() hits missing dependencies, it will append
213 # them to space-separated $missing_deps list and skip them.
214 # remote dependencies are processed if no_remotes is unset.
215 recurse_deps()
216 {
217         _cmd="$1"; shift
218         _name="$1"; # no shift
219         _depchain="$*"
220
221         _depsfile="$(get_temp tg-depsfile)"
222         # If no_remotes is unset check also our base against remote base.
223         # Checking our head against remote head has to be done in the helper.
224         if test -z "$no_remotes" && has_remote "top-bases/$_name"; then
225                 echo "refs/remotes/$base_remote/top-bases/$_name" >>"$_depsfile"
226         fi
227
228         # if the branch was annihilated, there exists no .topdeps file
229         if ! branch_annihilated "$_name"; then
230                 #TODO: handle nonexisting .topdeps?
231                 git cat-file blob "$_name:.topdeps" >>"$_depsfile";
232         fi;
233
234         _ret=0
235         while read _dep; do
236                 if ! ref_exists "$_dep" ; then
237                         # All hope is lost
238                         missing_deps="$missing_deps $_dep"
239                         continue
240                 fi
241
242                 _dep_is_tgish=1
243                 ref_exists "refs/top-bases/$_dep"  ||
244                         _dep_is_tgish=
245
246                 # Shoo shoo, keep our environment alone!
247                 [ -z "$_dep_is_tgish" ] ||
248                         (recurse_deps "$_cmd" "$_dep" "$@") ||
249                         _ret=$?
250
251                 eval "$_cmd"
252         done <"$_depsfile"
253         missing_deps="${missing_deps# }"
254         return $_ret
255 }
256
257 # branch_needs_update
258 # This is a helper function for determining whether given branch
259 # is up-to-date wrt. its dependencies. It expects input as if it
260 # is called as a recurse_deps() helper.
261 # In case the branch does need update, it will echo it together
262 # with the branch backtrace on the output (see needs_update()
263 # description for details) and set $_ret to non-zero.
264 branch_needs_update()
265 {
266         _dep_base_update=
267         if [ -n "$_dep_is_tgish" ]; then
268                 if has_remote "$_dep"; then
269                         branch_contains "$_dep" "refs/remotes/$base_remote/$_dep" || _dep_base_update=%
270                 fi
271                 # This can possibly override the remote check result;
272                 # we want to sync with our base first
273                 branch_contains "$_dep" "refs/top-bases/$_dep" || _dep_base_update=:
274         fi
275
276         if [ -n "$_dep_base_update" ]; then
277                 # _dep needs to be synced with its base/remote
278                 echo "$_dep_base_update $_dep $_depchain"
279                 _ret=1
280         elif [ -n "$_name" ] && ! branch_contains "refs/top-bases/$_name" "$_dep"; then
281                 # Some new commits in _dep
282                 echo "$_dep $_depchain"
283                 _ret=1
284         fi
285 }
286
287 # needs_update NAME
288 # This function is recursive; it outputs reverse path from NAME
289 # to the branch (e.g. B_DIRTY B1 B2 NAME), one path per line,
290 # inner paths first. Innermost name can be ':' if the head is
291 # not in sync with the base or '%' if the head is not in sync
292 # with the remote (in this order of priority).
293 # It will also return non-zero status if NAME needs update.
294 # If needs_update() hits missing dependencies, it will append
295 # them to space-separated $missing_deps list and skip them.
296 needs_update()
297 {
298         recurse_deps branch_needs_update "$@"
299 }
300
301 # branch_empty NAME [-i | -w]
302 branch_empty()
303 {
304         [ "$(pretty_tree "$1" -b)" = "$(pretty_tree "$1" ${2-})" ]
305 }
306
307 # list_deps [-i | -w]
308 # -i/-w apply only to HEAD
309 list_deps()
310 {
311         local head
312         local head_from
313         local from
314         head_from=${1-}
315         head="$(git symbolic-ref -q HEAD)" ||
316                 head="..detached.."
317
318         git for-each-ref refs/top-bases |
319                 while read rev type ref; do
320                         name="${ref#refs/top-bases/}"
321                         if branch_annihilated "$name"; then
322                                 continue;
323                         fi
324
325                         from=$head_from
326                         [ "refs/heads/$name" = "$head" ] ||
327                                 from=
328                         cat_file "$name:.topdeps" $from | while read dep; do
329                                 dep_is_tgish=true
330                                 ref_exists "refs/top-bases/$dep"  ||
331                                         dep_is_tgish=false
332                                 if ! "$dep_is_tgish" || ! branch_annihilated $dep; then
333                                         echo "$name $dep"
334                                 fi
335                         done
336                 done
337 }
338
339 # switch_to_base NAME [SEED]
340 switch_to_base()
341 {
342         _base="refs/top-bases/$1"; _seed="$2"
343         # We have to do all the hard work ourselves :/
344         # This is like git checkout -b "$_base" "$_seed"
345         # (or just git checkout "$_base"),
346         # but does not create a detached HEAD.
347         git read-tree -u -m HEAD "${_seed:-$_base}"
348         [ -z "$_seed" ] || git update-ref "$_base" "$_seed"
349         git symbolic-ref HEAD "$_base"
350 }
351
352 # Show the help messages.
353 do_help()
354 {
355         if [ -z "$1" ] ; then
356                 # This is currently invoked in all kinds of circumstances,
357                 # including when the user made a usage error. Should we end up
358                 # providing more than a short help message, then we should
359                 # differentiate.
360                 # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
361
362                 ## Build available commands list for help output
363
364                 cmds=
365                 sep=
366                 for cmd in "@cmddir@"/tg-*; do
367                         ! [ -r "$cmd" ] && continue
368                         # strip directory part and "tg-" prefix
369                         cmd="$(basename "$cmd")"
370                         cmd="${cmd#tg-}"
371                         cmds="$cmds$sep$cmd"
372                         sep="|"
373                 done
374
375                 echo "TopGit v$TG_VERSION - A different patch queue manager"
376                 echo "Usage: tg [-r REMOTE] ($cmds|help) ..."
377         elif [ -r "@cmddir@"/tg-$1 ] ; then
378                 setup_pager
379                 @cmddir@/tg-$1 -h 2>&1 || :
380                 echo
381                 if [ -r "@sharedir@/tg-$1.txt" ] ; then
382                         cat "@sharedir@/tg-$1.txt"
383                 fi
384         else
385                 echo "`basename $0`: no help for $1" 1>&2
386                 do_help
387                 exit 1
388         fi
389 }
390
391 ## Pager stuff
392
393 # isatty FD
394 isatty()
395 {
396         test -t $1
397 }
398
399 # setup_pager
400 # Spawn pager process and redirect the rest of our output to it
401 setup_pager()
402 {
403         isatty 1 || return 0
404
405         # TG_PAGER = GIT_PAGER | PAGER | less
406         # NOTE: GIT_PAGER='' is significant
407         TG_PAGER=${GIT_PAGER-${PAGER-less}}
408
409         [ -z "$TG_PAGER"  -o  "$TG_PAGER" = "cat" ]  && return 0
410
411
412         # now spawn pager
413         export LESS="${LESS:-FRSX}"     # as in pager.c:pager_preexec()
414
415         # setup_pager should be called only once per command
416         pager_fifo="$tg_tmp_dir/pager"
417         mkfifo -m 600 "$pager_fifo"
418
419         "$TG_PAGER" < "$pager_fifo" &
420         exec > "$pager_fifo"            # dup2(pager_fifo.in, 1)
421
422         # this is needed so e.g. `git diff` will still colorize it's output if
423         # requested in ~/.gitconfig with color.diff=auto
424         export GIT_PAGER_IN_USE=1
425
426         # atexit(close(1); wait pager)
427         # deliberately overwrites the global EXIT trap
428         trap "exec >&-; rm -rf \"$tg_tmp_dir\"; wait" EXIT
429 }
430
431 # get_temp NAME [-d]
432 # creates a new temporary file (or directory with -d) in the global
433 # temporary directory $tg_tmp_dir with pattern prefix NAME
434 get_temp()
435 {
436         mktemp ${2-} "$tg_tmp_dir/$1.XXXXXX"
437 }
438
439 ## Startup
440
441 [ -d "@cmddir@" ] ||
442         die "No command directory: '@cmddir@'"
443
444 ensure_git_repo_or_die
445
446 ## Initial setup
447
448 set -e
449 git_dir="$(git rev-parse --git-dir)"
450 root_dir="$(git rev-parse --show-cdup)"; root_dir="${root_dir:-.}"
451 # Make sure root_dir doesn't end with a trailing slash.
452 root_dir="${root_dir%/}"
453 base_remote="$(git config topgit.remote 2>/dev/null)" || :
454 tg="tg"
455 # make sure merging the .top* files will always behave sanely
456 setup_ours
457 setup_hook "pre-commit"
458 # create global temporary directories, inside GIT_DIR
459 tg_tmp_dir="$(mktemp -d "$git_dir/tg-tmp.XXXXXX")"
460 trap "rm -rf \"$tg_tmp_dir\"" EXIT
461
462 ## Dispatch
463
464 # We were sourced from another script for our utility functions;
465 # this is set by hooks.  Skip the rest of the file.  A simple return doesn't
466 # work as expected in every shell.  See http://bugs.debian.org/516188
467 if [ -z "$tg__include" ]; then
468
469 if [ "$1" = "-r" ]; then
470         shift
471         if [ -z "$1" ]; then
472                 echo "Option -r requires an argument." >&2
473                 do_help
474                 exit 1
475         fi
476         base_remote="$1"; shift
477         tg="$tg -r $base_remote"
478 fi
479
480 cmd="$1"
481 [ -n "$cmd" ] || { do_help; exit 1; }
482 shift
483
484 case "$cmd" in
485 help|--help|-h)
486         do_help "$1"
487         exit 0;;
488 --hooks-path)
489         # Internal command
490         echo "@hooksdir@";;
491 *)
492         [ -r "@cmddir@"/tg-$cmd ] || {
493                 echo "Unknown subcommand: $cmd" >&2
494                 do_help
495                 exit 1
496         }
497         . "@cmddir@"/tg-$cmd;;
498 esac
499
500 fi
501
502 # vim:noet