aboutsummaryrefslogtreecommitdiff
path: root/util/license.py
blob: 0bbc6be3a2f4fc4b7b0544c715039abb60b3d98a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python3

import argparse
import datetime
import sys

def readLicense(licenseFile):
    with open(licenseFile) as rawlicense:
        licensetext = rawlicense.read()
    
    # fill in the year
    licensetext = licensetext.replace('$CURRENTYEAR$', str(datetime.datetime.now().year))
    
    return licensetext

def hasLicense(sourceFile):
    with open(sourceFile) as source:
        if source.readline().startswith('/** LICENSE **'):
            return True
        else:
            return False

def addLicense(sourceFile, licenseText):
    with open(sourceFile, 'r') as source:
        origData = source.read()
    with open(sourceFile, 'w') as source:
        source.write(licenseText + origData)

def lint(license, src, dryRun, verbose=False):
    if verbose is True:
        print("license={0}".format(license))
        print("source={0}".format(src))

    # read license file
    licensetext = readLicense(license)
    if verbose is True:
        print("-- license text --")
        print(licensetext)
        print("-- license text --")
    
    if len(src) is 0:
        print("No files to process.")
        return 0
    
    # open source file and check for license
    numFaults = 0
    for filename in src:
        if hasLicense(filename) is True:
            if verbose:
                print("OK {0}".format(filename))
        else:
            if dryRun is True:
                if verbose:
                    print("fail {0}".format(filename))
            else:
                addLicense(filename, licensetext)
                print("fix {0}".format(filename))
            
            numFaults += 1
    
    if numFaults is not 0:
        print("License check: number of faults: {0}".format(numFaults))
    
    return numFaults

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='check source files for license')
    parser.add_argument('-l', '--license', required=True, help="use this file as license header template")
    parser.add_argument('-v', '--verbose', action='store_true', help="print additional information")
    parser.add_argument('-c', '--dry-run', action='store_true', help="don't modify any files, only check for licenses")
    parser.add_argument('src', nargs='*', help="list of files to check")
    args = parser.parse_args()

    sys.exit(lint(args.license, args.src, args.dry_run, args.verbose))