From c0dd50720639221595c33f992ac8f0260618f159 Mon Sep 17 00:00:00 2001 From: Deepak Mahakale Date: Fri, 28 May 2021 18:29:35 +0530 Subject: [PATCH] Fixes #751 Add `staged_changes?` check to avoid stashing files if no changes have been staged. stashing the files with no staged changes ends up deleting all files --- CHANGELOG.md | 2 ++ .../hook_context/helpers/stash_unstaged_changes.rb | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca3d3627..f8657465 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # Overcommit Changelog +* Add `staged_changes?` check to avoid stashing files if no changes has been staged. + ## 0.57.0 * Fix `CommitMsg` hooks to be able to call `modified_lines_in_file`. diff --git a/lib/overcommit/hook_context/helpers/stash_unstaged_changes.rb b/lib/overcommit/hook_context/helpers/stash_unstaged_changes.rb index f2866bd5..99b50869 100644 --- a/lib/overcommit/hook_context/helpers/stash_unstaged_changes.rb +++ b/lib/overcommit/hook_context/helpers/stash_unstaged_changes.rb @@ -15,7 +15,7 @@ def setup_environment # Don't attempt to stash changes if all changes are staged, as this # prevents us from modifying files at all, which plays better with # editors/tools which watch for file changes. - if !initial_commit? && unstaged_changes? + if !initial_commit? && unstaged_changes? && staged_changes? stash_changes # While running hooks make it appear as if nothing changed @@ -74,6 +74,13 @@ def unstaged_changes? !result.success? end + # Checks whether there are any staged changes. + # https://github.com/sds/overcommit/issues/751 + def staged_changes? + result = Overcommit::Utils.execute(%w[git --no-pager diff --cached --quiet]) + !result.success? + end + def stash_changes @stash_attempted = true