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