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