mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-09 21:04:17 +00:00
Refactor check_executables_have_shebangs for git ls-files reuse
This commit is contained in:
parent
6c99eceab7
commit
9e7cd9f13a
1 changed files with 23 additions and 12 deletions
|
|
@ -2,7 +2,9 @@
|
||||||
import argparse
|
import argparse
|
||||||
import shlex
|
import shlex
|
||||||
import sys
|
import sys
|
||||||
|
from typing import Generator
|
||||||
from typing import List
|
from typing import List
|
||||||
|
from typing import NamedTuple
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from typing import Sequence
|
from typing import Sequence
|
||||||
from typing import Set
|
from typing import Set
|
||||||
|
|
@ -19,29 +21,38 @@ def check_executables(paths: List[str]) -> int:
|
||||||
else: # pragma: win32 no cover
|
else: # pragma: win32 no cover
|
||||||
retv = 0
|
retv = 0
|
||||||
for path in paths:
|
for path in paths:
|
||||||
if not _check_has_shebang(path):
|
if not has_shebang(path):
|
||||||
_message(path)
|
_message(path)
|
||||||
retv = 1
|
retv = 1
|
||||||
|
|
||||||
return retv
|
return retv
|
||||||
|
|
||||||
|
|
||||||
def _check_git_filemode(paths: Sequence[str]) -> int:
|
class GitLsFile(NamedTuple):
|
||||||
outs = cmd_output('git', 'ls-files', '-z', '--stage', '--', *paths)
|
mode: str
|
||||||
seen: Set[str] = set()
|
filename: str
|
||||||
for out in zsplit(outs):
|
|
||||||
metadata, path = out.split('\t')
|
|
||||||
tagmode = metadata.split(' ', 1)[0]
|
|
||||||
|
|
||||||
is_executable = any(b in EXECUTABLE_VALUES for b in tagmode[-3:])
|
|
||||||
if is_executable and not _check_has_shebang(path):
|
def git_ls_files(paths: Sequence[str]) -> Generator[GitLsFile, None, None]:
|
||||||
_message(path)
|
outs = cmd_output('git', 'ls-files', '-z', '--stage', '--', *paths)
|
||||||
seen.add(path)
|
for out in zsplit(outs):
|
||||||
|
metadata, filename = out.split('\t')
|
||||||
|
mode, _, _ = metadata.split()
|
||||||
|
yield GitLsFile(mode, filename)
|
||||||
|
|
||||||
|
|
||||||
|
def _check_git_filemode(paths: Sequence[str]) -> int:
|
||||||
|
seen: Set[str] = set()
|
||||||
|
for ls_file in git_ls_files(paths):
|
||||||
|
is_executable = any(b in EXECUTABLE_VALUES for b in ls_file.mode[-3:])
|
||||||
|
if is_executable and not has_shebang(ls_file.filename):
|
||||||
|
_message(ls_file.filename)
|
||||||
|
seen.add(ls_file.filename)
|
||||||
|
|
||||||
return int(bool(seen))
|
return int(bool(seen))
|
||||||
|
|
||||||
|
|
||||||
def _check_has_shebang(path: str) -> int:
|
def has_shebang(path: str) -> int:
|
||||||
with open(path, 'rb') as f:
|
with open(path, 'rb') as f:
|
||||||
first_bytes = f.read(2)
|
first_bytes = f.read(2)
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue