spdxcheck.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. # Copyright Thomas Gleixner <[email protected]>
  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. # Special case for SH magic boot code files
  185. if line.startswith('LIST \"'):
  186. expr = expr.rstrip('\"').strip()
  187. self.parse(expr)
  188. self.spdx_valid += 1
  189. #
  190. # Should we check for more SPDX ids in the same file and
  191. # complain if there are any?
  192. #
  193. fail = 0
  194. break
  195. except ParserException as pe:
  196. if pe.tok:
  197. col = line.find(expr) + pe.tok.lexpos
  198. tok = pe.tok.value
  199. sys.stdout.write('%s: %d:%d %s: %s\n' %(fname, self.curline, col, pe.txt, tok))
  200. else:
  201. sys.stdout.write('%s: %d:0 %s\n' %(fname, self.curline, pe.txt))
  202. self.spdx_errors += 1
  203. if fname == '-':
  204. return
  205. base = os.path.dirname(fname)
  206. if self.dirdepth > 0:
  207. parts = base.split('/')
  208. i = 0
  209. base = '.'
  210. while i < self.dirdepth and i < len(parts) and len(parts[i]):
  211. base += '/' + parts[i]
  212. i += 1
  213. elif self.dirdepth == 0:
  214. base = self.basedir
  215. else:
  216. base = './' + base.rstrip('/')
  217. base += '/'
  218. di = self.spdx_dirs.get(base, dirinfo())
  219. di.update(fname, base, fail)
  220. self.spdx_dirs[base] = di
  221. class pattern(object):
  222. def __init__(self, line):
  223. self.pattern = line
  224. self.match = self.match_file
  225. if line == '.*':
  226. self.match = self.match_dot
  227. elif line.endswith('/'):
  228. self.pattern = line[:-1]
  229. self.match = self.match_dir
  230. elif line.startswith('/'):
  231. self.pattern = line[1:]
  232. self.match = self.match_fn
  233. def match_dot(self, fpath):
  234. return os.path.basename(fpath).startswith('.')
  235. def match_file(self, fpath):
  236. return os.path.basename(fpath) == self.pattern
  237. def match_fn(self, fpath):
  238. return fnmatch.fnmatchcase(fpath, self.pattern)
  239. def match_dir(self, fpath):
  240. if self.match_fn(os.path.dirname(fpath)):
  241. return True
  242. return fpath.startswith(self.pattern)
  243. def exclude_file(fpath):
  244. for rule in exclude_rules:
  245. if rule.match(fpath):
  246. return True
  247. return False
  248. def scan_git_tree(tree, basedir, dirdepth):
  249. parser.set_dirinfo(basedir, dirdepth)
  250. for el in tree.traverse():
  251. if not os.path.isfile(el.path):
  252. continue
  253. if exclude_file(el.path):
  254. parser.excluded += 1
  255. continue
  256. with open(el.path, 'rb') as fd:
  257. parser.parse_lines(fd, args.maxlines, el.path)
  258. def scan_git_subtree(tree, path, dirdepth):
  259. for p in path.strip('/').split('/'):
  260. tree = tree[p]
  261. scan_git_tree(tree, path.strip('/'), dirdepth)
  262. def read_exclude_file(fname):
  263. rules = []
  264. if not fname:
  265. return rules
  266. with open(fname) as fd:
  267. for line in fd:
  268. line = line.strip()
  269. if line.startswith('#'):
  270. continue
  271. if not len(line):
  272. continue
  273. rules.append(pattern(line))
  274. return rules
  275. if __name__ == '__main__':
  276. ap = ArgumentParser(description='SPDX expression checker')
  277. ap.add_argument('path', nargs='*', help='Check path or file. If not given full git tree scan. For stdin use "-"')
  278. ap.add_argument('-d', '--dirs', action='store_true',
  279. help='Show [sub]directory statistics.')
  280. ap.add_argument('-D', '--depth', type=int, default=-1,
  281. help='Directory depth for -d statistics. Default: unlimited')
  282. ap.add_argument('-e', '--exclude',
  283. help='File containing file patterns to exclude. Default: scripts/spdxexclude')
  284. ap.add_argument('-f', '--files', action='store_true',
  285. help='Show files without SPDX.')
  286. ap.add_argument('-m', '--maxlines', type=int, default=15,
  287. help='Maximum number of lines to scan in a file. Default 15')
  288. ap.add_argument('-v', '--verbose', action='store_true', help='Verbose statistics output')
  289. args = ap.parse_args()
  290. # Sanity check path arguments
  291. if '-' in args.path and len(args.path) > 1:
  292. sys.stderr.write('stdin input "-" must be the only path argument\n')
  293. sys.exit(1)
  294. try:
  295. # Use git to get the valid license expressions
  296. repo = git.Repo(os.getcwd())
  297. assert not repo.bare
  298. # Initialize SPDX data
  299. spdx = read_spdxdata(repo)
  300. # Initialize the parser
  301. parser = id_parser(spdx)
  302. except SPDXException as se:
  303. if se.el:
  304. sys.stderr.write('%s: %s\n' %(se.el.path, se.txt))
  305. else:
  306. sys.stderr.write('%s\n' %se.txt)
  307. sys.exit(1)
  308. except Exception as ex:
  309. sys.stderr.write('FAIL: %s\n' %ex)
  310. sys.stderr.write('%s\n' %traceback.format_exc())
  311. sys.exit(1)
  312. try:
  313. fname = args.exclude
  314. if not fname:
  315. fname = os.path.join(os.path.dirname(__file__), 'spdxexclude')
  316. exclude_rules = read_exclude_file(fname)
  317. except Exception as ex:
  318. sys.stderr.write('FAIL: Reading exclude file %s: %s\n' %(fname, ex))
  319. sys.exit(1)
  320. try:
  321. if len(args.path) and args.path[0] == '-':
  322. stdin = os.fdopen(sys.stdin.fileno(), 'rb')
  323. parser.parse_lines(stdin, args.maxlines, '-')
  324. else:
  325. if args.path:
  326. for p in args.path:
  327. if os.path.isfile(p):
  328. parser.parse_lines(open(p, 'rb'), args.maxlines, p)
  329. elif os.path.isdir(p):
  330. scan_git_subtree(repo.head.reference.commit.tree, p,
  331. args.depth)
  332. else:
  333. sys.stderr.write('path %s does not exist\n' %p)
  334. sys.exit(1)
  335. else:
  336. # Full git tree scan
  337. scan_git_tree(repo.head.commit.tree, '.', args.depth)
  338. ndirs = len(parser.spdx_dirs)
  339. dirsok = 0
  340. if ndirs:
  341. for di in parser.spdx_dirs.values():
  342. if not di.missing:
  343. dirsok += 1
  344. if args.verbose:
  345. sys.stderr.write('\n')
  346. sys.stderr.write('License files: %12d\n' %spdx.license_files)
  347. sys.stderr.write('Exception files: %12d\n' %spdx.exception_files)
  348. sys.stderr.write('License IDs %12d\n' %len(spdx.licenses))
  349. sys.stderr.write('Exception IDs %12d\n' %len(spdx.exceptions))
  350. sys.stderr.write('\n')
  351. sys.stderr.write('Files excluded: %12d\n' %parser.excluded)
  352. sys.stderr.write('Files checked: %12d\n' %parser.checked)
  353. sys.stderr.write('Lines checked: %12d\n' %parser.lines_checked)
  354. if parser.checked:
  355. pc = int(100 * parser.spdx_valid / parser.checked)
  356. sys.stderr.write('Files with SPDX: %12d %3d%%\n' %(parser.spdx_valid, pc))
  357. sys.stderr.write('Files with errors: %12d\n' %parser.spdx_errors)
  358. if ndirs:
  359. sys.stderr.write('\n')
  360. sys.stderr.write('Directories accounted: %8d\n' %ndirs)
  361. pc = int(100 * dirsok / ndirs)
  362. sys.stderr.write('Directories complete: %8d %3d%%\n' %(dirsok, pc))
  363. if ndirs and ndirs != dirsok and args.dirs:
  364. if args.verbose:
  365. sys.stderr.write('\n')
  366. sys.stderr.write('Incomplete directories: SPDX in Files\n')
  367. for f in sorted(parser.spdx_dirs.keys()):
  368. di = parser.spdx_dirs[f]
  369. if di.missing:
  370. valid = di.total - di.missing
  371. pc = int(100 * valid / di.total)
  372. sys.stderr.write(' %-80s: %5d of %5d %3d%%\n' %(f, valid, di.total, pc))
  373. if ndirs and ndirs != dirsok and args.files:
  374. if args.verbose or args.dirs:
  375. sys.stderr.write('\n')
  376. sys.stderr.write('Files without SPDX:\n')
  377. for f in sorted(parser.spdx_dirs.keys()):
  378. di = parser.spdx_dirs[f]
  379. for f in sorted(di.files):
  380. sys.stderr.write(' %s\n' %f)
  381. sys.exit(0)
  382. except Exception as ex:
  383. sys.stderr.write('FAIL: %s\n' %ex)
  384. sys.stderr.write('%s\n' %traceback.format_exc())
  385. sys.exit(1)