blob: b806cad297e783b0e022132f0b922c94ba9172b9 [file] [log] [blame]
Anthony Sottile8f615292022-01-15 19:24:05 -05001from __future__ import annotations
2
Mikhail Khvoinitsky10c5e4e2021-06-23 03:10:13 +03003import argparse
4import os
Anthony Sottile030bfac2019-01-31 19:19:10 -08005from typing import Sequence
6
Anthony Sottile70e405e2016-11-30 09:56:42 -08007from pre_commit_hooks.util import cmd_output
8
9
Anthony Sottile8f615292022-01-15 19:24:05 -050010def main(argv: Sequence[str] | None = None) -> int:
Mikhail Khvoinitsky10c5e4e2021-06-23 03:10:13 +030011 parser = argparse.ArgumentParser()
12 parser.add_argument('filenames', nargs='*')
13 args = parser.parse_args(argv)
14
15 if (
16 'PRE_COMMIT_FROM_REF' in os.environ and
17 'PRE_COMMIT_TO_REF' in os.environ
18 ):
19 diff_arg = '...'.join((
20 os.environ['PRE_COMMIT_FROM_REF'],
21 os.environ['PRE_COMMIT_TO_REF'],
22 ))
23 else:
24 diff_arg = '--staged'
Anthony Sottile70e405e2016-11-30 09:56:42 -080025 added_diff = cmd_output(
Mikhail Khvoinitsky10c5e4e2021-06-23 03:10:13 +030026 'git', 'diff', '--diff-filter=A', '--raw', diff_arg, '--',
27 *args.filenames,
Anthony Sottile70e405e2016-11-30 09:56:42 -080028 )
29 retv = 0
30 for line in added_diff.splitlines():
31 metadata, filename = line.split('\t', 1)
32 new_mode = metadata.split(' ')[1]
33 if new_mode == '160000':
Anthony Sottilef5c42a02020-02-05 11:10:42 -080034 print(f'{filename}: new submodule introduced')
Anthony Sottile70e405e2016-11-30 09:56:42 -080035 retv = 1
36
37 if retv:
Chris Kuehl4b928ab2016-11-30 10:10:29 -080038 print()
Anthony Sottile70e405e2016-11-30 09:56:42 -080039 print('This commit introduces new submodules.')
40 print('Did you unintentionally `git add .`?')
41 print('To fix: git rm {thesubmodule} # no trailing slash')
42 print('Also check .gitmodules')
43
44 return retv
45
46
47if __name__ == '__main__':
Anthony Sottile39ab2ed2021-10-23 13:23:50 -040048 raise SystemExit(main())