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