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