Skip to content

Commit 5a79873

Browse files
authored
Merge pull request #850 from vr8hub/newundo
Modify to work when only a single commit, add parameter checks
2 parents 90495d0 + 27f42be commit 5a79873

File tree

1 file changed

+46
-11
lines changed

1 file changed

+46
-11
lines changed

bin/git-undo

Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,27 @@
11
#!/usr/bin/env bash
22

3-
back="^"
3+
cstr="commits"
4+
ccnt=$(git rev-list --count HEAD)
5+
if [ $ccnt -eq 1 ]; then cstr="commit"; fi
6+
parm3=""
7+
8+
function _undo()
9+
{
10+
type=${1:-soft}
11+
undo_cnt=${2:-1}
12+
reset=${3:-""}
13+
14+
if [ $undo_cnt -gt $ccnt ]; then
15+
echo "Only $ccnt $cstr, cannot undo $undo_cnt"
16+
elif [ "$type" = "hard" ] && [ $ccnt -eq $undo_cnt ]; then
17+
echo "Cannot hard undo all commits"
18+
elif [ "$type" = "soft" ] && [ $ccnt -eq 1 ]; then
19+
git update-ref -d HEAD
20+
else
21+
git reset --$type HEAD~$undo_cnt
22+
fi
23+
if [ "$reset" != "" ]; then git reset; fi
24+
}
425

526
case "$1" in
627
-h)
@@ -12,26 +33,40 @@ EOL
1233
read -r res
1334
case "${res}" in
1435
"Y" | "y")
15-
test $2 -gt 1 > /dev/null 2>&1 && back="~$2"
16-
git reset --hard HEAD$back
17-
exit $?
36+
parm1=hard
37+
parm2=${2:-1}
1838
;;
1939
* )
2040
exit 0
2141
;;
2242
esac
2343
;;
2444
--hard)
25-
test $2 -gt 1 > /dev/null 2>&1 && back="~$2"
26-
git reset --hard HEAD$back
45+
parm1=hard
46+
parm2=${2:-1}
2747
;;
2848
-s|--soft)
29-
test $2 -gt 1 > /dev/null 2>&1 && back="~$2"
30-
git reset --soft HEAD$back
49+
parm1=soft
50+
parm2=${2:-1}
51+
parm3=reset
52+
;;
53+
"")
54+
parm1=soft
55+
parm2=1
56+
;;
57+
*[!0-9]*)
58+
echo "Invalid parameter: $1"
59+
exit 1
3160
;;
3261
*)
33-
test $1 -gt 1 > /dev/null 2>&1 && back="~$1"
34-
git reset --soft HEAD$back
35-
git reset
62+
parm1=soft
63+
parm2="$1"
3664
;;
3765
esac
66+
67+
if [[ ! $parm2 =~ ^[1-9][0-9]*$ ]]; then
68+
echo "Invalid undo count: $parm2"
69+
exit 1
70+
fi
71+
72+
_undo $parm1 $parm2 $parm3

0 commit comments

Comments
 (0)