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