1 #!/usr/bin/env python3 1 #!/usr/bin/env python3 2 # SPDX-License-Identifier: GPL-2.0 2 # SPDX-License-Identifier: GPL-2.0 3 # Copyright Thomas Gleixner <tglx@linutronix.de 3 # Copyright Thomas Gleixner <tglx@linutronix.de> 4 4 5 from argparse import ArgumentParser 5 from argparse import ArgumentParser 6 from ply import lex, yacc 6 from ply import lex, yacc 7 import locale 7 import locale 8 import traceback 8 import traceback 9 import fnmatch << 10 import sys 9 import sys 11 import git 10 import git 12 import re 11 import re 13 import os 12 import os 14 13 15 class ParserException(Exception): 14 class ParserException(Exception): 16 def __init__(self, tok, txt): 15 def __init__(self, tok, txt): 17 self.tok = tok 16 self.tok = tok 18 self.txt = txt 17 self.txt = txt 19 18 20 class SPDXException(Exception): 19 class SPDXException(Exception): 21 def __init__(self, el, txt): 20 def __init__(self, el, txt): 22 self.el = el 21 self.el = el 23 self.txt = txt 22 self.txt = txt 24 23 25 class SPDXdata(object): 24 class SPDXdata(object): 26 def __init__(self): 25 def __init__(self): 27 self.license_files = 0 26 self.license_files = 0 28 self.exception_files = 0 27 self.exception_files = 0 29 self.licenses = [ ] 28 self.licenses = [ ] 30 self.exceptions = { } 29 self.exceptions = { } 31 30 32 class dirinfo(object): << 33 def __init__(self): << 34 self.missing = 0 << 35 self.total = 0 << 36 self.files = [] << 37 << 38 def update(self, fname, basedir, miss): << 39 self.total += 1 << 40 self.missing += miss << 41 if miss: << 42 fname = './' + fname << 43 bdir = os.path.dirname(fname) << 44 if bdir == basedir.rstrip('/'): << 45 self.files.append(fname) << 46 << 47 # Read the spdx data from the LICENSES directo 31 # Read the spdx data from the LICENSES directory 48 def read_spdxdata(repo): 32 def read_spdxdata(repo): 49 33 50 # The subdirectories of LICENSES in the ke 34 # The subdirectories of LICENSES in the kernel source 51 # Note: exceptions needs to be parsed as l 35 # Note: exceptions needs to be parsed as last directory. 52 license_dirs = [ "preferred", "dual", "dep 36 license_dirs = [ "preferred", "dual", "deprecated", "exceptions" ] 53 lictree = repo.head.commit.tree['LICENSES' 37 lictree = repo.head.commit.tree['LICENSES'] 54 38 55 spdx = SPDXdata() 39 spdx = SPDXdata() 56 40 57 for d in license_dirs: 41 for d in license_dirs: 58 for el in lictree[d].traverse(): 42 for el in lictree[d].traverse(): 59 if not os.path.isfile(el.path): 43 if not os.path.isfile(el.path): 60 continue 44 continue 61 45 62 exception = None 46 exception = None 63 for l in open(el.path, encoding="u 47 for l in open(el.path, encoding="utf-8").readlines(): 64 if l.startswith('Valid-License 48 if l.startswith('Valid-License-Identifier:'): 65 lid = l.split(':')[1].stri 49 lid = l.split(':')[1].strip().upper() 66 if lid in spdx.licenses: 50 if lid in spdx.licenses: 67 raise SPDXException(el 51 raise SPDXException(el, 'Duplicate License Identifier: %s' %lid) 68 else: 52 else: 69 spdx.licenses.append(l 53 spdx.licenses.append(lid) 70 54 71 elif l.startswith('SPDX-Except 55 elif l.startswith('SPDX-Exception-Identifier:'): 72 exception = l.split(':')[1 56 exception = l.split(':')[1].strip().upper() 73 spdx.exceptions[exception] 57 spdx.exceptions[exception] = [] 74 58 75 elif l.startswith('SPDX-Licens 59 elif l.startswith('SPDX-Licenses:'): 76 for lic in l.split(':')[1] 60 for lic in l.split(':')[1].upper().strip().replace(' ', '').replace('\t', '').split(','): 77 if not lic in spdx.lic 61 if not lic in spdx.licenses: 78 raise SPDXExceptio 62 raise SPDXException(None, 'Exception %s missing license %s' %(exception, lic)) 79 spdx.exceptions[except 63 spdx.exceptions[exception].append(lic) 80 64 81 elif l.startswith("License-Tex 65 elif l.startswith("License-Text:"): 82 if exception: 66 if exception: 83 if not len(spdx.except 67 if not len(spdx.exceptions[exception]): 84 raise SPDXExceptio 68 raise SPDXException(el, 'Exception %s is missing SPDX-Licenses' %exception) 85 spdx.exception_files + 69 spdx.exception_files += 1 86 else: 70 else: 87 spdx.license_files += 71 spdx.license_files += 1 88 break 72 break 89 return spdx 73 return spdx 90 74 91 class id_parser(object): 75 class id_parser(object): 92 76 93 reserved = [ 'AND', 'OR', 'WITH' ] 77 reserved = [ 'AND', 'OR', 'WITH' ] 94 tokens = [ 'LPAR', 'RPAR', 'ID', 'EXC' ] + 78 tokens = [ 'LPAR', 'RPAR', 'ID', 'EXC' ] + reserved 95 79 96 precedence = ( ('nonassoc', 'AND', 'OR'), 80 precedence = ( ('nonassoc', 'AND', 'OR'), ) 97 81 98 t_ignore = ' \t' 82 t_ignore = ' \t' 99 83 100 def __init__(self, spdx): 84 def __init__(self, spdx): 101 self.spdx = spdx 85 self.spdx = spdx 102 self.lasttok = None 86 self.lasttok = None 103 self.lastid = None 87 self.lastid = None 104 self.lexer = lex.lex(module = self, re 88 self.lexer = lex.lex(module = self, reflags = re.UNICODE) 105 # Initialize the parser. No debug file 89 # Initialize the parser. No debug file and no parser rules stored on disk 106 # The rules are small enough to be gen 90 # The rules are small enough to be generated on the fly 107 self.parser = yacc.yacc(module = self, 91 self.parser = yacc.yacc(module = self, write_tables = False, debug = False) 108 self.lines_checked = 0 92 self.lines_checked = 0 109 self.checked = 0 93 self.checked = 0 110 self.excluded = 0 << 111 self.spdx_valid = 0 94 self.spdx_valid = 0 112 self.spdx_errors = 0 95 self.spdx_errors = 0 113 self.spdx_dirs = {} << 114 self.dirdepth = -1 << 115 self.basedir = '.' << 116 self.curline = 0 96 self.curline = 0 117 self.deepest = 0 97 self.deepest = 0 118 98 119 def set_dirinfo(self, basedir, dirdepth): << 120 if dirdepth >= 0: << 121 self.basedir = basedir << 122 bdir = basedir.lstrip('./').rstrip << 123 if bdir != '': << 124 parts = bdir.split('/') << 125 else: << 126 parts = [] << 127 self.dirdepth = dirdepth + len(par << 128 << 129 # Validate License and Exception IDs 99 # Validate License and Exception IDs 130 def validate(self, tok): 100 def validate(self, tok): 131 id = tok.value.upper() 101 id = tok.value.upper() 132 if tok.type == 'ID': 102 if tok.type == 'ID': 133 if not id in self.spdx.licenses: 103 if not id in self.spdx.licenses: 134 raise ParserException(tok, 'In 104 raise ParserException(tok, 'Invalid License ID') 135 self.lastid = id 105 self.lastid = id 136 elif tok.type == 'EXC': 106 elif tok.type == 'EXC': 137 if id not in self.spdx.exceptions: 107 if id not in self.spdx.exceptions: 138 raise ParserException(tok, 'In 108 raise ParserException(tok, 'Invalid Exception ID') 139 if self.lastid not in self.spdx.ex 109 if self.lastid not in self.spdx.exceptions[id]: 140 raise ParserException(tok, 'Ex 110 raise ParserException(tok, 'Exception not valid for license %s' %self.lastid) 141 self.lastid = None 111 self.lastid = None 142 elif tok.type != 'WITH': 112 elif tok.type != 'WITH': 143 self.lastid = None 113 self.lastid = None 144 114 145 # Lexer functions 115 # Lexer functions 146 def t_RPAR(self, tok): 116 def t_RPAR(self, tok): 147 r'\)' 117 r'\)' 148 self.lasttok = tok.type 118 self.lasttok = tok.type 149 return tok 119 return tok 150 120 151 def t_LPAR(self, tok): 121 def t_LPAR(self, tok): 152 r'\(' 122 r'\(' 153 self.lasttok = tok.type 123 self.lasttok = tok.type 154 return tok 124 return tok 155 125 156 def t_ID(self, tok): 126 def t_ID(self, tok): 157 r'[A-Za-z.0-9\-+]+' 127 r'[A-Za-z.0-9\-+]+' 158 128 159 if self.lasttok == 'EXC': 129 if self.lasttok == 'EXC': 160 print(tok) 130 print(tok) 161 raise ParserException(tok, 'Missin 131 raise ParserException(tok, 'Missing parentheses') 162 132 163 tok.value = tok.value.strip() 133 tok.value = tok.value.strip() 164 val = tok.value.upper() 134 val = tok.value.upper() 165 135 166 if val in self.reserved: 136 if val in self.reserved: 167 tok.type = val 137 tok.type = val 168 elif self.lasttok == 'WITH': 138 elif self.lasttok == 'WITH': 169 tok.type = 'EXC' 139 tok.type = 'EXC' 170 140 171 self.lasttok = tok.type 141 self.lasttok = tok.type 172 self.validate(tok) 142 self.validate(tok) 173 return tok 143 return tok 174 144 175 def t_error(self, tok): 145 def t_error(self, tok): 176 raise ParserException(tok, 'Invalid to 146 raise ParserException(tok, 'Invalid token') 177 147 178 def p_expr(self, p): 148 def p_expr(self, p): 179 '''expr : ID 149 '''expr : ID 180 | ID WITH EXC 150 | ID WITH EXC 181 | expr AND expr 151 | expr AND expr 182 | expr OR expr 152 | expr OR expr 183 | LPAR expr RPAR''' 153 | LPAR expr RPAR''' 184 pass 154 pass 185 155 186 def p_error(self, p): 156 def p_error(self, p): 187 if not p: 157 if not p: 188 raise ParserException(None, 'Unfin 158 raise ParserException(None, 'Unfinished license expression') 189 else: 159 else: 190 raise ParserException(p, 'Syntax e 160 raise ParserException(p, 'Syntax error') 191 161 192 def parse(self, expr): 162 def parse(self, expr): 193 self.lasttok = None 163 self.lasttok = None 194 self.lastid = None 164 self.lastid = None 195 self.parser.parse(expr, lexer = self.l 165 self.parser.parse(expr, lexer = self.lexer) 196 166 197 def parse_lines(self, fd, maxlines, fname) 167 def parse_lines(self, fd, maxlines, fname): 198 self.checked += 1 168 self.checked += 1 199 self.curline = 0 169 self.curline = 0 200 fail = 1 << 201 try: 170 try: 202 for line in fd: 171 for line in fd: 203 line = line.decode(locale.getp 172 line = line.decode(locale.getpreferredencoding(False), errors='ignore') 204 self.curline += 1 173 self.curline += 1 205 if self.curline > maxlines: 174 if self.curline > maxlines: 206 break 175 break 207 self.lines_checked += 1 176 self.lines_checked += 1 208 if line.find("SPDX-License-Ide 177 if line.find("SPDX-License-Identifier:") < 0: 209 continue 178 continue 210 expr = line.split(':')[1].stri 179 expr = line.split(':')[1].strip() 211 # Remove trailing comment clos 180 # Remove trailing comment closure 212 if line.strip().endswith('*/') 181 if line.strip().endswith('*/'): 213 expr = expr.rstrip('*/').s 182 expr = expr.rstrip('*/').strip() 214 # Remove trailing xml comment 183 # Remove trailing xml comment closure 215 if line.strip().endswith('-->' 184 if line.strip().endswith('-->'): 216 expr = expr.rstrip('-->'). 185 expr = expr.rstrip('-->').strip() 217 # Special case for SH magic bo 186 # Special case for SH magic boot code files 218 if line.startswith('LIST \"'): 187 if line.startswith('LIST \"'): 219 expr = expr.rstrip('\"').s 188 expr = expr.rstrip('\"').strip() 220 self.parse(expr) 189 self.parse(expr) 221 self.spdx_valid += 1 190 self.spdx_valid += 1 222 # 191 # 223 # Should we check for more SPD 192 # Should we check for more SPDX ids in the same file and 224 # complain if there are any? 193 # complain if there are any? 225 # 194 # 226 fail = 0 << 227 break 195 break 228 196 229 except ParserException as pe: 197 except ParserException as pe: 230 if pe.tok: 198 if pe.tok: 231 col = line.find(expr) + pe.tok 199 col = line.find(expr) + pe.tok.lexpos 232 tok = pe.tok.value 200 tok = pe.tok.value 233 sys.stdout.write('%s: %d:%d %s 201 sys.stdout.write('%s: %d:%d %s: %s\n' %(fname, self.curline, col, pe.txt, tok)) 234 else: 202 else: 235 sys.stdout.write('%s: %d:0 %s\ 203 sys.stdout.write('%s: %d:0 %s\n' %(fname, self.curline, pe.txt)) 236 self.spdx_errors += 1 204 self.spdx_errors += 1 237 205 238 if fname == '-': !! 206 def scan_git_tree(tree): 239 return << 240 << 241 base = os.path.dirname(fname) << 242 if self.dirdepth > 0: << 243 parts = base.split('/') << 244 i = 0 << 245 base = '.' << 246 while i < self.dirdepth and i < le << 247 base += '/' + parts[i] << 248 i += 1 << 249 elif self.dirdepth == 0: << 250 base = self.basedir << 251 else: << 252 base = './' + base.rstrip('/') << 253 base += '/' << 254 << 255 di = self.spdx_dirs.get(base, dirinfo( << 256 di.update(fname, base, fail) << 257 self.spdx_dirs[base] = di << 258 << 259 class pattern(object): << 260 def __init__(self, line): << 261 self.pattern = line << 262 self.match = self.match_file << 263 if line == '.*': << 264 self.match = self.match_dot << 265 elif line.endswith('/'): << 266 self.pattern = line[:-1] << 267 self.match = self.match_dir << 268 elif line.startswith('/'): << 269 self.pattern = line[1:] << 270 self.match = self.match_fn << 271 << 272 def match_dot(self, fpath): << 273 return os.path.basename(fpath).startsw << 274 << 275 def match_file(self, fpath): << 276 return os.path.basename(fpath) == self << 277 << 278 def match_fn(self, fpath): << 279 return fnmatch.fnmatchcase(fpath, self << 280 << 281 def match_dir(self, fpath): << 282 if self.match_fn(os.path.dirname(fpath << 283 return True << 284 return fpath.startswith(self.pattern) << 285 << 286 def exclude_file(fpath): << 287 for rule in exclude_rules: << 288 if rule.match(fpath): << 289 return True << 290 return False << 291 << 292 def scan_git_tree(tree, basedir, dirdepth): << 293 parser.set_dirinfo(basedir, dirdepth) << 294 for el in tree.traverse(): 207 for el in tree.traverse(): 295 if not os.path.isfile(el.path): !! 208 # Exclude stuff which would make pointless noise >> 209 # FIXME: Put this somewhere more sensible >> 210 if el.path.startswith("LICENSES"): 296 continue 211 continue 297 if exclude_file(el.path): !! 212 if el.path.find("license-rules.rst") >= 0: 298 parser.excluded += 1 !! 213 continue >> 214 if not os.path.isfile(el.path): 299 continue 215 continue 300 with open(el.path, 'rb') as fd: 216 with open(el.path, 'rb') as fd: 301 parser.parse_lines(fd, args.maxlin 217 parser.parse_lines(fd, args.maxlines, el.path) 302 218 303 def scan_git_subtree(tree, path, dirdepth): !! 219 def scan_git_subtree(tree, path): 304 for p in path.strip('/').split('/'): 220 for p in path.strip('/').split('/'): 305 tree = tree[p] 221 tree = tree[p] 306 scan_git_tree(tree, path.strip('/'), dirde !! 222 scan_git_tree(tree) 307 << 308 def read_exclude_file(fname): << 309 rules = [] << 310 if not fname: << 311 return rules << 312 with open(fname) as fd: << 313 for line in fd: << 314 line = line.strip() << 315 if line.startswith('#'): << 316 continue << 317 if not len(line): << 318 continue << 319 rules.append(pattern(line)) << 320 return rules << 321 223 322 if __name__ == '__main__': 224 if __name__ == '__main__': 323 225 324 ap = ArgumentParser(description='SPDX expr 226 ap = ArgumentParser(description='SPDX expression checker') 325 ap.add_argument('path', nargs='*', help='C 227 ap.add_argument('path', nargs='*', help='Check path or file. If not given full git tree scan. For stdin use "-"') 326 ap.add_argument('-d', '--dirs', action='st << 327 help='Show [sub]directory << 328 ap.add_argument('-D', '--depth', type=int, << 329 help='Directory depth for << 330 ap.add_argument('-e', '--exclude', << 331 help='File containing file << 332 ap.add_argument('-f', '--files', action='s << 333 help='Show files without S << 334 ap.add_argument('-m', '--maxlines', type=i 228 ap.add_argument('-m', '--maxlines', type=int, default=15, 335 help='Maximum number of li 229 help='Maximum number of lines to scan in a file. Default 15') 336 ap.add_argument('-v', '--verbose', action= 230 ap.add_argument('-v', '--verbose', action='store_true', help='Verbose statistics output') 337 args = ap.parse_args() 231 args = ap.parse_args() 338 232 339 # Sanity check path arguments 233 # Sanity check path arguments 340 if '-' in args.path and len(args.path) > 1 234 if '-' in args.path and len(args.path) > 1: 341 sys.stderr.write('stdin input "-" must 235 sys.stderr.write('stdin input "-" must be the only path argument\n') 342 sys.exit(1) 236 sys.exit(1) 343 237 344 try: 238 try: 345 # Use git to get the valid license exp 239 # Use git to get the valid license expressions 346 repo = git.Repo(os.getcwd()) 240 repo = git.Repo(os.getcwd()) 347 assert not repo.bare 241 assert not repo.bare 348 242 349 # Initialize SPDX data 243 # Initialize SPDX data 350 spdx = read_spdxdata(repo) 244 spdx = read_spdxdata(repo) 351 245 352 # Initialize the parser 246 # Initialize the parser 353 parser = id_parser(spdx) 247 parser = id_parser(spdx) 354 248 355 except SPDXException as se: 249 except SPDXException as se: 356 if se.el: 250 if se.el: 357 sys.stderr.write('%s: %s\n' %(se.e 251 sys.stderr.write('%s: %s\n' %(se.el.path, se.txt)) 358 else: 252 else: 359 sys.stderr.write('%s\n' %se.txt) 253 sys.stderr.write('%s\n' %se.txt) 360 sys.exit(1) 254 sys.exit(1) 361 255 362 except Exception as ex: 256 except Exception as ex: 363 sys.stderr.write('FAIL: %s\n' %ex) 257 sys.stderr.write('FAIL: %s\n' %ex) 364 sys.stderr.write('%s\n' %traceback.for 258 sys.stderr.write('%s\n' %traceback.format_exc()) 365 sys.exit(1) 259 sys.exit(1) 366 260 367 try: 261 try: 368 fname = args.exclude << 369 if not fname: << 370 fname = os.path.join(os.path.dirna << 371 exclude_rules = read_exclude_file(fnam << 372 except Exception as ex: << 373 sys.stderr.write('FAIL: Reading exclud << 374 sys.exit(1) << 375 << 376 try: << 377 if len(args.path) and args.path[0] == 262 if len(args.path) and args.path[0] == '-': 378 stdin = os.fdopen(sys.stdin.fileno 263 stdin = os.fdopen(sys.stdin.fileno(), 'rb') 379 parser.parse_lines(stdin, args.max 264 parser.parse_lines(stdin, args.maxlines, '-') 380 else: 265 else: 381 if args.path: 266 if args.path: 382 for p in args.path: 267 for p in args.path: 383 if os.path.isfile(p): 268 if os.path.isfile(p): 384 parser.parse_lines(ope 269 parser.parse_lines(open(p, 'rb'), args.maxlines, p) 385 elif os.path.isdir(p): 270 elif os.path.isdir(p): 386 scan_git_subtree(repo. !! 271 scan_git_subtree(repo.head.reference.commit.tree, p) 387 args. << 388 else: 272 else: 389 sys.stderr.write('path 273 sys.stderr.write('path %s does not exist\n' %p) 390 sys.exit(1) 274 sys.exit(1) 391 else: 275 else: 392 # Full git tree scan 276 # Full git tree scan 393 scan_git_tree(repo.head.commit !! 277 scan_git_tree(repo.head.commit.tree) 394 << 395 ndirs = len(parser.spdx_dirs) << 396 dirsok = 0 << 397 if ndirs: << 398 for di in parser.spdx_dirs.val << 399 if not di.missing: << 400 dirsok += 1 << 401 278 402 if args.verbose: 279 if args.verbose: 403 sys.stderr.write('\n') 280 sys.stderr.write('\n') 404 sys.stderr.write('License file 281 sys.stderr.write('License files: %12d\n' %spdx.license_files) 405 sys.stderr.write('Exception fi 282 sys.stderr.write('Exception files: %12d\n' %spdx.exception_files) 406 sys.stderr.write('License IDs 283 sys.stderr.write('License IDs %12d\n' %len(spdx.licenses)) 407 sys.stderr.write('Exception ID 284 sys.stderr.write('Exception IDs %12d\n' %len(spdx.exceptions)) 408 sys.stderr.write('\n') 285 sys.stderr.write('\n') 409 sys.stderr.write('Files exclud << 410 sys.stderr.write('Files checke 286 sys.stderr.write('Files checked: %12d\n' %parser.checked) 411 sys.stderr.write('Lines checke 287 sys.stderr.write('Lines checked: %12d\n' %parser.lines_checked) 412 if parser.checked: !! 288 sys.stderr.write('Files with SPDX: %12d\n' %parser.spdx_valid) 413 pc = int(100 * parser.spdx << 414 sys.stderr.write('Files wi << 415 missing = parser.checked - << 416 mpc = int(100 * missing / << 417 sys.stderr.write('Files wi << 418 sys.stderr.write('Files with e 289 sys.stderr.write('Files with errors: %12d\n' %parser.spdx_errors) 419 if ndirs: << 420 sys.stderr.write('\n') << 421 sys.stderr.write('Director << 422 pc = int(100 * dirsok / nd << 423 sys.stderr.write('Director << 424 << 425 if ndirs and ndirs != dirsok and a << 426 if args.verbose: << 427 sys.stderr.write('\n') << 428 sys.stderr.write('Incomplete d << 429 for f in sorted(parser.spdx_di << 430 di = parser.spdx_dirs[f] << 431 if di.missing: << 432 valid = di.total - di. << 433 pc = int(100 * valid / << 434 sys.stderr.write(' << 435 << 436 if ndirs and ndirs != dirsok and a << 437 if args.verbose or args.dirs: << 438 sys.stderr.write('\n') << 439 sys.stderr.write('Files withou << 440 for f in sorted(parser.spdx_di << 441 di = parser.spdx_dirs[f] << 442 for f in sorted(di.files): << 443 sys.stderr.write(' << 444 290 445 sys.exit(0) 291 sys.exit(0) 446 292 447 except Exception as ex: 293 except Exception as ex: 448 sys.stderr.write('FAIL: %s\n' %ex) 294 sys.stderr.write('FAIL: %s\n' %ex) 449 sys.stderr.write('%s\n' %traceback.for 295 sys.stderr.write('%s\n' %traceback.format_exc()) 450 sys.exit(1) 296 sys.exit(1)
Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.