diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index 5157783..e6403cb 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -130,6 +130,15 @@ entry: fix-encoding-pragma description: 'Add # -*- coding: utf-8 -*- to the top of python files' types: [python] +- id: fix-yaml + name: Fix YAML files + language: python + entry: fix-yaml + description: 'Add --- header to yaml files' + types: [yaml] + # for backward compatibility + files: '' + minimum_pre_commit_version: 0.15.0 - id: flake8 name: Flake8 description: This hook runs flake8. diff --git a/pre_commit_hooks/fix_yaml.py b/pre_commit_hooks/fix_yaml.py new file mode 100644 index 0000000..8705381 --- /dev/null +++ b/pre_commit_hooks/fix_yaml.py @@ -0,0 +1,34 @@ +from __future__ import absolute_import +from __future__ import print_function +from __future__ import unicode_literals + +import argparse +import io + +from six import text_type + + +def main(argv=None): + parser = argparse.ArgumentParser() + parser.add_argument('filenames', nargs='*', help='Filenames to fix') + args = parser.parse_args(argv) + + retv = 0 + + for filename in args.filenames: + with io.open(filename, 'r+', encoding="utf-8") as f: + line = f.readline().strip() + if line != text_type('---'): + print("[%s]" % line) + f.seek(0, 0) + content = f.read() + f.seek(0, 0) + f.write('---\n' + content) + print('{}: Added --- header to YAML file'.format(filename)) + retv = 1 + + return retv + + +if __name__ == '__main__': + exit(main()) diff --git a/tests/fix_simple_yaml_test.py b/tests/fix_simple_yaml_test.py new file mode 100644 index 0000000..eaa9263 --- /dev/null +++ b/tests/fix_simple_yaml_test.py @@ -0,0 +1,16 @@ +from __future__ import absolute_import +from __future__ import unicode_literals + +from pre_commit_hooks import fix_yaml + + +def test_no_change(tmpdir): + f = tmpdir.join('f.yaml') + f.write('---\nfoo: bar') + assert fix_yaml.main((f.strpath,)) == 0 + + +def test_change(tmpdir): + f = tmpdir.join('f.yaml') + f.write('foo: bar') + assert fix_yaml.main((f.strpath,)) == 1