guilt: abort if working with a detached head
[guilt.git] / guilt
blobfbdf765e61ef534b67859611ee896aeb1f2f97ee
1 #!/bin/sh
3 # Copyright (c) Josef "Jeff" Sipek, 2006-2008
6 GUILT_VERSION="0.31.1"
7 GUILT_NAME="Ciuleandra"
9 # If the first argument is one of the below, display the man page instead of
10 # the rather silly and mostly useless usage string
11 case $1 in
12 -h|--h|--he|--hel|--help)
13 shift
14 exec "guilt-help" "`basename $0`"
15 exit
17 -V|--ver|--versi|--versio|--version)
18 echo "Guilt version $GUILT_VERSION"
19 exit
21 esac
23 # we change directories ourselves
24 SUBDIRECTORY_OK=1
26 . "$(git --exec-path)/git-sh-setup"
29 # Git version check
31 gitver=`git --version | cut -d' ' -f3 | sed -e 's/^debian\.//'`
32 case "$gitver" in
33 1.5.*) ;; # git config
34 1.6.*) ;; # git config
35 *) die "Unsupported version of git ($gitver)" ;;
36 esac
39 # Shell library
42 # echo -n is a bashism, use printf instead
43 _disp()
45 printf "%b" "$*"
48 # echo -e is a bashism, use printf instead
49 disp()
51 printf "%b\n" "$*"
54 noerr()
56 "$@" 2>/dev/null
59 silent()
61 "$@" >/dev/null 2>/dev/null
64 ########
66 guilt_commands()
68 find "`dirname $0`" -maxdepth 1 -name "guilt-*" -type f -perm +111 | sed -e "s/.*\\/`basename $0`-//"
71 if [ "`basename $0`" = "guilt" ]; then
72 # being run as standalone
74 # by default, we shouldn't fail
75 cmd=
77 if [ $# -ne 0 ]; then
78 # take first arg, and try to execute it
80 arg="$1"
81 dir=`dirname $0`
83 if [ -x "$dir/guilt-$arg" ]; then
84 cmd=$arg
85 else
86 # might be a short handed
87 for command in $(guilt_commands); do
88 case $command in
89 $arg*)
90 if [ -x "$dir/guilt-$command" ]; then
91 cmd=$command
94 esac
95 done
97 if [ -n "$cmd" ]; then
98 shift
99 exec "$dir/guilt-$cmd" "$@"
101 # this is not reached because of the exec
102 die "Exec failed! Something is terribly wrong!"
103 else
104 disp "Command $arg not found" >&2
105 disp "" >&2
109 # no args passed or invalid command entered, just output help summary
111 disp "Guilt v$GUILT_VERSION"
112 disp ""
113 disp "Pick a command:"
114 guilt_commands | sort | column | column -t | sed -e 's/^/ /'
116 disp ""
117 disp "Example:"
118 disp "\tguilt-push"
119 disp "or"
120 disp "\tguilt push"
122 # now, let's exit
123 exit 1
126 ########
129 # Library goodies
132 # usage: valid_patchname <patchname>
133 valid_patchname()
135 case "$1" in
136 /*|./*|../*|*/./*|*/../*|*/.|*/..|*/|*\ *|*\ *)
137 return 1;;
139 return 0;;
140 esac
143 get_branch()
145 silent git symbolic-ref HEAD || \
146 die "Working on a detached HEAD is unsupported."
148 git symbolic-ref HEAD | sed -e 's,^refs/heads/,,'
151 verify_branch()
153 [ ! -d "$GIT_DIR/patches" ] &&
154 die "Patches directory doesn't exist, try guilt-init"
155 [ ! -d "$GIT_DIR/patches/$branch" ] &&
156 die "Branch $branch is not initialized, try guilt-init"
157 [ ! -f "$GIT_DIR/patches/$branch/series" ] &&
158 die "Branch $branch does not have a series file"
159 [ ! -f "$GIT_DIR/patches/$branch/status" ] &&
160 die "Branch $branch does not have a status file"
161 [ -f "$GIT_DIR/patches/$branch/applied" ] &&
162 die "Warning: Branch $branch has 'applied' file - guilt is not compatible with stgit"
165 get_top()
167 tail -1 "$GUILT_DIR/$branch/status"
170 get_prev()
172 if [ `wc -l < "$GUILT_DIR/$branch/status"` -gt 1 ]; then
173 tail -n 2 "$GUILT_DIR/$branch/status" | head -n 1
177 get_series()
179 # ignore all lines matching:
180 # - empty lines
181 # - whitespace only
182 # - optional whitespace followed by '#' followed by more
183 # optional whitespace
184 grep -ve '^[[:space:]]*\(#.*\)*$' "$series"
187 # usage: do_make_header <hash>
188 do_make_header()
190 # we should try to work with commit objects only
191 if [ `git cat-file -t "$1"` != "commit" ]; then
192 disp "Hash $1 is not a commit object" >&2
193 disp "Aborting..." >&2
194 exit 2
197 git cat-file -p "$1" | awk '
198 BEGIN{headers=1; firstline=1}
199 /^author / && headers {
200 sub(/^author +/, "");
201 sub(/ [0-9]* [+-]*[0-9][0-9]*$/, "");
202 author=$0
204 !headers {
205 print
206 if (firstline) {
207 firstline = 0;
208 print "\nFrom: " author;
211 /^$/ && headers { headers = 0 }
215 # usage: do_get_patch patchfile
216 do_get_patch()
218 cat "$1" | awk '
219 BEGIN{}
220 /^(diff |---)/,/END{}/
224 # usage: do_get_header patchfile
225 do_get_header()
227 # The complexity arises from the fact that we want to ignore the
228 # From line and the empty line after it if it exists
230 # 2nd line skips the From line
231 # 3rd line skips the empty line right after a From line
232 # 4th line terminates execution when we encounter the diff
233 cat "$1" | awk '
234 BEGIN{skip=0}
235 /^Subject:/ && (NR==1){print substr($0, 10); next}
236 /^From:/{skip=1; next}
237 /^[ \t\f\n\r\v]*$/ && (skip==1){skip=0; next}
238 /^(diff |---)/{exit}
239 {print $0}
240 END{}
244 # usage: do_get_full_header patchfile
245 do_get_full_header()
247 # 2nd line checks for the begining of a patch
248 # 3rd line outputs the line if it didn't get pruned by the above rules
249 cat "$1" | awk '
250 BEGIN{}
251 /^(diff |---)/{exit}
252 {print $0}
253 END{}
257 # usage: assert_head_check
258 assert_head_check()
260 if ! head_check refs/patches/$branch/`get_top`; then
261 die "aborting..."
265 # usage: head_check <expected hash>
266 head_check()
268 # make sure we're not doing funky things to commits that don't
269 # belong to us
271 case "$1" in
273 # the expected hash is empty
274 return 0 ;;
275 refs/patches/$branch/)
276 # the expected hash is an invalid rev
277 return 0 ;;
278 esac
280 if [ "`git rev-parse refs/heads/$branch`" != "`git rev-parse $1`" ]; then
281 disp "Expected HEAD commit $1" >&2
282 disp " got `git rev-parse refs/heads/$branch`" >&2
283 return 1
285 return 0
288 # usage: series_insert_patch <patchname>
289 series_insert_patch()
291 awk -v top="`get_top`" -v new="$1" \
292 'BEGIN{if (top == "") print new;}
294 print $0;
295 if (top != "" && top == $0) print new;
296 }' "$series" > "$series.tmp"
297 mv "$series.tmp" "$series"
300 # usage: series_remove_patch <patchname>
301 series_remove_patch()
303 grep -v "^$1\$" < "$series" > "$series.tmp"
304 mv "$series.tmp" "$series"
307 # usage: series_rename_patch <oldname> <newname>
308 series_rename_patch()
310 awk -v old="$1" -v new="$2" \
311 '{ if ($0 == old) print new; else print $0 }' \
312 "$series" > "$series.tmp"
314 mv "$series.tmp" "$series"
317 # usage: series_rename_patch <oldpatchname> <newpatchname>
318 ref_rename_patch()
320 git update-ref "refs/patches/$branch/$2" `git rev-parse "refs/patches/$branch/$1"`
321 remove_ref "refs/patches/$branch/$1"
324 # Beware! This is one of the few (only?) places where we modify the applied
325 # file directly
327 # usage: applied_rename_patch <oldname> <newname>
328 applied_rename_patch()
330 awk -v old="$1" -v new="$2" \
331 'BEGIN{FS=":"}
332 { if ($0 == old)
333 print new;
334 else
335 print;
336 }' "$applied" > "$applied.tmp"
338 mv "$applied.tmp" "$applied"
341 # usage: remove_patch_refs
342 # reads patch names from stdin
343 remove_patch_refs()
345 while read pname; do
346 remove_ref "refs/patches/$branch/$pname"
347 done
350 # usage: pop_many_patches <commitish> <number of patches>
351 pop_many_patches()
353 assert_head_check
356 cd "$TOP_DIR"
358 # remove the patches refs
359 tail -$2 < "$applied" | remove_patch_refs
361 git reset --hard "$1" > /dev/null
362 head -n "-$2" < "$applied" > "$applied.tmp"
363 mv "$applied.tmp" "$applied"
366 # update references to top, bottom, and base
367 update_stack_tags
370 # usage: pop_all_patches
371 pop_all_patches()
373 pop_many_patches \
374 `git rev-parse refs/patches/$branch/$(head -1 "$applied")^` \
375 `wc -l < "$applied"`
378 # usage: remove_ref <refname>
379 remove_ref()
382 # does the ref exist?
383 r=`git show-ref --verify -s "$1" 2> /dev/null`
384 [ $? -ne 0 ] && exit 0
386 # remove it
387 git update-ref -d "$1" "$r"
391 # usage: update_stack_tags [force]
393 # if [force] is non-empty, then do not check for autotagging being enabled,
394 # just assume it is
395 update_stack_tags()
397 # bail if autotagging is not enabled
398 if [ -z "$1" -a $autotag -eq 0 ]; then
399 return 0
402 if [ -s "$applied" ]; then
403 # there are patches applied, therefore we must get the top,
404 # bottom and base hashes, and update the tags
406 git update-ref "refs/tags/${branch}_top" `git rev-parse HEAD`
407 git update-ref "refs/tags/${branch}_bottom" `git rev-parse refs/patches/$branch/$(head -1 < $applied)`
408 git update-ref "refs/tags/${branch}_base" `git rev-parse refs/patches/$branch/$(head -1 < $applied)^`
409 else
410 # there are no patches applied, therefore we must remove the
411 # tags to old top, bottom, and base
413 remove_ref "refs/tags/${branch}_top"
414 remove_ref "refs/tags/${branch}_bottom"
415 remove_ref "refs/tags/${branch}_base"
419 # usage: push_patch patchname [bail_action]
420 push_patch()
422 __push_patch_bail=0
425 TMP_LOG=`get_tmp_file log`
426 TMP_MSG=`get_tmp_file msg`
428 p="$GUILT_DIR/$branch/$1"
429 pname="$1"
430 bail_action="$2"
431 reject="--reject"
433 assert_head_check
434 cd "$TOP_DIR"
436 # apply the patch if and only if there is something to apply
437 if [ `git apply --numstat "$p" | wc -l` -gt 0 ]; then
438 if [ "$bail_action" = abort ]; then
439 reject=""
441 git apply -C$guilt_push_diff_context --index \
442 $reject "$p" > /dev/null 2> "$TMP_LOG"
443 __push_patch_bail=$?
445 if [ $__push_patch_bail -ne 0 ]; then
446 cat "$TMP_LOG" >&2
447 if [ "$bail_action" = "abort" ]; then
448 rm -f "$TMP_LOG" "$TMP_MSG"
449 return $__push_patch_bail
454 # grab a commit message out of the patch
455 do_get_header "$p" > "$TMP_MSG"
457 # make a default commit message if patch doesn't contain one
458 [ ! -s "$TMP_MSG" ] && echo "patch $pname" > "$TMP_MSG"
460 # extract a From line from the patch header, and set
461 # GIT_AUTHOR_{NAME,EMAIL}
462 author_str=`sed -n -e '/^From:/ { s/^From: //; p; q; }; /^(diff |---)/ q' "$p"`
463 if [ ! -z "$author_str" ]; then
464 GIT_AUTHOR_NAME=`echo $author_str | sed -e 's/ *<.*$//'`
465 export GIT_AUTHOR_NAME="${GIT_AUTHOR_NAME:-" "}"
466 export GIT_AUTHOR_EMAIL="`echo $author_str | sed -e 's/[^<]*//'`"
469 # must strip nano-second part otherwise git gets very
470 # confused, and makes up strange timestamps from the past
471 # (chances are it decides to interpret it as a unix
472 # timestamp).
473 export GIT_AUTHOR_DATE="`stat -c %y "$p" | sed -e '
474 s/^\([0-9]\{4\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\) \([0-9]\{2\}\):\([0-9]\{2\}\):\([0-9]\{2\}\)\.[0-9]* \(.*\)$/\1-\2-\3 \4:\5:\6 \7/'`"
475 export GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
477 # commit
478 treeish=`git write-tree`
479 commitish=`git commit-tree $treeish -p HEAD < "$TMP_MSG"`
480 git update-ref HEAD $commitish
482 # mark patch as applied
483 git update-ref "refs/patches/$branch/$pname" $commitish ""
485 echo "$pname" >> $applied
487 rm -f "$TMP_MSG" "$TMP_LOG"
490 # sub-shell funky-ness
491 __push_patch_bail=$?
493 # update references to top, bottom, and base of the stack
494 update_stack_tags
496 return $__push_patch_bail
499 # usage: must_commit_first
500 must_commit_first()
502 git update-index --refresh --unmerged -q > /dev/null
503 [ `git diff-files | wc -l` -eq 0 ] || return $?
504 [ `git diff-index HEAD | wc -l` -eq 0 ]
505 return $?
508 # usage: fold_patch patchname
509 fold_patch()
511 set -- "$1" "`get_top`"
513 assert_head_check
515 push_patch "$1"
517 __refresh_patch "$2" HEAD^^ 2 "" ""
519 series_remove_patch "$1"
522 # usage: refresh_patch patchname gengitdiff incldiffstat
523 refresh_patch()
525 __refresh_patch "$1" HEAD^ 1 "$2" "$3"
528 # usage: __refresh_patch patchname commitish number_of_commits gengitdiff
529 # incldiffstat
530 __refresh_patch()
532 assert_head_check
535 TMP_DIFF=`get_tmp_file diff`
537 cd "$TOP_DIR"
538 p="$GUILT_DIR/$branch/$1"
540 git diff-files --name-only | (while read n; do git update-index "$n" ; done)
542 # get the patch header
543 do_get_full_header "$p" > "$TMP_DIFF"
545 [ ! -z "$4" ] && diffopts="-C -M --find-copies-harder"
547 if [ ! -z "$5" ]; then
549 echo "---"
550 git diff --stat $diffopts "$2"
551 echo ""
552 ) >> "$TMP_DIFF"
555 # get the new patch
556 git diff $diffopts "$2" >> "$TMP_DIFF"
558 # move the new patch in
559 mv "$p" "$p~"
560 mv "$TMP_DIFF" $p
563 # drop the currently applied patch, pop_many_patches does it's own
564 # cd $TOP_DIR
565 pop_many_patches "$2" "$3"
567 # push_patch does it's own cd $TOP_DIR
568 push_patch "$1"
571 # usage: munge_hash_range <hash range>
573 # this means:
574 # <hash> - one commit
575 # <hash>.. - hash until head (excludes hash, includes head)
576 # ..<hash> - until hash (includes hash)
577 # <hash1>..<hash2> - from hash to hash (inclusive)
579 # The output of this function is suitable to be passed to "git rev-list"
580 munge_hash_range()
582 case "$1" in
583 *..*..*|*\ *)
584 # double .. or space is illegal
585 return 1;;
586 ..*)
587 # e.g., "..v0.10"
588 echo ${1#..};;
589 *..)
590 # e.g., "v0.19.."
591 echo ${1%..}..HEAD;;
592 *..*)
593 # e.g., "v0.19-rc1..v0.19"
594 echo ${1%%..*}..${1#*..};;
596 # e.g., "v0.19"
597 echo $1^..$1;;
598 *) # empty
599 return 1;;
600 esac
601 return 0
604 # usage: get_tmp_file <prefix> [<opts>]
606 # Get a unique filename and create the file in a non-racy way
607 get_tmp_file()
609 while true; do
610 mktemp $2 "/tmp/guilt.$1.XXXXXXXXXXXXXXX" && break
611 done
614 # usage: guilt_hook <hook name> <args....>
615 guilt_hook()
617 __hookname="$1"
618 [ ! -x "$GIT_DIR/hooks/guilt/$__hookname" ] && return 0
620 shift
622 "$GIT_DIR/hooks/guilt/$__hookname" "$@"
623 return $?
627 # Some constants
630 # used for: git apply -C <val>
631 guilt_push_diff_context=1
633 # default autotag value
634 AUTOTAG_DEFAULT=1
637 # Parse any part of .git/config that belongs to us
640 # autotag?
641 autotag=`git config guilt.autotag`
642 [ -z "$autotag" ] && autotag=$AUTOTAG_DEFAULT
645 # The following gets run every time this file is source'd
648 TOP_DIR=`git rev-parse --show-cdup`
649 if [ -z "$TOP_DIR" ]; then
650 TOP_DIR="./"
653 GUILT_DIR="$GIT_DIR/patches"
655 branch=`get_branch`
657 # most of the time we want to verify that the repo's branch has been
658 # initialized, but every once in a blue moon (e.g., we want to run guilt-init),
659 # we must avoid the checks
660 if [ -z "$DO_NOT_CHECK_BRANCH_EXISTENCE" ]; then
661 verify_branch
663 # do not check the status file format (guilt-repair needs this,
664 # otherwise nothing can do what's necessary to bring the repo into a
665 # useable state)
666 if [ -z "$DO_NOT_CHECK_STATUS_FILE_FORMAT" ]; then
667 [ -s "$GIT_DIR/patches/$branch/status" ] &&
668 grep "^[0-9a-f]\{40\}:" "$GIT_DIR/patches/$branch/status" > /dev/null &&
669 die "Status file appears to use old format, try guilt-repair --status"
673 # very useful files
674 series="$GUILT_DIR/$branch/series"
675 applied="$GUILT_DIR/$branch/status"
677 # determine an editor to use for anything interactive (fall back to vi)
678 editor="vi"
679 [ ! -z "$EDITOR" ] && editor="$EDITOR"
681 # determine a pager to use for anything interactive (fall back to more)
682 pager="more"
683 [ ! -z "$PAGER" ] && pager="$PAGER"