Skip to content

Commit 7f0dac4

Browse files
authored
pre-commit: print warning when staged version doesn't match disk version (#986)
1 parent 5443e2d commit 7f0dac4

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

coding-standard.py

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,8 +138,7 @@ def __init__(self, path, contents=None):
138138
self.path = Path(path)
139139
self.contents = contents
140140
if contents is None:
141-
with open(self.path, "r", encoding="utf-8") as f:
142-
self.contents = f.read().splitlines()
141+
raise ValueError("Contents not provided")
143142

144143
self.allowLeadingTab = False
145144
if self.isMakefile:
@@ -348,9 +347,11 @@ def __init__(self, baseRef):
348347
if baseRef is None:
349348
baseRef = "HEAD"
350349
self.baseRef = baseRef
350+
self.stagedContents = False
351351
return
352352

353353
def getStagedFiles(self, extension=None):
354+
self.stagedContents = True
354355
try:
355356
result = subprocess.run(
356357
["git", "diff", "--cached", "--name-only", "--diff-filter=ACMRT"],
@@ -384,6 +385,27 @@ def getPreviousContents(self, path):
384385

385386
return result.stdout.splitlines()
386387

388+
def getContents(self, path):
389+
if not self.stagedContents:
390+
with open(path, "r", encoding="utf-8") as f:
391+
return f.read().splitlines()
392+
393+
try:
394+
cmd = ['git', 'show', f':{path}'] # colon = index
395+
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
396+
contents = result.stdout.splitlines()
397+
398+
result = subprocess.run(['git', 'diff', '--quiet', path], capture_output=True)
399+
if result.returncode != 0:
400+
print("** Warning: file '{path}' was modified after staging."
401+
" Re-run git add before committing.")
402+
403+
return contents
404+
except subprocess.CalledProcessError:
405+
pass
406+
407+
return None
408+
387409
def root(self):
388410
result = subprocess.run(
389411
["git", "rev-parse", "--show-toplevel"],
@@ -447,7 +469,7 @@ def main():
447469
exit(1)
448470

449471
if TextFile.pathIsText(path):
450-
tfile = TextFile(path)
472+
tfile = TextFile(path, repo.getContents(path))
451473
if doShow:
452474
tfile.show()
453475
elif doFix:

0 commit comments

Comments
 (0)