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