summaryrefslogtreecommitdiff
path: root/bin/git-edit-commit
blob: cec9748a627c85d896559e54dfd0c6496b7828cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/bin/sh
# Copyright (C) 2015 The Qt Company Ltd.
# Contact: http://www.qt.io/licensing/
#
# You may use this file under the terms of the 3-clause BSD license.
# See the file LICENSE from this package for details.
#

if test "x$EDITOR" = "x$0" ; then
    # The script was launched as an $EDITOR from git rebase -i.
    # Modify the pick line to an edit line and just exit.
    sed -e '1,$s/^pick '"$SHORT_SHA1 /edit $SHORT_SHA1 /" < "$1" >/tmp/editcommit$$
    mv /tmp/editcommit$$ "$1"
    exit 0
fi

# Extract the SHA-1 from the command-line and validate it.
MODE=message
if test "x$1" = "x--source" ; then
    MODE=source
    shift
fi
if test -z "$1" ; then
    echo "Usage: $0 [--source] sha-1"
    echo ""
    echo "git-edit-commit allows you to edit a git commit to change"
    echo "the commit message, even if it is several hundred changes back."
    echo "It is equivalent to 'git rebase -i', but slightly safer."
    echo ""
    echo "The --source option specifies that you want to edit the source"
    echo "as well as the commit message.  This starts a 'git rebase -i'"
    echo "which you will then have to perform manually."
    exit 1
fi
SHA1="$1"
if ! git merge-base "$SHA1" HEAD >/dev/null 2>/dev/null ; then
    echo "$SHA1 does not appear to be in the current branch"
    exit 1
fi

# Get the current branch.
CURRENTBRANCH=`git branch | grep '^\*' | awk '{print $2}' -`
if test "$CURRENTBRANCH" = "(no" ; then
    echo "Not on a valid branch - please check out the correct branch"
    exit 1
fi

if test -n "`git diff HEAD`" ; then
    echo "You have uncommited changes. Please commit or stash them first." >&2
    exit 1
fi

# Replace aliases like HEAD and HEAD^ with the actual SHA-1.
SHA1=`git rev-parse "$SHA1"`
SHORT_SHA1=`git rev-parse --short "$SHA1"`

# Check that the change hasn't already been pushed.
COMMON=`git merge-base "$SHA1" "origin/$CURRENTBRANCH" 2>/dev/null`
if test "$COMMON" = "$SHA1" ; then
    echo "$SHA1 has already been pushed - cannot edit it"
    exit 1
fi

EDITOR="$0"
export EDITOR
export SHORT_SHA1
if ! git rebase --preserve-merges -i "${SHA1}^" ; then
    exit 1
fi
unset EDITOR

# If doing a source rebase, then just start it up at the right point.
if test "$MODE" = "source" ; then
    echo "To make the source for your chosen commit editable, run:"
    echo ""
    echo "        git reset HEAD^"
    echo ""
    exit 0
fi

git commit --amend

git rebase --continue

exit 0