Class: Overcommit::HookContext::PreCommit

Inherits:
Base
  • Object
show all
Defined in:
lib/overcommit/hook_context/pre_commit.rb

Overview

Contains helpers related to contextual information used by pre-commit hooks.

This includes staged files, which lines of those files have been modified, etc.

Instance Method Summary collapse

Methods inherited from Base

#hook_class_name, #hook_script_name, #hook_type_name, #initialize

Constructor Details

This class inherits a constructor from Overcommit::HookContext::Base

Instance Method Details

#cleanup_environmentObject

Restore unstaged changes and reset file modification times so it appears as if nothing ever changed.



27
28
29
30
31
32
33
34
35
# File 'lib/overcommit/hook_context/pre_commit.rb', line 27

def cleanup_environment
  `git reset --hard` # Ensure working tree is clean before popping stash

  if @changes_stashed
    `git stash pop --index --quiet`
  end

  restore_modified_times
end

#modified_filesObject

Get a list of added, copied, or modified files that have been staged. Renames and deletions are ignored, since there should be nothing to check.



39
40
41
42
43
44
# File 'lib/overcommit/hook_context/pre_commit.rb', line 39

def modified_files
  @modified_files ||=
    `git diff --cached --name-only --diff-filter=ACM --ignore-submodules=all`.
      split("\n").
      map { |relative_file| File.expand_path(relative_file) }
end

#modified_lines(file) ⇒ Object

Returns the set of line numbers corresponding to the lines that were changed in a specified file.



48
49
50
51
# File 'lib/overcommit/hook_context/pre_commit.rb', line 48

def modified_lines(file)
  @modified_lines ||= {}
  @modified_lines[file] ||= extract_modified_lines(file)
end

#setup_environmentObject

Stash unstaged contents of files so hooks don’t see changes that aren’t about to be committed.



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/overcommit/hook_context/pre_commit.rb', line 11

def setup_environment
  store_modified_times

  if any_changes?
    @changes_stashed = true
    `git stash save --keep-index --quiet #{<<-MSG}`
      "Overcommit: Stash of repo state before hook run at #{Time.now}"
    MSG
  end

  # While running the hooks make it appear as if nothing changed
  restore_modified_times
end