pre-commit-hooks/pre_commit_hooks/check_merge_conflict.py

57 lines
1.5 KiB
Python
Raw Permalink Normal View History

from __future__ import annotations
2015-03-14 07:30:14 +08:00
import argparse
import os.path
from collections.abc import Sequence
from pre_commit_hooks.util import cmd_output
2015-03-14 07:30:14 +08:00
CONFLICT_PATTERNS = [
b'<<<<<<< ',
b'======= ',
b'=======\r\n',
b'=======\n',
2017-07-13 09:35:24 +08:00
b'>>>>>>> ',
2015-03-14 07:30:14 +08:00
]
def is_in_merge() -> bool:
git_dir = cmd_output('git', 'rev-parse', '--git-dir').rstrip()
return (
os.path.exists(os.path.join(git_dir, 'MERGE_MSG')) and
(
os.path.exists(os.path.join(git_dir, 'MERGE_HEAD')) or
os.path.exists(os.path.join(git_dir, 'rebase-apply')) or
os.path.exists(os.path.join(git_dir, 'rebase-merge'))
)
)
def main(argv: Sequence[str] | None = None) -> int:
2015-03-14 07:30:14 +08:00
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*')
parser.add_argument('--assume-in-merge', action='store_true')
2015-03-14 07:30:14 +08:00
args = parser.parse_args(argv)
if not is_in_merge() and not args.assume_in_merge:
return 0
2015-03-14 07:30:14 +08:00
retcode = 0
for filename in args.filenames:
with open(filename, 'rb') as inputfile:
for i, line in enumerate(inputfile, start=1):
2015-03-14 07:30:14 +08:00
for pattern in CONFLICT_PATTERNS:
if line.startswith(pattern):
2020-02-04 00:41:48 +08:00
print(
f'{filename}:{i}: Merge conflict string '
f'{pattern.strip().decode()!r} found',
2020-02-04 00:41:48 +08:00
)
2015-03-14 07:30:14 +08:00
retcode = 1
return retcode
2015-03-14 07:30:14 +08:00
if __name__ == '__main__':
raise SystemExit(main())