Skip to content

Commit a5338f2

Browse files
authored
Merge pull request #244 from pre-commit/yaml_multi_document
Add an --allow-multiple-documents option to check-yaml
2 parents e09278e + e87b81a commit a5338f2

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ Add this to your `.pre-commit-config.yaml`
4343
- `check-vcs-permalinks` - Ensures that links to vcs websites are permalinks.
4444
- `check-xml` - Attempts to load all xml files to verify syntax.
4545
- `check-yaml` - Attempts to load all yaml files to verify syntax.
46+
- `--allow-multiple-documents` - allow yaml files which use the
47+
[multi-document syntax](http://www.yaml.org/spec/1.2/spec.html#YAML)
4648
- `debug-statements` - Check for pdb / ipdb / pudb statements in code.
4749
- `detect-aws-credentials` - Checks for the existence of AWS secrets that you
4850
have set up with the AWS CLI.

pre_commit_hooks/check_yaml.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,24 @@
1111
Loader = yaml.SafeLoader
1212

1313

14+
def _load_all(*args, **kwargs):
15+
# need to exhaust the generator
16+
return tuple(yaml.load_all(*args, **kwargs))
17+
18+
1419
def check_yaml(argv=None):
1520
parser = argparse.ArgumentParser()
21+
parser.add_argument(
22+
'-m', '--allow-multiple-documents', dest='yaml_load_fn',
23+
action='store_const', const=_load_all, default=yaml.load,
24+
)
1625
parser.add_argument('filenames', nargs='*', help='Yaml filenames to check.')
1726
args = parser.parse_args(argv)
1827

1928
retval = 0
2029
for filename in args.filenames:
2130
try:
22-
yaml.load(open(filename), Loader=Loader)
31+
args.yaml_load_fn(open(filename), Loader=Loader)
2332
except yaml.YAMLError as exc:
2433
print(exc)
2534
retval = 1

tests/check_yaml_test.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
from __future__ import absolute_import
2+
from __future__ import unicode_literals
3+
14
import pytest
25

36
from pre_commit_hooks.check_yaml import check_yaml
@@ -13,3 +16,20 @@
1316
def test_check_yaml(filename, expected_retval):
1417
ret = check_yaml([get_resource_path(filename)])
1518
assert ret == expected_retval
19+
20+
21+
def test_check_yaml_allow_multiple_documents(tmpdir):
22+
f = tmpdir.join('test.yaml')
23+
f.write('---\nfoo\n---\nbar\n')
24+
25+
# should failw without the setting
26+
assert check_yaml((f.strpath,))
27+
28+
# should pass when we allow multiple documents
29+
assert not check_yaml(('--allow-multiple-documents', f.strpath))
30+
31+
32+
def test_fails_even_with_allow_multiple_documents(tmpdir):
33+
f = tmpdir.join('test.yaml')
34+
f.write('[')
35+
assert check_yaml(('--allow-multiple-documents', f.strpath))

0 commit comments

Comments
 (0)