Skip to content

Commit c1fd423

Browse files
jawshooahsds
authored andcommitted
Add helper method HookContext::PreCommit#amend?
Returns true if the current hook run was initiated by amending a commit, false otherwise.
1 parent 16509a8 commit c1fd423

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

lib/overcommit/hook_context/pre_commit.rb

+15-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,21 @@ module Overcommit::HookContext
77
# This includes staged files, which lines of those files have been modified,
88
# etc. It is also responsible for saving/restoring the state of the repo so
99
# hooks only inspect staged changes.
10-
class PreCommit < Base
10+
class PreCommit < Base # rubocop:disable ClassLength
11+
# Returns whether this hook run was triggered by `git commit --amend`
12+
def amend?
13+
if @amended.nil?
14+
cmd = Overcommit::Utils.parent_command
15+
@amended = !(/--amend/ =~ cmd).nil?
16+
17+
amend_alias = `git config --get-regexp '^alias\\.' '--amend'`.
18+
slice(/(?<=alias\.)\w+/)
19+
20+
@amended ||= !(/git #{amend_alias}/ =~ cmd).nil? unless amend_alias.nil?
21+
end
22+
@amended
23+
end
24+
1125
# Stash unstaged contents of files so hooks don't see changes that aren't
1226
# about to be committed.
1327
def setup_environment

spec/overcommit/hook_context/pre_commit_spec.rb

+35
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,41 @@
77
let(:input) { double('input') }
88
let(:context) { described_class.new(config, args, input) }
99

10+
describe '#amend?' do
11+
subject { context.amend? }
12+
13+
context 'when amending a commit using `git commit --amend`' do
14+
before do
15+
Overcommit::Utils.stub(:parent_command).and_return('git commit --amend')
16+
end
17+
18+
it { should == true }
19+
end
20+
21+
context 'when amending a commit using a git alias' do
22+
around do |example|
23+
repo do
24+
`git config alias.amend 'commit --amend'`
25+
example.run
26+
end
27+
end
28+
29+
before do
30+
Overcommit::Utils.stub(:parent_command).and_return('git amend')
31+
end
32+
33+
it { should == true }
34+
end
35+
36+
context 'when not amending a commit' do
37+
before do
38+
Overcommit::Utils.stub(:parent_command).and_return('git commit')
39+
end
40+
41+
it { should == false }
42+
end
43+
end
44+
1045
describe '#setup_environment' do
1146
subject { context.setup_environment }
1247

0 commit comments

Comments
 (0)