2021-01-08 23:36:55 +08:00
|
|
|
"""Check that text files with a shebang are executable."""
|
2022-01-16 08:24:05 +08:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2021-01-08 23:36:55 +08:00
|
|
|
import argparse
|
|
|
|
import shlex
|
|
|
|
import sys
|
2024-10-12 07:30:07 +08:00
|
|
|
from collections.abc import Sequence
|
2021-01-08 23:36:55 +08:00
|
|
|
|
|
|
|
from pre_commit_hooks.check_executables_have_shebangs import EXECUTABLE_VALUES
|
|
|
|
from pre_commit_hooks.check_executables_have_shebangs import git_ls_files
|
|
|
|
from pre_commit_hooks.check_executables_have_shebangs import has_shebang
|
|
|
|
|
|
|
|
|
2022-01-16 08:24:05 +08:00
|
|
|
def check_shebangs(paths: list[str]) -> int:
|
2021-01-08 23:36:55 +08:00
|
|
|
# Cannot optimize on non-executability here if we intend this check to
|
|
|
|
# work on win32 -- and that's where problems caused by non-executability
|
|
|
|
# (elsewhere) are most likely to arise from.
|
|
|
|
return _check_git_filemode(paths)
|
|
|
|
|
|
|
|
|
|
|
|
def _check_git_filemode(paths: Sequence[str]) -> int:
|
2022-01-16 08:24:05 +08:00
|
|
|
seen: set[str] = set()
|
2021-01-08 23:36:55 +08:00
|
|
|
for ls_file in git_ls_files(paths):
|
|
|
|
is_executable = any(b in EXECUTABLE_VALUES for b in ls_file.mode[-3:])
|
|
|
|
if not is_executable and has_shebang(ls_file.filename):
|
|
|
|
_message(ls_file.filename)
|
|
|
|
seen.add(ls_file.filename)
|
|
|
|
|
|
|
|
return int(bool(seen))
|
|
|
|
|
|
|
|
|
|
|
|
def _message(path: str) -> None:
|
|
|
|
print(
|
|
|
|
f'{path}: has a shebang but is not marked executable!\n'
|
|
|
|
f' If it is supposed to be executable, try: '
|
|
|
|
f'`chmod +x {shlex.quote(path)}`\n'
|
2022-05-26 23:31:24 +08:00
|
|
|
f' If on Windows, you may also need to: '
|
|
|
|
f'`git add --chmod=+x {shlex.quote(path)}`\n'
|
2021-01-08 23:36:55 +08:00
|
|
|
f' If it not supposed to be executable, double-check its shebang '
|
|
|
|
f'is wanted.\n',
|
|
|
|
file=sys.stderr,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2022-01-16 08:24:05 +08:00
|
|
|
def main(argv: Sequence[str] | None = None) -> int:
|
2021-01-08 23:36:55 +08:00
|
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
|
|
parser.add_argument('filenames', nargs='*')
|
|
|
|
args = parser.parse_args(argv)
|
|
|
|
|
|
|
|
return check_shebangs(args.filenames)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2021-10-24 01:23:50 +08:00
|
|
|
raise SystemExit(main())
|