blob: 28c62e486957da4971d477fa362925b18b028666 [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
Chase Qi30290532018-11-20 18:54:43 +08009run_pycodestyle = False
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000010try:
Chase Qi30290532018-11-20 18:54:43 +080011 import pycodestyle
12 run_pycodestyle = True
13except ImportError:
14 print("pycodestyle 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
Chase Qi30290532018-11-20 18:54:43 +080043def pycodestyle_check(filepath, args):
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000044 _fmt = "%(row)d:%(col)d: %(code)s %(text)s"
45 options = {
Chase Qi30290532018-11-20 18:54:43 +080046 'ignore': args.pycodestyle_ignore,
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000047 "show_source": True}
Chase Qi30290532018-11-20 18:54:43 +080048 pycodestyle_checker = pycodestyle.StyleGuide(options)
49 fchecker = pycodestyle_checker.checker_class(
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000050 filepath,
Chase Qi30290532018-11-20 18:54:43 +080051 options=pycodestyle_checker.options)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000052 fchecker.check_all()
53 if fchecker.report.file_errors > 0:
54 result_message_list = []
Chase Qi30290532018-11-20 18:54:43 +080055 result_message_list.append("* PYCODESTYLE: [FAILED]: " + filepath)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000056 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:
Chase Qi30290532018-11-20 18:54:43 +080068 message = "* PYCODESTYLE: [PASSED]: " + filepath
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000069 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:
Chase Qied017432018-12-14 16:56:20 +0800147 yaml.load(filecontent)
Milosz Wasilewskic69b4092017-10-20 14:04:52 +0100148 message = "* YAMLVALID: [PASSED]: " + filename
149 print_stderr(message)
Chase Qi30290532018-11-20 18:54:43 +0800150 except yaml.YAMLError:
Milosz Wasilewskic69b4092017-10-20 14:04:52 +0100151 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:
Chase Qied017432018-12-14 16:56:20 +0800166 # Exclude types of warnings in the following format:
167 # -e CODE1,CODE2..
168 ignore_string = "-e %s" % ",".join(args.shellcheck_ignore)
Milosz Wasilewskiab7645a2016-11-07 10:45:34 +0000169 if len(ignore_string) < 4: # contains only "-e "
170 ignore_string = ""
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000171 cmd = 'shellcheck %s' % ignore_string
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000172 return validate_external(cmd, filename, "SHELLCHECK", args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000173
174
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000175def validate_php(filename, args):
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000176 cmd = 'php -l'
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000177 return validate_external(cmd, filename, "PHPLINT", args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000178
179
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000180def validate_external(cmd, filename, prefix, args):
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000181 final_cmd = "%s %s 2>&1" % (cmd, filename)
182 status, output = subprocess.getstatusoutput(final_cmd)
183 if status == 0:
184 message = '* %s: [PASSED]: %s' % (prefix, filename)
185 print_stderr(message)
186 else:
187 result_message_list = []
188 result_message_list.append('* %s: [FAILED]: %s' % (prefix, filename))
189 result_message_list.append('* %s: [OUTPUT]:' % prefix)
190 for line in output.splitlines():
191 result_message_list.append(' ' + line)
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000192 publish_result(result_message_list, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000193 return 1
194 return 0
195
196
197def validate_file(args, path):
198 exitcode = 0
199 if path.endswith(".yaml"):
Milosz Wasilewskid0b78132016-11-22 19:21:14 +0000200 exitcode = validate_yaml(path, args)
201 if exitcode == 0:
202 # if yaml isn't valid there is no point in checking metadata
Dan Rue8ec540c2018-01-25 14:38:12 -0600203 exitcode = validate_yaml_contents(path, args)
Chase Qi30290532018-11-20 18:54:43 +0800204 elif run_pycodestyle and path.endswith(".py"):
205 exitcode = pycodestyle_check(path, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000206 elif path.endswith(".php"):
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000207 exitcode = validate_php(path, args)
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000208 elif path.endswith(".sh") or \
209 path.endswith("sh-test-lib") or \
210 path.endswith("android-test-lib"):
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000211 exitcode = validate_shell(path, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000212 return exitcode
213
214
215def run_unit_tests(args, filelist=None):
216 exitcode = 0
217 if filelist is not None:
218 for filename in filelist:
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000219 tmp_exitcode = validate_file(args, filename)
220 if tmp_exitcode != 0:
221 exitcode = 1
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000222 else:
223 for root, dirs, files in os.walk('.'):
224 if not root.startswith("./.git"):
225 for name in files:
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000226 tmp_exitcode = validate_file(
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000227 args,
228 root + "/" + name)
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000229 if tmp_exitcode != 0:
230 exitcode = 1
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000231 return exitcode
232
233
234def main(args):
235 exitcode = 0
236 if args.git_latest:
237 # check if git exists
238 git_status, git_result = subprocess.getstatusoutput(
239 "git show --name-only --format=''")
240 if git_status == 0:
241 filelist = git_result.split()
242 exitcode = run_unit_tests(args, filelist)
243 elif len(args.file_path) > 0:
244 exitcode = run_unit_tests(args, [args.file_path])
245 else:
246 exitcode = run_unit_tests(args)
247 exit(exitcode)
248
249
250if __name__ == '__main__':
251 parser = argparse.ArgumentParser()
252 parser.add_argument("-p",
Chase Qi30290532018-11-20 18:54:43 +0800253 "--pycodestyle-ignore",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000254 nargs="*",
Milosz Wasilewskiab7645a2016-11-07 10:45:34 +0000255 default=["E501"],
Chase Qi30290532018-11-20 18:54:43 +0800256 help="Space separated list of pycodestyle exclusions",
257 dest="pycodestyle_ignore")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000258 parser.add_argument("-s",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000259 "--shellcheck-ignore",
260 nargs="*",
261 help="Space separated list of shellcheck exclusions",
262 dest="shellcheck_ignore")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000263 parser.add_argument("-g",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000264 "--git-latest",
265 action="store_true",
266 default=False,
267 help="If set, the script will try to evaluate files in last git \
268 commit instead of the whole repository",
269 dest="git_latest")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000270 parser.add_argument("-f",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000271 "--file-path",
272 default="",
273 help="Path to the file that should be checked",
274 dest="file_path")
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000275 parser.add_argument("-r",
276 "--result-file",
277 default="build-error.txt",
278 help="Path to the file that contains results in case of failure",
279 dest="result_file")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000280
281 args = parser.parse_args()
282 main(args)