[PATCH] guilt: improve patch header handling
[guilt.git] / guilt
blob665129c943180dbe3af01c4d4948dcbcc3cb1fa7
1 #!/bin/sh
3 # Copyright (c) Josef "Jeff" Sipek, 2006-2010
6 GUILT_VERSION="0.34"
7 GUILT_NAME="Runaway"
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 1.7.*) ;; # git config
36 *) die "Unsupported version of git ($gitver)" ;;
37 esac
40 # Shell library
43 # echo -n is a bashism, use printf instead
44 _disp()
46 printf "%b" "$*"
49 # echo -e is a bashism, use printf instead
50 disp()
52 printf "%b\n" "$*"
55 noerr()
57 "$@" 2>/dev/null
60 silent()
62 "$@" >/dev/null 2>/dev/null
65 ########
67 guilt_commands()
69 find "`dirname $0`" -maxdepth 1 -name "guilt-*" -type f -perm +111 | sed -e "s/.*\\/`basename $0`-//"
72 if [ "`basename $0`" = "guilt" ]; then
73 # being run as standalone
75 # by default, we shouldn't fail
76 cmd=
78 if [ $# -ne 0 ]; then
79 # take first arg, and try to execute it
81 arg="$1"
82 dir=`dirname $0`
84 if [ -x "$dir/guilt-$arg" ]; then
85 cmd=$arg
86 else
87 # might be a short handed
88 for command in $(guilt_commands); do
89 case $command in
90 $arg*)
91 if [ -x "$dir/guilt-$command" ]; then
92 cmd=$command
95 esac
96 done
98 if [ -n "$cmd" ]; then
99 shift
100 exec "$dir/guilt-$cmd" "$@"
102 # this is not reached because of the exec
103 die "Exec failed! Something is terribly wrong!"
104 else
105 disp "Command $arg not found" >&2
106 disp "" >&2
110 # no args passed or invalid command entered, just output help summary
112 disp "Guilt v$GUILT_VERSION"
113 disp ""
114 disp "Pick a command:"
115 guilt_commands | sort | column | column -t | sed -e 's/^/ /'
117 disp ""
118 disp "Example:"
119 disp "\tguilt-push"
120 disp "or"
121 disp "\tguilt push"
123 # now, let's exit
124 exit 1
127 ########
130 # Library goodies
133 # usage: valid_patchname <patchname>
134 valid_patchname()
136 case "$1" in
137 /*|./*|../*|*/./*|*/../*|*/.|*/..|*/|*\ *|*\ *)
138 return 1;;
139 *:*)
140 return 1;;
142 return 0;;
143 esac
146 get_branch()
148 silent git symbolic-ref HEAD || \
149 die "Working on a detached HEAD is unsupported."
151 git symbolic-ref HEAD | sed -e 's,^refs/heads/,,'
154 verify_branch()
156 [ ! -d "$GIT_DIR/patches" ] &&
157 die "Patches directory doesn't exist, try guilt-init"
158 [ ! -d "$GIT_DIR/patches/$branch" ] &&
159 die "Branch $branch is not initialized, try guilt-init"
160 [ ! -f "$GIT_DIR/patches/$branch/series" ] &&
161 die "Branch $branch does not have a series file"
162 [ ! -f "$GIT_DIR/patches/$branch/status" ] &&
163 die "Branch $branch does not have a status file"
164 [ -f "$GIT_DIR/patches/$branch/applied" ] &&
165 die "Warning: Branch $branch has 'applied' file - guilt is not compatible with stgit"
168 get_top()
170 tail -n 1 "$GUILT_DIR/$branch/status"
173 get_prev()
175 if [ `wc -l < "$GUILT_DIR/$branch/status"` -gt 1 ]; then
176 tail -n 2 "$GUILT_DIR/$branch/status" | head_n 1
180 get_full_series()
182 # ignore all lines matching:
183 # - empty lines
184 # - whitespace only
185 # - optional whitespace followed by '#' followed by more
186 # optional whitespace
187 # also remove comments from end of lines
188 sed -n -e "/^[[:space:]]*\(#.*\)*\$/ ! {
189 s/[[:space:]]*#.*\$//
193 " $series
196 get_series()
198 get_full_series | while read p; do
199 check_guards "$p" && echo "$p"
200 done
203 # usage: check_guards <patch>
204 # Returns 0 if the patch should be pushed
205 check_guards()
207 get_guards "$1" | while read guard; do
208 g=`echo $guard | sed "s/^[+-]//"`
209 case "$guard" in
211 # Push +guard *only if* guard selected
212 silent grep -F "$g" "$guards_file" || return 1
215 # Push -guard *unless* guard selected
216 silent grep -F "$g" "$guards_file" && return 1
217 true
219 esac
220 done
222 # propagate return from subshell
223 return $?
226 # usage: get_guards <patch>
227 get_guards()
229 awk -v pname="$1" '
230 ($1 == pname) {
231 guards = "";
233 for(i=2; i<=NF; i++) {
234 sub(/#[^+-]*/, "", $i);
235 if (length($i)) {
236 if (length(guards))
237 guards = guards " " $i;
238 else
239 guards = $i;
243 print guards;
244 }' < "$series"
247 # usage: set_guards <patch> <guards...>
248 set_guards()
251 p="$1"
252 shift
253 for x in "$@"; do
254 case "$x" in
255 [+-]*)
256 awk -v pname="$p" -v newguard="$x" '{
257 if ($1 == pname)
258 print $0 " #" newguard;
259 else
260 print $0;
261 }' < "$series" > "$series.tmp"
262 mv "$series.tmp" "$series"
265 echo "'$x' is not a valid guard name" >&2
267 esac
268 done
272 # usage: unset_guards <patch> <guards...>
273 unset_guards()
276 p="$1"
277 shift
278 for x in "$@"; do
279 awk -v pname="$p" -v oldguard="$x" '{
280 if ($1 == pname) {
281 guards = "";
283 for(i=2; i<=NF; i++) {
284 if ($i == "#" oldguard)
285 continue;
287 if (length(guards))
288 guards = guards " " $i;
289 else
290 guards = $i;
293 if (length(guards))
294 print $1 " " guards;
295 else
296 print $1;
297 } else
298 print $0;
299 }' < "$series" > "$series.tmp"
300 mv "$series.tmp" "$series"
301 done
305 # usage: do_make_header <hash>
306 do_make_header()
308 # we should try to work with commit objects only
309 if [ `git cat-file -t "$1"` != "commit" ]; then
310 disp "Hash $1 is not a commit object" >&2
311 disp "Aborting..." >&2
312 exit 2
315 git cat-file -p "$1" | awk '
316 BEGIN{headers=1; firstline=1}
317 /^author / && headers {
318 sub(/^author +/, "");
319 sub(/ [0-9]* [+-]*[0-9][0-9]*$/, "");
320 author=$0
322 !headers {
323 print
324 if (firstline) {
325 firstline = 0;
326 print "\nFrom: " author;
329 /^$/ && headers { headers = 0 }
333 # usage: do_get_patch patchfile
334 do_get_patch()
336 cat "$1" | awk '
337 BEGIN{}
338 /^(diff |---$|--- )/,/END{}/
342 # usage: do_get_header patchfile
343 do_get_header()
345 # The complexity arises from the fact that we want to ignore all
346 # but the Subject line of the header, and any empty lines after it,
347 # if these exist, and inject only the Subject line as the first
348 # line of the commit message.
350 # 1st line prints first encountered Subject line plus empty line.
351 # 2nd line skips standard email/git patch header lines.
352 # 3rd line skips tip's additional header lines.
353 # 4th line skips any empty lines thereafter.
354 # 5th line turns off empty line skip upon seeing a non-empty line.
355 # 6th line terminates execution when we encounter the diff
356 cat "$1" | awk '
357 BEGIN{body=0; subj=0}
358 /^Subject:/ && (body == 0 && subj == 0){subj=1; print substr($0, 10) "\n"; next}
359 /^(Subject:|From:|Author:|Date:|commit)/ && (body == 0){next}
360 /^(Commit-ID:|Gitweb:|AuthorDate:|Committer:CommitDate:)/ && (body == 0){next}
361 /^[ \t\f\n\r\v]*$/ && (body==0){next}
362 /^.*$/ && (body==0){body=1}
363 /^(diff |---$|--- )/{exit}
364 {print $0}
365 END{}
369 # usage: do_get_full_header patchfile
370 do_get_full_header()
372 # 2nd line checks for the begining of a patch
373 # 3rd line outputs the line if it didn't get pruned by the above rules
374 cat "$1" | awk '
375 BEGIN{}
376 /^(diff |---$|--- )/{exit}
377 {print $0}
378 END{}
382 # usage: assert_head_check
383 assert_head_check()
385 if ! head_check refs/patches/$branch/`get_top`; then
386 die "aborting..."
390 # usage: head_check <expected hash>
391 head_check()
393 # make sure we're not doing funky things to commits that don't
394 # belong to us
396 case "$1" in
398 # the expected hash is empty
399 return 0 ;;
400 refs/patches/$branch/)
401 # the expected hash is an invalid rev
402 return 0 ;;
403 esac
405 if [ "`git rev-parse refs/heads/$branch`" != "`git rev-parse $1`" ]; then
406 disp "Expected HEAD commit $1" >&2
407 disp " got `git rev-parse refs/heads/$branch`" >&2
408 return 1
410 return 0
413 # usage: series_insert_patch <patchname>
414 series_insert_patch()
416 awk -v top="`get_top`" -v new="$1" \
417 'BEGIN{if (top == "") print new;}
419 print $0;
420 if (top != "" && top == $0) print new;
421 }' "$series" > "$series.tmp"
422 mv "$series.tmp" "$series"
425 # usage: series_remove_patch <patchname>
426 series_remove_patch()
428 grep -v "^$1\([[:space:]].*\)\?$" < "$series" > "$series.tmp"
429 mv "$series.tmp" "$series"
432 # usage: series_rename_patch <oldname> <newname>
433 series_rename_patch()
435 # Rename the patch, but preserve comments on the line
436 awk -v old="$1" -v new="$2" '
438 if (index($0, old) == 1)
439 print new substr($0, length(old) + 1);
440 else
441 print $0;
442 }' "$series" > "$series.tmp"
444 mv "$series.tmp" "$series"
447 # usage: series_rename_patch <oldpatchname> <newpatchname>
448 ref_rename_patch()
450 git update-ref "refs/patches/$branch/$2" `git rev-parse "refs/patches/$branch/$1"`
451 remove_ref "refs/patches/$branch/$1"
454 # Beware! This is one of the few (only?) places where we modify the applied
455 # file directly
457 # usage: applied_rename_patch <oldname> <newname>
458 applied_rename_patch()
460 awk -v old="$1" -v new="$2" \
461 'BEGIN{FS=":"}
462 { if ($0 == old)
463 print new;
464 else
465 print;
466 }' "$applied" > "$applied.tmp"
468 mv "$applied.tmp" "$applied"
471 # usage: remove_patch_refs
472 # reads patch names from stdin
473 remove_patch_refs()
475 while read pname; do
476 remove_ref "refs/patches/$branch/$pname"
477 done
480 # usage: pop_many_patches <commitish> <number of patches>
481 pop_many_patches()
483 assert_head_check
486 cd_to_toplevel
488 # remove the patches refs
489 tail -n $2 < "$applied" | remove_patch_refs
491 git reset --hard "$1" > /dev/null
493 n=`wc -l < "$applied"`
494 n=`expr $n - $2`
495 head_n "$n" < "$applied" > "$applied.tmp"
496 mv "$applied.tmp" "$applied"
500 # usage: pop_all_patches
501 pop_all_patches()
503 pop_many_patches \
504 `git rev-parse refs/patches/$branch/$(head_n 1 "$applied")^` \
505 `wc -l < "$applied"`
508 # usage: remove_ref <refname>
509 remove_ref()
512 # does the ref exist?
513 r=`git show-ref --verify -s "$1" 2> /dev/null`
514 [ $? -ne 0 ] && exit 0
516 # remove it
517 git update-ref -d "$1" "$r"
521 # usage: commit patchname parent
522 commit()
525 TMP_MSG=`get_tmp_file msg`
527 p="$GUILT_DIR/$branch/$1"
528 pname="$1"
529 cd_to_toplevel
531 git diff-files --name-only | (while read n; do git update-index "$n" ; done)
533 # grab a commit message out of the patch
534 do_get_header "$p" > "$TMP_MSG"
536 # make a default commit message if patch doesn't contain one
537 [ ! -s "$TMP_MSG" ] && echo "patch $pname" > "$TMP_MSG"
539 # extract author and date lines from the patch header, and set
540 # GIT_AUTHOR_{NAME,EMAIL,DATE}
541 # prefering Author/AuthorDate lines if available.
542 author_str=`sed -n -e '/^Author:/ { s/^Author: //; p; q; }; /^(diff |---$|--- )/ q' "$p"`
543 if [ -z "$author_str" ]; then
544 author_str=`sed -n -e '/^From:/ { s/^From: //; p; q; }; /^(diff |---$|--- )/ q' "$p"`
547 if [ ! -z "$author_str" ]; then
548 GIT_AUTHOR_NAME=`echo $author_str | sed -e 's/ *<.*$//'`
549 export GIT_AUTHOR_NAME="${GIT_AUTHOR_NAME:-" "}"
550 export GIT_AUTHOR_EMAIL="`echo $author_str | sed -e 's/[^<]*//'`"
552 author_date_str=`sed -n -e '/^AuthorDate:/ { s/^AuthorDate: //; p; q; }; /^(diff |---$|--- )/ q' "$p"`
553 if [ -z "$author_date_str" ]; then
554 author_date_str=`sed -n -e '/^Date:/ { s/^Date: //; p; q; }; /^(diff |---$|--- )/ q' "$p"`
556 if [ ! -z "$author_date_str" ]; then
557 export GIT_AUTHOR_DATE=`echo $author_date_str`
561 # `git log -1 --pretty=%ct` doesn't work on Git 1.5.x
562 ct=`git cat-file commit HEAD | awk '/^committer /{ print $(NF-1); exit; }'`
563 if [ $ct -gt `last_modified "$p"` ]; then
564 ct=`expr $ct + 60`
565 if [ $ct -gt `date +%s` ]; then
566 touch "$p"
567 else
568 touch_date $ct "$p"
572 export GIT_COMMITTER_DATE="`format_last_modified "$p"`"
574 # export GIT_AUTHOR_DATE only if a Date line was unavailable
575 if [ -z "$author_date_str" ]; then
576 export GIT_AUTHOR_DATE="$GIT_COMMITTER_DATE"
579 # commit
580 treeish=`git write-tree`
581 commitish=`git commit-tree $treeish -p $2 < "$TMP_MSG"`
582 git update-ref HEAD $commitish
584 # mark patch as applied
585 git update-ref "refs/patches/$branch/$pname" HEAD
587 rm -f "$TMP_MSG"
591 # usage: push_patch patchname [bail_action]
592 push_patch()
594 __push_patch_bail=0
597 TMP_LOG=`get_tmp_file log`
599 p="$GUILT_DIR/$branch/$1"
600 pname="$1"
601 bail_action="$2"
602 reject="--reject"
604 assert_head_check
605 cd_to_toplevel
607 # apply the patch if and only if there is something to apply
608 if [ `git apply --numstat "$p" | wc -l` -gt 0 ]; then
609 if [ "$bail_action" = abort ]; then
610 reject=""
612 git apply -C$guilt_push_diff_context --index \
613 $reject "$p" > /dev/null 2> "$TMP_LOG"
614 __push_patch_bail=$?
616 if [ $__push_patch_bail -ne 0 ]; then
617 cat "$TMP_LOG" >&2
618 if [ "$bail_action" = "abort" ]; then
619 rm -f "$TMP_LOG" "$TMP_MSG"
620 return $__push_patch_bail
625 commit "$pname" HEAD
627 echo "$pname" >> $applied
629 rm -f "$TMP_LOG"
632 # sub-shell funky-ness
633 __push_patch_bail=$?
635 return $__push_patch_bail
638 # usage: must_commit_first
639 must_commit_first()
641 git update-index --refresh --unmerged -q > /dev/null
642 [ `git diff-files | wc -l` -eq 0 ] || return $?
643 [ `git diff-index HEAD | wc -l` -eq 0 ]
644 return $?
647 # usage: fold_patch patchname
648 fold_patch()
650 set -- "$1" "`get_top`"
652 assert_head_check
654 push_patch "$1"
656 # merge the patch headers
658 pcur="$GUILT_DIR/$branch/$2"
659 pnext="$GUILT_DIR/$branch/$1"
660 TMP_CUR=`get_tmp_file diff-cur`
661 TMP_NEXT=`get_tmp_file diff-next`
662 TMP_DIFF=`get_tmp_file diff`
663 do_get_full_header "$pcur" > "$TMP_CUR"
664 do_get_full_header "$pnext" > "$TMP_NEXT"
665 do_get_patch "$pcur" > "$TMP_DIFF"
667 case "`stat -c %s \"$TMP_CUR\"`,`stat -c %s \"$TMP_NEXT\"`" in
668 *,0)
669 # since the new patch header is empty, we
670 # don't have to do anything
672 0,*)
673 # current is empty; new is not
674 mv "$pcur" "$pcur~"
675 cat "$TMP_NEXT" > "$pcur"
676 cat "$TMP_DIFF" >> "$pcur"
678 *,*)
679 mv "$pcur" "$pcur~"
680 cat "$TMP_CUR" > "$pcur"
681 echo >> "$pcur"
682 echo "Header from folded patch '$1':" >> "$pcur"
683 echo >> "$pcur"
684 cat "$TMP_NEXT" >> "$pcur"
685 cat "$TMP_DIFF" >> "$pcur"
687 esac
689 rm -f "$TMP_CUR" "$TMP_NEXT" "$TMP_DIFF"
692 __refresh_patch "$2" HEAD^^ 2 "" ""
694 series_remove_patch "$1"
697 # usage: refresh_patch patchname gengitdiff incldiffstat
698 refresh_patch()
700 __refresh_patch "$1" HEAD^ 1 "$2" "$3"
703 # usage: __refresh_patch patchname commitish number_of_commits gengitdiff
704 # incldiffstat
705 __refresh_patch()
707 assert_head_check
710 TMP_DIFF=`get_tmp_file diff`
712 cd_to_toplevel
713 p="$GUILT_DIR/$branch/$1"
714 pname="$1"
716 # get the patch header
717 do_get_full_header "$p" > "$TMP_DIFF"
719 [ ! -z "$4" ] && diffopts="-C -M --find-copies-harder"
721 if [ -n "$5" -o $diffstat = "true" ]; then
723 echo "---"
724 git diff --stat $diffopts "$2"
725 echo ""
726 ) >> "$TMP_DIFF"
729 # get the new patch
730 git diff --binary $diffopts "$2" >> "$TMP_DIFF"
732 # move the new patch in
733 mv "$p" "$p~"
734 mv "$TMP_DIFF" $p
736 # commit
737 commit "$pname" "HEAD~$3"
739 # drop folded patches
740 N=`expr "$3" - 1`
742 # remove the patches refs
743 tail -n $N < "$applied" | remove_patch_refs
745 n=`wc -l < "$applied"`
746 n=`expr $n - $N`
747 head_n "$n" < "$applied" > "$applied.tmp"
748 mv "$applied.tmp" "$applied"
752 # usage: munge_hash_range <hash range>
754 # this means:
755 # <hash> - one commit
756 # <hash>.. - hash until head (excludes hash, includes head)
757 # ..<hash> - until hash (includes hash)
758 # <hash1>..<hash2> - from hash to hash (inclusive)
760 # The output of this function is suitable to be passed to "git rev-list"
761 munge_hash_range()
763 case "$1" in
764 *..*..*|*\ *)
765 # double .. or space is illegal
766 return 1;;
767 ..*)
768 # e.g., "..v0.10"
769 echo ${1#..};;
770 *..)
771 # e.g., "v0.19.."
772 echo ${1%..}..HEAD;;
773 *..*)
774 # e.g., "v0.19-rc1..v0.19"
775 echo ${1%%..*}..${1#*..};;
777 # e.g., "v0.19"
778 echo $1^..$1;;
779 *) # empty
780 return 1;;
781 esac
782 return 0
785 # usage: get_tmp_file <prefix> [<opts>]
787 # Get a unique filename and create the file in a non-racy way
788 get_tmp_file()
790 while true; do
791 mktemp $2 "/tmp/guilt.$1.XXXXXXXXXXXXXXX" && break
792 done
795 # usage: guilt_hook <hook name> <args....>
796 guilt_hook()
798 __hookname="$1"
799 [ ! -x "$GIT_DIR/hooks/guilt/$__hookname" ] && return 0
801 shift
803 "$GIT_DIR/hooks/guilt/$__hookname" "$@"
804 return $?
808 # Some constants
811 # used for: git apply -C <val>
812 guilt_push_diff_context=1
814 # default diffstat value: true or false
815 DIFFSTAT_DEFAULT="false"
818 # Parse any part of .git/config that belongs to us
821 # generate diffstat?
822 diffstat=`git config --bool guilt.diffstat`
823 [ -z "$diffstat" ] && diffstat=$DIFFSTAT_DEFAULT
826 # The following gets run every time this file is source'd
829 GUILT_DIR="$GIT_DIR/patches"
831 branch=`get_branch`
833 # most of the time we want to verify that the repo's branch has been
834 # initialized, but every once in a blue moon (e.g., we want to run guilt-init),
835 # we must avoid the checks
836 if [ -z "$DO_NOT_CHECK_BRANCH_EXISTENCE" ]; then
837 verify_branch
839 # do not check the status file format (guilt-repair needs this,
840 # otherwise nothing can do what's necessary to bring the repo into a
841 # useable state)
842 if [ -z "$DO_NOT_CHECK_STATUS_FILE_FORMAT" ]; then
843 [ -s "$GIT_DIR/patches/$branch/status" ] &&
844 grep "^[0-9a-f]\{40\}:" "$GIT_DIR/patches/$branch/status" > /dev/null &&
845 die "Status file appears to use old format, try guilt-repair --status"
849 # very useful files
850 series="$GUILT_DIR/$branch/series"
851 applied="$GUILT_DIR/$branch/status"
852 guards_file="$GUILT_DIR/$branch/guards"
854 # determine a pager to use for anything interactive (fall back to more)
855 pager="more"
856 [ ! -z "$PAGER" ] && pager="$PAGER"
858 UNAME_S=`uname -s`
860 if [ -r "`dirname $0`/os.$UNAME_S" ]; then
861 . "`dirname $0`/os.$UNAME_S"
862 else
863 die "Unsupported operating system: $UNAME_S"