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