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