From 73ac710bdae3ab62956e06e1002428678e523260 Mon Sep 17 00:00:00 2001 From: Ryan Luckie Date: Wed, 7 Apr 2021 00:27:57 -0500 Subject: [PATCH] Add gitleaks hook --- .pre-commit-hooks.yaml | 6 +++ pre_commit_hooks/check_gitleaks.py | 65 ++++++++++++++++++++++++++++++ setup.cfg | 1 + 3 files changed, 72 insertions(+) create mode 100644 pre_commit_hooks/check_gitleaks.py diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index fa617b9..e7e3f30 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -205,3 +205,9 @@ language: python types: [text] stages: [commit, push, manual] +- id: check-gitleaks + name: "gitleaks" + entry: check-gitleaks + language: python + pass_filenames: false + always_run: true diff --git a/pre_commit_hooks/check_gitleaks.py b/pre_commit_hooks/check_gitleaks.py new file mode 100644 index 0000000..c8be082 --- /dev/null +++ b/pre_commit_hooks/check_gitleaks.py @@ -0,0 +1,65 @@ +import argparse +import json +import os +from typing import Optional +from typing import Sequence + +from pre_commit_hooks.util import CalledProcessError +from pre_commit_hooks.util import cmd_output + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser() + parser.add_argument( + '-r', '--report', type=str, + default='', help='where to store report', + ) + parser.add_argument( + '-c', '--config', type=str, + default='', help='location of config', + ) + args = parser.parse_args(argv) + cwd = os.getcwd() + + report = args.report or None + config = args.config or None + + if not config: + _config = os.path.join(cwd, '.gitleaks.toml') + if os.path.isfile(_config): + config = _config + + cmd = f'gitleaks --redact --quiet --format=json --path={cwd}' + report_path = None + if report: + report_path = os.path.join(cwd, report) + os.makedirs(os.path.dirname(report_path), exist_ok=True) + if config: + cmd += f' --config-path={config}' + out = [] + # history + try: + cmd_output(*cmd.split()) + except CalledProcessError as excp: + for line in excp.args[3].split('\n'): + if line: + out.append(json.loads(line)) + # unstaged + cmd += ' --unstaged' + try: + cmd_output(*cmd.split()) + except CalledProcessError as excp: + for line in excp.args[3].split('\n'): + if line: + out.append(json.loads(line)) + if report: + with open(report_path, 'w') as f: + json.dump(out, f) + if out: + print(json.dumps(out, indent=4)) + return 1 + return 0 + + +if __name__ == '__main__': + exit(main()) diff --git a/setup.cfg b/setup.cfg index 631faab..7611f2d 100644 --- a/setup.cfg +++ b/setup.cfg @@ -66,6 +66,7 @@ console_scripts = requirements-txt-fixer = pre_commit_hooks.requirements_txt_fixer:main sort-simple-yaml = pre_commit_hooks.sort_simple_yaml:main trailing-whitespace-fixer = pre_commit_hooks.trailing_whitespace_fixer:main + check-gitleaks = pre_commit_hooks.check_gitleaks:main [bdist_wheel] universal = True