[GUILT 3/6] Handle paths that contain spaces
[guilt.git] / guilt
blobe433b32142cecb6b6b2a3571bc2c429467a0e76a
1 #!/bin/sh
3 # Copyright (c) Josef "Jeff" Sipek, 2006-2011
6 GUILT_VERSION="0.35"
7 GUILT_NAME="Gloria"
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
42 usage()
44 echo "Usage: guilt $CMDNAME $USAGE" >&2
45 exit 1
48 # echo -n is a bashism, use printf instead
49 _disp()
51 printf "%b" "$*"
54 # echo -e is a bashism, use printf instead
55 disp()
57 printf "%b\n" "$*"
60 noerr()
62 "$@" 2>/dev/null
65 silent()
67 "$@" >/dev/null 2>/dev/null
70 ########
72 guilt_commands()
74 find "`dirname $0`/../lib/guilt" -maxdepth 1 -name "guilt-*" -type f -perm +111 2> /dev/null | sed -e "s/.*\\/`basename $0`-//"
75 find "`dirname $0`" -maxdepth 1 -name "guilt-*" -type f -perm +111 | sed -e "s/.*\\/`basename $0`-//"
78 # by default, we shouldn't fail
79 cmd=
81 if [ $# -ne 0 ]; then
82 # take first arg, and try to execute it
84 arg="$1"
85 dir=`dirname $0`
86 libdir="`dirname $0`/../lib/guilt"
88 if [ -x "$dir/guilt-$arg" ]; then
89 cmd="$dir/guilt-$arg"
90 CMDNAME=$arg
91 elif [ -x "$libdir/guilt-$arg" ]; then
92 cmd="$libdir/guilt-$arg"
93 CMDNAME=$arg
94 else
95 # might be a short handed
96 for command in $(guilt_commands); do
97 case $command in
98 $arg*)
99 if [ -x "$dir/guilt-$command" ]; then
100 cmd="$dir/guilt-$command"
101 CMDNAME=$command
102 elif [ -x "$libdir/guilt-$command" ]; then
103 cmd="$libdir/guilt-$command"
104 CMDNAME=$command
107 esac
108 done
110 if [ -z "$cmd" ]; then
111 disp "Command $arg not found" >&2
112 disp "" >&2
113 exit 1
116 shift
117 else
118 # no args passed or invalid command entered, just output help summary
120 disp "Guilt v$GUILT_VERSION"
121 disp ""
122 disp "Pick a command:"
123 guilt_commands | sort | column | column -t | sed -e 's/^/ /'
125 disp ""
126 disp "Example:"
127 disp "\tguilt push"
129 # now, let's exit
130 exit 1
133 ########
136 # Library goodies
139 # usage: valid_patchname <patchname>
140 valid_patchname()
142 case "$1" in
143 /*|./*|../*|*/./*|*/../*|*/.|*/..|*/|*\ *|*\ *)
144 return 1;;
145 *:*)
146 return 1;;
148 return 0;;
149 esac
152 get_branch()
154 silent git symbolic-ref HEAD || \
155 die "Working on a detached HEAD is unsupported."
157 git symbolic-ref HEAD | sed -e 's,^refs/heads/,,'
160 verify_branch()
162 [ ! -d "$GIT_DIR/patches" ] &&
163 die "Patches directory doesn't exist, try guilt init"
164 [ ! -d "$GIT_DIR/patches/$branch" ] &&
165 die "Branch $branch is not initialized, try guilt init"
166 [ ! -f "$GIT_DIR/patches/$branch/series" ] &&
167 die "Branch $branch does not have a series file"
168 [ ! -f "$GIT_DIR/patches/$branch/status" ] &&
169 die "Branch $branch does not have a status file"
170 [ -f "$GIT_DIR/patches/$branch/applied" ] &&
171 die "Warning: Branch $branch has 'applied' file - guilt is not compatible with stgit"
174 get_top()
176 tail -n 1 "$GUILT_DIR/$branch/status"
179 get_prev()
181 if [ `wc -l < "$GUILT_DIR/$branch/status"` -gt 1 ]; then
182 tail -n 2 "$GUILT_DIR/$branch/status" | head_n 1
186 get_full_series()
188 # ignore all lines matching:
189 # - empty lines
190 # - whitespace only
191 # - optional whitespace followed by '#' followed by more
192 # optional whitespace
193 # also remove comments from end of lines
194 sed -n -e "/^[[:space:]]*\(#.*\)*\$/ ! {
195 s/[[:space:]]*#.*\$//
199 " "$series"
202 get_series()
204 get_full_series | while read p; do
205 check_guards "$p" && echo "$p"
206 done
209 # usage: check_guards <patch>
210 # Returns 0 if the patch should be pushed
211 check_guards()
213 get_guards "$1" | while read guard; do
214 g=`echo $guard | sed "s/^[+-]//"`
215 case "$guard" in
217 # Push +guard *only if* guard selected
218 silent grep -F "$g" "$guards_file" || return 1
221 # Push -guard *unless* guard selected
222 silent grep -F "$g" "$guards_file" && return 1
223 true
225 esac
226 done
228 # propagate return from subshell
229 return $?
232 # usage: get_guards <patch>
233 get_guards()
235 awk -v pname="$1" '
236 ($1 == pname) {
237 guards = "";
239 for(i=2; i<=NF; i++) {
240 sub(/#[^+-]*/, "", $i);
241 if (length($i)) {
242 if (length(guards))
243 guards = guards " " $i;
244 else
245 guards = $i;
249 print guards;
250 }' < "$series"
253 # usage: set_guards <patch> <guards...>
254 set_guards()
257 p="$1"
258 shift
259 for x in "$@"; do
260 case "$x" in
261 [+-]*)
262 awk -v pname="$p" -v newguard="$x" '{
263 if ($1 == pname)
264 print $0 " #" newguard;
265 else
266 print $0;
267 }' < "$series" > "$series.tmp"
268 mv "$series.tmp" "$series"
271 echo "'$x' is not a valid guard name" >&2
273 esac
274 done
278 # usage: unset_guards <patch> <guards...>
279 unset_guards()
282 p="$1"
283 shift
284 for x in "$@"; do
285 awk -v pname="$p" -v oldguard="$x" '{
286 if ($1 == pname) {
287 guards = "";
289 for(i=2; i<=NF; i++) {
290 if ($i == "#" oldguard)
291 continue;
293 if (length(guards))
294 guards = guards " " $i;
295 else
296 guards = $i;
299 if (length(guards))
300 print $1 " " guards;
301 else
302 print $1;
303 } else
304 print $0;
305 }' < "$series" > "$series.tmp"
306 mv "$series.tmp" "$series"
307 done
311 # usage: do_make_header <hash>
312 do_make_header()
314 # we should try to work with commit objects only
315 if [ `git cat-file -t "$1"` != "commit" ]; then
316 disp "Hash $1 is not a commit object" >&2
317 disp "Aborting..." >&2
318 exit 2
321 git cat-file -p "$1" | awk '
322 BEGIN{headers=1; firstline=1}
323 /^author / && headers {
324 sub(/^author +/, "");
325 sub(/ [0-9]* [+-]*[0-9][0-9]*$/, "");
326 author=$0
328 !headers {
329 print
330 if (firstline) {
331 firstline = 0;
332 print "\nFrom: " author;
335 /^$/ && headers { headers = 0 }
339 # usage: do_get_patch patchfile
340 do_get_patch()
342 cat "$1" | awk '
343 BEGIN{}
344 /^(diff |---$|--- )/ {patch = 1}
345 patch == 1 {print $0}
346 END{}
350 # usage: do_get_header patchfile
351 do_get_header()
353 # The complexity arises from the fact that we want to ignore all but the
354 # Subject line of the header, and any empty lines after it, if these
355 # exist, and inject only the Subject line as the first line of the
356 # commit message.
358 # We also need to strip "from:" lines from the body of the patch
359 # description as these are used by people to manually set the author of
360 # the patch to be different to their local email address and failing to
361 # strip them results in duplicate from: lines in output from guilt
362 # patchbomb.
364 # 1st line prints first encountered Subject line plus empty line.
365 # 2nd line skips standard email/git patch header lines.
366 # 3th line skips "from:" lines throughout the patch description
367 # 4rd line skips tip's additional header lines.
368 # 5th line skips any empty lines thereafter.
369 # 6th line turns off empty line skip upon seeing a non-empty line.
370 # 7th line terminates execution when we encounter the diff
371 awk '
372 BEGIN{body=0; subj=0}
373 /^Subject:/ && (body == 0 && subj == 0){subj=1; print substr($0, 10) "\n"; next}
374 /^(Subject:|Author:|Date:|commit)/ && (body == 0){next}
375 /^From:/ {next}
376 /^(Commit-ID:|Gitweb:|AuthorDate:|Committer:CommitDate:)/ && (body == 0){next}
377 /^[ \t\f\n\r\v]*$/ && (body==0){next}
378 /^.*$/ && (body==0){body=1}
379 /^(diff |---$|--- )/{exit}
380 {print $0}
381 END{}
382 ' < "$1"
385 # usage: do_get_full_header patchfile
386 do_get_full_header()
388 # 2nd line checks for the begining of a patch
389 # 3rd line outputs the line if it didn't get pruned by the above rules
390 awk '
391 BEGIN{}
392 /^(diff |---$|--- )/{exit}
393 {print $0}
394 END{}
395 ' < "$1"
398 # usage: assert_head_check
399 assert_head_check()
401 if ! head_check refs/patches/$branch/`get_top`; then
402 die "aborting..."
406 # usage: head_check <expected hash>
407 head_check()
409 # make sure we're not doing funky things to commits that don't
410 # belong to us
412 case "$1" in
414 # the expected hash is empty
415 return 0 ;;
416 refs/patches/$branch/)
417 # the expected hash is an invalid rev
418 return 0 ;;
419 esac
421 if [ "`git rev-parse refs/heads/$branch`" != "`git rev-parse $1`" ]; then
422 disp "Expected HEAD commit $1" >&2
423 disp " got `git rev-parse refs/heads/$branch`" >&2
424 return 1
426 return 0
429 # usage: series_insert_patch <patchname>
430 series_insert_patch()
432 awk -v top="`get_top`" -v new="$1" \
433 'BEGIN{if (top == "") print new;}
435 print $0;
436 if (top != "" && top == $0) print new;
437 }' "$series" > "$series.tmp"
438 mv "$series.tmp" "$series"
441 # usage: series_remove_patch <patchname>
442 series_remove_patch()
444 grep -v "^$1\([[:space:]].*\)\?$" < "$series" > "$series.tmp"
445 mv "$series.tmp" "$series"
448 # usage: series_rename_patch <oldname> <newname>
449 series_rename_patch()
451 # Rename the patch, but preserve comments on the line
452 awk -v old="$1" -v new="$2" '
454 if (index($0, old) == 1)
455 print new substr($0, length(old) + 1);
456 else
457 print $0;
458 }' "$series" > "$series.tmp"
460 mv "$series.tmp" "$series"
463 # usage: series_rename_patch <oldpatchname> <newpatchname>
464 ref_rename_patch()
466 git update-ref "refs/patches/$branch/$2" `git rev-parse "refs/patches/$branch/$1"`
467 remove_ref "refs/patches/$branch/$1"
470 # Beware! This is one of the few (only?) places where we modify the applied
471 # file directly
473 # usage: applied_rename_patch <oldname> <newname>
474 applied_rename_patch()
476 awk -v old="$1" -v new="$2" \
477 'BEGIN{FS=":"}
478 { if ($0 == old)
479 print new;
480 else
481 print;
482 }' "$applied" > "$applied.tmp"
484 mv "$applied.tmp" "$applied"
487 # usage: remove_patch_refs
488 # reads patch names from stdin
489 remove_patch_refs()
491 while read pname; do
492 remove_ref "refs/patches/$branch/$pname"
493 done
496 # usage: pop_many_patches <commitish> <number of patches>
497 pop_many_patches()
499 assert_head_check
502 cd_to_toplevel
504 # remove the patches refs
505 tail -n $2 < "$applied" | remove_patch_refs
507 git reset --hard "$1" > /dev/null
509 n=`wc -l < "$applied"`
510 n=`expr $n - $2`
511 head_n "$n" < "$applied" > "$applied.tmp"
512 mv "$applied.tmp" "$applied"
516 # usage: pop_all_patches
517 pop_all_patches()
519 pop_many_patches \
520 `git rev-parse refs/patches/$branch/$(head_n 1 "$applied")^` \
521 `wc -l < "$applied"`
524 # usage: remove_ref <refname>
525 remove_ref()
528 # does the ref exist?
529 r=`git show-ref --verify -s "$1" 2> /dev/null`
530 [ $? -ne 0 ] && exit 0
532 # remove it
533 git update-ref -d "$1" "$r"
537 # usage: commit patchname parent
538 commit()
541 TMP_MSG=`get_tmp_file msg`
543 p="$GUILT_DIR/$branch/$1"
544 pname="$1"
545 cd_to_toplevel
547 git diff-files --name-only | (while read n; do git update-index "$n" ; done)
549 # grab a commit message out of the patch
550 do_get_header "$p" > "$TMP_MSG"
552 # make a default commit message if patch doesn't contain one
553 [ ! -s "$TMP_MSG" ] && echo "patch $pname" > "$TMP_MSG"
555 # extract author and date lines from the patch header, and set
556 # GIT_AUTHOR_{NAME,EMAIL,DATE}
557 # prefering Author/AuthorDate lines if available.
558 author_str=`sed -n -e '/^Author:/ { s/^Author: //; p; q; }; /^(diff |---$|--- )/ q' "$p"`
559 if [ -z "$author_str" ]; then
560 author_str=`sed -n -e '/^From:/ { s/^From: //; p; q; }; /^(diff |---$|--- )/ q' "$p"`
563 if [ ! -z "$author_str" ]; then
564 GIT_AUTHOR_NAME=`echo $author_str | sed -e 's/ *<.*$//'`
565 export GIT_AUTHOR_NAME="${GIT_AUTHOR_NAME:-" "}"
566 export GIT_AUTHOR_EMAIL="`echo $author_str | sed -e 's/[^<]*//'`"
568 author_date_str=`sed -n -e '/^AuthorDate:/ { s/^AuthorDate: //; p; q; }; /^(diff |---$|--- )/ q' "$p"`
569 if [ -z "$author_date_str" ]; then
570 author_date_str=`sed -n -e '/^Date:/ { s/^Date: //; p; q; }; /^(diff |---$|--- )/ q' "$p"`
572 if [ ! -z "$author_date_str" ]; then
573 export GIT_AUTHOR_DATE=`echo $author_date_str`
577 # `git log -1 --pretty=%ct` doesn't work on Git 1.5.x
578 ct=`git cat-file commit HEAD | awk '/^committer /{ print $(NF-1); exit; }'`
579 if [ $ct -gt `last_modified "$p"` ]; then
580 ct=`expr $ct + 60`
581 if [ $ct -gt `date +%s` ]; then
582 touch "$p"
583 else
584 touch_date $ct "$p"
588 export GIT_COMMITTER_DATE="`format_last_modified "$p"`"
590 # export GIT_AUTHOR_DATE only if a Date line was unavailable
591 if [ -z "$author_date_str" ]; then
592 export GIT_AUTHOR_DATE="$GIT_COMMITTER_DATE"
595 # commit
596 treeish=`git write-tree`
597 commitish=`git commit-tree $treeish -p $2 < "$TMP_MSG"`
598 git update-ref HEAD $commitish
600 # mark patch as applied
601 git update-ref "refs/patches/$branch/$pname" HEAD
603 rm -f "$TMP_MSG"
607 # usage: push_patch patchname [bail_action]
608 push_patch()
610 __push_patch_bail=0
613 TMP_LOG=`get_tmp_file log`
615 p="$GUILT_DIR/$branch/$1"
616 pname="$1"
617 bail_action="$2"
618 reject="--reject"
620 assert_head_check
621 cd_to_toplevel
623 # apply the patch if and only if there is something to apply
624 if [ `do_get_patch "$p" | wc -l` -gt 0 ]; then
625 if [ "$bail_action" = abort ]; then
626 reject=""
628 git apply -C$guilt_push_diff_context --index \
629 $reject "$p" > /dev/null 2> "$TMP_LOG"
630 __push_patch_bail=$?
632 if [ $__push_patch_bail -ne 0 ]; then
633 cat "$TMP_LOG" >&2
634 if [ "$bail_action" = "abort" ]; then
635 rm -f "$TMP_LOG" "$TMP_MSG"
636 return $__push_patch_bail
641 commit "$pname" HEAD
643 echo "$pname" >> "$applied"
645 rm -f "$TMP_LOG"
648 # sub-shell funky-ness
649 __push_patch_bail=$?
651 return $__push_patch_bail
654 # usage: must_commit_first
655 must_commit_first()
657 git update-index --refresh --unmerged -q > /dev/null
658 [ `git diff-files | wc -l` -eq 0 ] || return $?
659 [ `git diff-index HEAD | wc -l` -eq 0 ]
660 return $?
663 # usage: fold_patch patchname
664 fold_patch()
666 set -- "$1" "`get_top`"
668 assert_head_check
670 push_patch "$1"
672 # merge the patch headers
674 pcur="$GUILT_DIR/$branch/$2"
675 pnext="$GUILT_DIR/$branch/$1"
676 TMP_CUR=`get_tmp_file diff-cur`
677 TMP_NEXT=`get_tmp_file diff-next`
678 TMP_DIFF=`get_tmp_file diff`
679 do_get_full_header "$pcur" > "$TMP_CUR"
680 do_get_full_header "$pnext" > "$TMP_NEXT"
681 do_get_patch "$pcur" > "$TMP_DIFF"
683 case "`stat -c %s \"$TMP_CUR\"`,`stat -c %s \"$TMP_NEXT\"`" in
684 *,0)
685 # since the new patch header is empty, we
686 # don't have to do anything
688 0,*)
689 # current is empty; new is not
690 mv "$pcur" "$pcur~"
691 cat "$TMP_NEXT" > "$pcur"
692 cat "$TMP_DIFF" >> "$pcur"
694 *,*)
695 mv "$pcur" "$pcur~"
696 cat "$TMP_CUR" > "$pcur"
697 echo >> "$pcur"
698 echo "Header from folded patch '$1':" >> "$pcur"
699 echo >> "$pcur"
700 cat "$TMP_NEXT" >> "$pcur"
701 cat "$TMP_DIFF" >> "$pcur"
703 esac
705 rm -f "$TMP_CUR" "$TMP_NEXT" "$TMP_DIFF"
708 __refresh_patch "$2" HEAD^^ 2 "" ""
710 series_remove_patch "$1"
713 # usage: refresh_patch patchname gengitdiff incldiffstat
714 refresh_patch()
716 __refresh_patch "$1" HEAD^ 1 "$2" "$3"
719 # usage: __refresh_patch patchname commitish number_of_commits gengitdiff
720 # incldiffstat
721 __refresh_patch()
723 assert_head_check
726 TMP_DIFF=`get_tmp_file diff`
728 cd_to_toplevel
729 p="$GUILT_DIR/$branch/$1"
730 pname="$1"
732 # get the patch header
733 do_get_full_header "$p" > "$TMP_DIFF"
735 [ ! -z "$4" ] && diffopts="-C -M --find-copies-harder"
737 if [ -n "$5" -o $diffstat = "true" ]; then
739 echo "---"
740 git diff --stat $diffopts "$2"
741 echo ""
742 ) >> "$TMP_DIFF"
745 # get the new patch
746 git diff --binary $diffopts "$2" >> "$TMP_DIFF"
748 # move the new patch in
749 mv "$p" "$p~"
750 mv "$TMP_DIFF" "$p"
752 # commit
753 commit "$pname" "HEAD~$3"
755 # drop folded patches
756 N=`expr "$3" - 1`
758 # remove the patches refs
759 tail -n $N < "$applied" | remove_patch_refs
761 n=`wc -l < "$applied"`
762 n=`expr $n - $N`
763 head_n "$n" < "$applied" > "$applied.tmp"
764 mv "$applied.tmp" "$applied"
768 # usage: munge_hash_range <hash range>
770 # this means:
771 # <hash> - one commit
772 # <hash>.. - hash until head (excludes hash, includes head)
773 # ..<hash> - until hash (includes hash)
774 # <hash1>..<hash2> - from hash to hash (inclusive)
776 # The output of this function is suitable to be passed to "git rev-list"
777 munge_hash_range()
779 case "$1" in
780 *..*..*|*\ *)
781 # double .. or space is illegal
782 return 1;;
783 ..*)
784 # e.g., "..v0.10"
785 echo ${1#..};;
786 *..)
787 # e.g., "v0.19.."
788 echo ${1%..}..HEAD;;
789 *..*)
790 # e.g., "v0.19-rc1..v0.19"
791 echo ${1%%..*}..${1#*..};;
793 # e.g., "v0.19"
794 echo $1^..$1;;
795 *) # empty
796 return 1;;
797 esac
798 return 0
801 # usage: get_tmp_file <prefix> [<opts>]
803 # Get a unique filename and create the file in a non-racy way
804 get_tmp_file()
806 while true; do
807 mktemp $2 "/tmp/guilt.$1.XXXXXXXXXXXXXXX" && break
808 done
811 # usage: guilt_hook <hook name> <args....>
812 guilt_hook()
814 __hookname="$1"
815 [ ! -x "$GIT_DIR/hooks/guilt/$__hookname" ] && return 0
817 shift
819 "$GIT_DIR/hooks/guilt/$__hookname" "$@"
820 return $?
824 # source the command
826 . "$cmd"
829 # Some constants
832 # used for: git apply -C <val>
833 guilt_push_diff_context=1
835 # default diffstat value: true or false
836 DIFFSTAT_DEFAULT="false"
839 # Parse any part of .git/config that belongs to us
842 # generate diffstat?
843 diffstat=`git config --bool guilt.diffstat`
844 [ -z "$diffstat" ] && diffstat=$DIFFSTAT_DEFAULT
847 # The following gets run every time this file is source'd
850 GUILT_DIR="$GIT_DIR/patches"
852 branch=`get_branch`
854 # most of the time we want to verify that the repo's branch has been
855 # initialized, but every once in a blue moon (e.g., we want to run guilt init),
856 # we must avoid the checks
857 if [ -z "$DO_NOT_CHECK_BRANCH_EXISTENCE" ]; then
858 verify_branch
860 # do not check the status file format (guilt repair needs this,
861 # otherwise nothing can do what's necessary to bring the repo into a
862 # useable state)
863 if [ -z "$DO_NOT_CHECK_STATUS_FILE_FORMAT" ]; then
864 [ -s "$GIT_DIR/patches/$branch/status" ] &&
865 grep "^[0-9a-f]\{40\}:" "$GIT_DIR/patches/$branch/status" > /dev/null &&
866 die "Status file appears to use old format, try guilt repair --status"
870 # very useful files
871 series="$GUILT_DIR/$branch/series"
872 applied="$GUILT_DIR/$branch/status"
873 guards_file="$GUILT_DIR/$branch/guards"
875 # determine a pager to use for anything interactive (fall back to more)
876 pager="more"
877 [ ! -z "$PAGER" ] && pager="$PAGER"
879 UNAME_S=`uname -s`
881 if [ -r "`dirname $0`/os.$UNAME_S" ]; then
882 . "`dirname $0`/os.$UNAME_S"
883 elif [ -r "`dirname $0`/../lib/guilt/os.$UNAME_S" ]; then
884 . "`dirname $0`/../lib/guilt/os.$UNAME_S"
885 else
886 die "Unsupported operating system: $UNAME_S"
889 _main "$@"