blob: 13a4a65539c4f0ef32a3e9298caa4f4e0aa07f06 [file] [log] [blame]
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +00001#!/usr/bin/python3
2import argparse
3import os
4import sys
5import subprocess
6import traceback
7import yaml
8
9run_pep8 = False
10try:
11 import pep8
12 run_pep8 = True
13except:
Antonio Terceiro1396fb12016-11-07 18:45:52 -020014 print("PEP8 is not available!")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000015
16
17def print_stderr(message):
18 sys.stderr.write(message)
19 sys.stderr.write("\n")
20
21
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +000022def publish_result(result_message_list, args):
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000023 result_message = '\n'.join(result_message_list)
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +000024 try:
25 f = open(args.result_file, 'a')
26 f.write("\n\n")
27 f.write(result_message)
28 f.write("\n\n")
29 f.close()
30 except IOError as e:
31 print_stderr("Cannot write to result file: %s" % args.result_file)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000032 print_stderr(result_message)
33
34
Dan Rue8ec540c2018-01-25 14:38:12 -060035def detect_abi():
36 # Retrieve the current canonical abi from
37 # automated/lib/sh-test-lib:detect_abi
38 return subprocess.check_output(
39 ". automated/lib/sh-test-lib && detect_abi && echo $abi",
40 shell=True).decode('utf-8').strip()
41
42
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +000043def pep8_check(filepath, args):
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000044 _fmt = "%(row)d:%(col)d: %(code)s %(text)s"
45 options = {
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +000046 'ignore': args.pep8_ignore,
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000047 "show_source": True}
48 pep8_checker = pep8.StyleGuide(options)
49 fchecker = pep8_checker.checker_class(
50 filepath,
51 options=pep8_checker.options)
52 fchecker.check_all()
53 if fchecker.report.file_errors > 0:
54 result_message_list = []
55 result_message_list.append("* PEP8: [FAILED]: " + filepath)
56 fchecker.report.print_statistics()
57 for line_number, offset, code, text, doc in fchecker.report._deferred_print:
58 result_message_list.append(
59 _fmt % {
60 'path': filepath,
61 'row': fchecker.report.line_offset + line_number,
62 'col': offset + 1,
63 'code': code, 'text': text,
64 })
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +000065 publish_result(result_message_list, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000066 return 1
67 else:
68 message = "* PEP8: [PASSED]: " + filepath
69 print_stderr(message)
70 return 0
71
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +000072
Dan Rue8ec540c2018-01-25 14:38:12 -060073def validate_yaml_contents(filepath, args):
74 def validate_lava_yaml(y, args):
Milosz Wasilewskic69b4092017-10-20 14:04:52 +010075 result_message_list = []
Milosz Wasilewskic69b4092017-10-20 14:04:52 +010076 if 'metadata' not in y.keys():
77 result_message_list.append("* METADATA [FAILED]: " + filepath)
78 result_message_list.append("\tmetadata section missing")
79 publish_result(result_message_list, args)
80 exit(1)
81 metadata_dict = y['metadata']
82 mandatory_keys = set([
83 'name',
84 'format',
85 'description',
86 'maintainer',
87 'os',
88 'devices'])
89 if not mandatory_keys.issubset(set(metadata_dict.keys())):
90 result_message_list.append("* METADATA [FAILED]: " + filepath)
91 result_message_list.append("\tmandatory keys missing: %s" %
92 mandatory_keys.difference(set(metadata_dict.keys())))
93 result_message_list.append("\tactual keys present: %s" %
94 metadata_dict.keys())
95 publish_result(result_message_list, args)
96 return 1
97 for key in mandatory_keys:
98 if len(metadata_dict[key]) == 0:
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000099 result_message_list.append("* METADATA [FAILED]: " + filepath)
Milosz Wasilewskic69b4092017-10-20 14:04:52 +0100100 result_message_list.append("\t%s has no content" % key)
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000101 publish_result(result_message_list, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000102 return 1
Milosz Wasilewskic69b4092017-10-20 14:04:52 +0100103 result_message_list.append("* METADATA [PASSED]: " + filepath)
104 publish_result(result_message_list, args)
Dan Rue8ec540c2018-01-25 14:38:12 -0600105 return 0
106
107 def validate_skipgen_yaml(filepath, args):
108 abi = detect_abi()
109 # Run skipgen on skipgen yaml file to check for output and errors
110 skips = subprocess.check_output(
111 "automated/bin/{}/skipgen {}".format(abi, filepath),
112 shell=True).decode('utf-8').strip()
113 if len(skips.split('\n')) < 1:
114 publish_result(["* SKIPGEN [FAILED]: " + filepath + " - No skips found"], args)
115 return 1
116 publish_result(["* SKIPGEN [PASSED]: " + filepath], args)
117 return 0
118
119 filecontent = None
120 try:
121 with open(filepath, "r") as f:
122 filecontent = f.read()
123 except FileNotFoundError:
124 publish_result(["* YAMLVALIDCONTENTS [PASSED]: " + filepath + " - deleted"], args)
125 return 0
126 y = yaml.load(filecontent)
127 if 'metadata' in y.keys():
128 # lava yaml file
129 return validate_lava_yaml(y, args)
130 elif 'skiplist' in y.keys():
131 # skipgen yaml file
132 return validate_skipgen_yaml(filepath, args)
133 else:
134 publish_result(["* YAMLVALIDCONTENTS [FAILED]: " + filepath + " - Unknown yaml type detected"], args)
135 return 1
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000136
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000137
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000138def validate_yaml(filename, args):
Milosz Wasilewskic69b4092017-10-20 14:04:52 +0100139 filecontent = None
140 try:
141 with open(filename, "r") as f:
142 filecontent = f.read()
143 except FileNotFoundError:
144 publish_result(["* YAMLVALID [PASSED]: " + filename + " - deleted"], args)
145 return 0
146 try:
147 y = yaml.load(filecontent)
148 message = "* YAMLVALID: [PASSED]: " + filename
149 print_stderr(message)
150 except:
151 message = "* YAMLVALID: [FAILED]: " + filename
152 result_message_list = []
153 result_message_list.append(message)
154 result_message_list.append("\n\n")
155 exc_type, exc_value, exc_traceback = sys.exc_info()
156 for line in traceback.format_exception_only(exc_type, exc_value):
157 result_message_list.append(' ' + line)
158 publish_result(result_message_list, args)
159 return 1
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000160 return 0
161
162
163def validate_shell(filename, ignore_options):
164 ignore_string = ""
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000165 if args.shellcheck_ignore is not None:
166 ignore_string = "-e %s" % " ".join(args.shellcheck_ignore)
Milosz Wasilewskiab7645a2016-11-07 10:45:34 +0000167 if len(ignore_string) < 4: # contains only "-e "
168 ignore_string = ""
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000169 cmd = 'shellcheck %s' % ignore_string
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000170 return validate_external(cmd, filename, "SHELLCHECK", args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000171
172
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000173def validate_php(filename, args):
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000174 cmd = 'php -l'
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000175 return validate_external(cmd, filename, "PHPLINT", args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000176
177
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000178def validate_external(cmd, filename, prefix, args):
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000179 final_cmd = "%s %s 2>&1" % (cmd, filename)
180 status, output = subprocess.getstatusoutput(final_cmd)
181 if status == 0:
182 message = '* %s: [PASSED]: %s' % (prefix, filename)
183 print_stderr(message)
184 else:
185 result_message_list = []
186 result_message_list.append('* %s: [FAILED]: %s' % (prefix, filename))
187 result_message_list.append('* %s: [OUTPUT]:' % prefix)
188 for line in output.splitlines():
189 result_message_list.append(' ' + line)
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000190 publish_result(result_message_list, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000191 return 1
192 return 0
193
194
195def validate_file(args, path):
196 exitcode = 0
197 if path.endswith(".yaml"):
Milosz Wasilewskid0b78132016-11-22 19:21:14 +0000198 exitcode = validate_yaml(path, args)
199 if exitcode == 0:
200 # if yaml isn't valid there is no point in checking metadata
Dan Rue8ec540c2018-01-25 14:38:12 -0600201 exitcode = validate_yaml_contents(path, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000202 elif run_pep8 and path.endswith(".py"):
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000203 exitcode = pep8_check(path, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000204 elif path.endswith(".php"):
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000205 exitcode = validate_php(path, args)
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000206 elif path.endswith(".sh") or \
207 path.endswith("sh-test-lib") or \
208 path.endswith("android-test-lib"):
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000209 exitcode = validate_shell(path, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000210 return exitcode
211
212
213def run_unit_tests(args, filelist=None):
214 exitcode = 0
215 if filelist is not None:
216 for filename in filelist:
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000217 tmp_exitcode = validate_file(args, filename)
218 if tmp_exitcode != 0:
219 exitcode = 1
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000220 else:
221 for root, dirs, files in os.walk('.'):
222 if not root.startswith("./.git"):
223 for name in files:
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000224 tmp_exitcode = validate_file(
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000225 args,
226 root + "/" + name)
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000227 if tmp_exitcode != 0:
228 exitcode = 1
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000229 return exitcode
230
231
232def main(args):
233 exitcode = 0
234 if args.git_latest:
235 # check if git exists
236 git_status, git_result = subprocess.getstatusoutput(
237 "git show --name-only --format=''")
238 if git_status == 0:
239 filelist = git_result.split()
240 exitcode = run_unit_tests(args, filelist)
241 elif len(args.file_path) > 0:
242 exitcode = run_unit_tests(args, [args.file_path])
243 else:
244 exitcode = run_unit_tests(args)
245 exit(exitcode)
246
247
248if __name__ == '__main__':
249 parser = argparse.ArgumentParser()
250 parser.add_argument("-p",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000251 "--pep8-ignore",
252 nargs="*",
Milosz Wasilewskiab7645a2016-11-07 10:45:34 +0000253 default=["E501"],
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000254 help="Space separated list of pep8 exclusions",
255 dest="pep8_ignore")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000256 parser.add_argument("-s",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000257 "--shellcheck-ignore",
258 nargs="*",
259 help="Space separated list of shellcheck exclusions",
260 dest="shellcheck_ignore")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000261 parser.add_argument("-g",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000262 "--git-latest",
263 action="store_true",
264 default=False,
265 help="If set, the script will try to evaluate files in last git \
266 commit instead of the whole repository",
267 dest="git_latest")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000268 parser.add_argument("-f",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000269 "--file-path",
270 default="",
271 help="Path to the file that should be checked",
272 dest="file_path")
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000273 parser.add_argument("-r",
274 "--result-file",
275 default="build-error.txt",
276 help="Path to the file that contains results in case of failure",
277 dest="result_file")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000278
279 args = parser.parse_args()
280 main(args)