1+
2+ from __future__ import print_function
3+
4+ import argparse
5+ import jsonschema
6+ import jsonschema .exceptions
7+ import os .path
8+ import yaml
9+
10+ import pre_commit .constants as C
11+
12+
13+ class InvalidManifestError (ValueError ): pass
14+
15+
16+ MANIFEST_JSON_SCHEMA = {
17+ 'type' : 'object' ,
18+ 'properties' : {
19+ 'hooks' : {
20+ 'type' : 'array' ,
21+ 'minItems' : 1 ,
22+ 'items' : {
23+ 'type' : 'object' ,
24+ 'properties' : {
25+ 'id' : {'type' : 'string' },
26+ 'name' : {'type' : 'string' },
27+ 'description' : {'type' : 'string' },
28+ 'entry' : {'type' : 'string' },
29+ 'language' : {'type' : 'string' },
30+ 'expected_return_value' : {'type' : 'number' },
31+ },
32+ 'required' : ['id' , 'name' , 'entry' ],
33+ },
34+ },
35+ },
36+ 'required' : ['hooks' ],
37+ }
38+
39+
40+ def check_is_valid_manifest (file_contents ):
41+ file_objects = yaml .load (file_contents )
42+
43+ jsonschema .validate (file_objects , MANIFEST_JSON_SCHEMA )
44+
45+ for hook_config in file_objects ['hooks' ]:
46+ language = hook_config .get ('language' )
47+
48+ if language is not None and not any (
49+ language .startswith (lang ) for lang in C .SUPPORTED_LANGUAGES
50+ ):
51+ raise InvalidManifestError (
52+ 'Expected language {0} for {1} to start with one of {2!r}' .format (
53+ hook_config ['id' ],
54+ hook_config ['language' ],
55+ C .SUPPORTED_LANGUAGES ,
56+ )
57+ )
58+
59+
60+
61+ def run (argv ):
62+ parser = argparse .ArgumentParser ()
63+ parser .add_argument (
64+ '--filename' ,
65+ required = False , default = None ,
66+ help = 'Manifest filename. Defaults to {0} at root of git repo' .format (
67+ C .MANIFEST_FILE ,
68+ )
69+ )
70+ args = parser .parse_args (argv )
71+
72+ if args .filename is None :
73+ # TODO: filename = git.get_root() + C.MANIFEST_FILE
74+ raise NotImplementedError
75+ else :
76+ filename = args .filename
77+
78+ if not os .path .exists (filename ):
79+ print ('File {0} does not exist' .format (filename ))
80+ return 1
81+
82+ file_contents = open (filename , 'r' ).read ()
83+
84+ try :
85+ yaml .load (file_contents )
86+ except Exception as e :
87+ print ('File {0} is not a valid yaml file' .format (filename ))
88+ print (str (e ))
89+ return 1
90+
91+ try :
92+ check_is_valid_manifest (file_contents )
93+ except (jsonschema .exceptions .ValidationError , InvalidManifestError ) as e :
94+ print ('File {0} is not a valid manifest file' .format (filename ))
95+ print (str (e ))
96+ return 1
97+
98+ return 0
0 commit comments