blob: 3f127c4a15a57d8faeaf9dc30871b1246eac8767 [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
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +000035def pep8_check(filepath, args):
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000036 _fmt = "%(row)d:%(col)d: %(code)s %(text)s"
37 options = {
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +000038 'ignore': args.pep8_ignore,
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000039 "show_source": True}
40 pep8_checker = pep8.StyleGuide(options)
41 fchecker = pep8_checker.checker_class(
42 filepath,
43 options=pep8_checker.options)
44 fchecker.check_all()
45 if fchecker.report.file_errors > 0:
46 result_message_list = []
47 result_message_list.append("* PEP8: [FAILED]: " + filepath)
48 fchecker.report.print_statistics()
49 for line_number, offset, code, text, doc in fchecker.report._deferred_print:
50 result_message_list.append(
51 _fmt % {
52 'path': filepath,
53 'row': fchecker.report.line_offset + line_number,
54 'col': offset + 1,
55 'code': code, 'text': text,
56 })
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +000057 publish_result(result_message_list, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000058 return 1
59 else:
60 message = "* PEP8: [PASSED]: " + filepath
61 print_stderr(message)
62 return 0
63
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +000064
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +000065def metadata_check(filepath, args):
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +000066 if filepath.lower().endswith("yaml"):
Milosz Wasilewskic69b4092017-10-20 14:04:52 +010067 filecontent = None
68 try:
69 with open(filepath, "r") as f:
70 filecontent = f.read()
71 except FileNotFoundError:
72 publish_result(["* METADATA [PASSED]: " + filepath + " - deleted"], args)
73 return 0
74 result_message_list = []
75 y = yaml.load(filecontent)
76 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)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000105 return 0
106
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000107
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000108def validate_yaml(filename, args):
Milosz Wasilewskic69b4092017-10-20 14:04:52 +0100109 filecontent = None
110 try:
111 with open(filename, "r") as f:
112 filecontent = f.read()
113 except FileNotFoundError:
114 publish_result(["* YAMLVALID [PASSED]: " + filename + " - deleted"], args)
115 return 0
116 try:
117 y = yaml.load(filecontent)
118 message = "* YAMLVALID: [PASSED]: " + filename
119 print_stderr(message)
120 except:
121 message = "* YAMLVALID: [FAILED]: " + filename
122 result_message_list = []
123 result_message_list.append(message)
124 result_message_list.append("\n\n")
125 exc_type, exc_value, exc_traceback = sys.exc_info()
126 for line in traceback.format_exception_only(exc_type, exc_value):
127 result_message_list.append(' ' + line)
128 publish_result(result_message_list, args)
129 return 1
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000130 return 0
131
132
133def validate_shell(filename, ignore_options):
134 ignore_string = ""
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000135 if args.shellcheck_ignore is not None:
136 ignore_string = "-e %s" % " ".join(args.shellcheck_ignore)
Milosz Wasilewskiab7645a2016-11-07 10:45:34 +0000137 if len(ignore_string) < 4: # contains only "-e "
138 ignore_string = ""
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000139 cmd = 'shellcheck %s' % ignore_string
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000140 return validate_external(cmd, filename, "SHELLCHECK", args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000141
142
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000143def validate_php(filename, args):
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000144 cmd = 'php -l'
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000145 return validate_external(cmd, filename, "PHPLINT", args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000146
147
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000148def validate_external(cmd, filename, prefix, args):
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000149 final_cmd = "%s %s 2>&1" % (cmd, filename)
150 status, output = subprocess.getstatusoutput(final_cmd)
151 if status == 0:
152 message = '* %s: [PASSED]: %s' % (prefix, filename)
153 print_stderr(message)
154 else:
155 result_message_list = []
156 result_message_list.append('* %s: [FAILED]: %s' % (prefix, filename))
157 result_message_list.append('* %s: [OUTPUT]:' % prefix)
158 for line in output.splitlines():
159 result_message_list.append(' ' + line)
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000160 publish_result(result_message_list, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000161 return 1
162 return 0
163
164
165def validate_file(args, path):
166 exitcode = 0
167 if path.endswith(".yaml"):
Milosz Wasilewskid0b78132016-11-22 19:21:14 +0000168 exitcode = validate_yaml(path, args)
169 if exitcode == 0:
170 # if yaml isn't valid there is no point in checking metadata
171 exitcode = metadata_check(path, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000172 elif run_pep8 and path.endswith(".py"):
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000173 exitcode = pep8_check(path, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000174 elif path.endswith(".php"):
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000175 exitcode = validate_php(path, args)
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000176 elif path.endswith(".sh") or \
177 path.endswith("sh-test-lib") or \
178 path.endswith("android-test-lib"):
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000179 exitcode = validate_shell(path, args)
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000180 return exitcode
181
182
183def run_unit_tests(args, filelist=None):
184 exitcode = 0
185 if filelist is not None:
186 for filename in filelist:
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000187 tmp_exitcode = validate_file(args, filename)
188 if tmp_exitcode != 0:
189 exitcode = 1
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000190 else:
191 for root, dirs, files in os.walk('.'):
192 if not root.startswith("./.git"):
193 for name in files:
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000194 tmp_exitcode = validate_file(
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000195 args,
196 root + "/" + name)
Milosz Wasilewskidb499392016-11-07 19:43:51 +0000197 if tmp_exitcode != 0:
198 exitcode = 1
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000199 return exitcode
200
201
202def main(args):
203 exitcode = 0
204 if args.git_latest:
205 # check if git exists
206 git_status, git_result = subprocess.getstatusoutput(
207 "git show --name-only --format=''")
208 if git_status == 0:
209 filelist = git_result.split()
210 exitcode = run_unit_tests(args, filelist)
211 elif len(args.file_path) > 0:
212 exitcode = run_unit_tests(args, [args.file_path])
213 else:
214 exitcode = run_unit_tests(args)
215 exit(exitcode)
216
217
218if __name__ == '__main__':
219 parser = argparse.ArgumentParser()
220 parser.add_argument("-p",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000221 "--pep8-ignore",
222 nargs="*",
Milosz Wasilewskiab7645a2016-11-07 10:45:34 +0000223 default=["E501"],
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000224 help="Space separated list of pep8 exclusions",
225 dest="pep8_ignore")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000226 parser.add_argument("-s",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000227 "--shellcheck-ignore",
228 nargs="*",
229 help="Space separated list of shellcheck exclusions",
230 dest="shellcheck_ignore")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000231 parser.add_argument("-g",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000232 "--git-latest",
233 action="store_true",
234 default=False,
235 help="If set, the script will try to evaluate files in last git \
236 commit instead of the whole repository",
237 dest="git_latest")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000238 parser.add_argument("-f",
Milosz Wasilewski7ae041c2016-11-07 11:10:06 +0000239 "--file-path",
240 default="",
241 help="Path to the file that should be checked",
242 dest="file_path")
Milosz Wasilewski65d6f0e2016-11-08 13:54:59 +0000243 parser.add_argument("-r",
244 "--result-file",
245 default="build-error.txt",
246 help="Path to the file that contains results in case of failure",
247 dest="result_file")
Milosz Wasilewskidbf52aa2016-11-01 17:51:26 +0000248
249 args = parser.parse_args()
250 main(args)