proper error exit on no revision found
[xonotic/div0-gittools.git] / git-identify-revision
1 #!/bin/sh
2
3 # situation: work tree is unknown rev
4 # arguments: git rev-list arguments
5 # we now identify the one revision with least differences
6
7 usage()
8 {
9         echo "Usage: $0 [--cached] git-rev-list args..."
10         echo
11         echo "Example: $0 --all"
12         echo "Compares current work tree to all revisions, and identifies the"
13         echo "closest match."
14         echo
15         echo "Example: $0 --cached v1.0..HEAD"
16         echo "Compares current work tree to all revisions between v1.0 and HEAD,"
17         echo "and identifies the closest match."
18 }
19
20 case "$1" in
21         --cached)
22                 use_worktree=false
23                 shift
24                 ;;
25         --help|-h)
26                 usage
27                 exit 0
28                 ;;
29         *)
30                 use_worktree=true
31                 ;;
32 esac
33
34 if [ $# = 0 ]; then
35         usage >&2
36         exit 1
37 fi
38
39 diffopts="-M -C"
40
41 if $use_worktree; then
42         echo >&2 "Saving index..."
43         oldindex=`git write-tree`
44         # set up resetting
45         trap 'echo >&2 "Restoring index..."; git reset "$oldindex" .' EXIT
46         trap 'exit 1' INT TERM
47
48         echo >&2 "Creating index..."
49         git add -A
50 fi
51
52 echo >&2 "Listing candidates..."
53 allrevs=`git rev-list "$@"`
54
55 echo >&2 "Evaluating candidates..."
56 bestrev=
57 bestrevscore=
58 for rev in $allrevs; do
59         score=`git diff $diffopts --cached "$rev" | wc -l`
60         if [ -z "$bestrevscore" ] || [ "$score" -lt "$bestrevscore" ]; then
61                 echo >&2 "Improved to $rev (score: $score)"
62                 bestrev=$rev
63                 bestrevscore=$score
64                 if [ $score -eq 0 ]; then
65                         break
66                 fi
67         fi
68 done
69 echo >&2 "Done."
70
71 if [ -z "$bestrevscore" ]; then
72         exit 1
73 fi
74
75 echo "$bestrev"
76 git diff $diffopts --cached "$bestrev" >&2