spdxcheck.py 16 KB

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