From 087a9638173224f6d53a9ba0d0faf780b2c53d2d Mon Sep 17 00:00:00 2001 From: Timothy Sweetser Date: Fri, 4 Jan 2019 17:30:33 -0500 Subject: [PATCH] adds sql formatter --- .pre-commit-hooks.yaml | 5 +++++ pre_commit_hooks/format_sql.py | 35 ++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100755 pre_commit_hooks/format_sql.py diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index 5157783..c6b13e7 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -183,3 +183,8 @@ entry: trailing-whitespace-fixer language: python types: [text] +- id: format-sql + name: Format SQL Files + description: This hook formats SQL files + entry: sql-formatter + language: python diff --git a/pre_commit_hooks/format_sql.py b/pre_commit_hooks/format_sql.py new file mode 100755 index 0000000..3c0ea66 --- /dev/null +++ b/pre_commit_hooks/format_sql.py @@ -0,0 +1,35 @@ +import sys +import click +import os +import sqlparse + +options = {"keyword_case": "upper", "comma_first": True} + + + +def reformat(sql_file): + with open(sql_file, "r") as f: + original = f.read() + new = sqlparse.format(original, **options) + with open(sql_file, "w") as f: + f.write(new) + if new == original: + return 0 + else: + return 1 + + +@click.command() +@click.option('--directory', required=True) +def main(directory): + res = 0 + for root, dirs, files in os.walk(directory): + for f in files: + if f.split('.')[-1] == 'sql': + res = max(res, reformat(os.path.join(root, f))) + print(f"reformatted {f}") + return res + + +if __name__ == "__main__": + sys.exit(main())