mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-06 03:56:54 +00:00
Add check for permitted characters in pathnames
Add a new checker that checks for allowed characters in pathnames. Includes arguments for overriding the default allowed list and extending it. Default allow list is alphanumeric plus `.-_`.
This commit is contained in:
parent
69b4df5589
commit
9bb6ebc34d
5 changed files with 109 additions and 0 deletions
49
pre_commit_hooks/check_permitted_path_characters.py
Normal file
49
pre_commit_hooks/check_permitted_path_characters.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import string
|
||||
from typing import Sequence
|
||||
|
||||
DEFAULT_ALLOWLIST = string.ascii_letters + string.digits + '-_./'
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('filenames', nargs='*')
|
||||
parser.add_argument(
|
||||
'--allowlist',
|
||||
default=DEFAULT_ALLOWLIST,
|
||||
help=(
|
||||
'Override the default allowlist of permitted characters. The'
|
||||
' default is %(default)s'
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
'--extra-allowlist',
|
||||
default='',
|
||||
help='Extend the default allowlist with these characters.',
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
allowlist = set(args.allowlist + args.extra_allowlist)
|
||||
|
||||
retcode = 0
|
||||
for filename in args.filenames:
|
||||
# check the entire path, not just the filename, to catch directories
|
||||
# with invalid characters
|
||||
file_chars = set(filename)
|
||||
if not file_chars.issubset(allowlist):
|
||||
# sorted and stringified for readability
|
||||
pretty_allowlist = ''.join(sorted(allowlist))
|
||||
pretty_banlist = repr(''.join(sorted(file_chars - allowlist)))
|
||||
print(
|
||||
f'"{filename}" contains characters not in the allowlist:'
|
||||
f' "{pretty_banlist}". Allowlist is: "{pretty_allowlist}".',
|
||||
)
|
||||
retcode = 1
|
||||
|
||||
return retcode
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Loading…
Add table
Add a link
Reference in a new issue