copyright_checker.py 4.39 KB
Newer Older
Przemek Tredak's avatar
Przemek Tredak committed
1
2
3
#!/usr/bin/env python
# coding: utf-8

4
# Copyright (c) 2022-2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Przemek Tredak's avatar
Przemek Tredak committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#
# See LICENSE for license information.


import os
import sys
import json
import datetime

if len(sys.argv) < 2:
    print("Usage: python copyright_checker.py <path>")

path = sys.argv[1]

config_path = os.path.dirname(os.path.realpath(__file__)) + "/config.json"

21

Przemek Tredak's avatar
Przemek Tredak committed
22
class bcolors:
23
24
25
26
27
    OKGREEN = "\033[92m"
    WARNING = "\033[93m"
    FAIL = "\033[91m"
    ENDC = "\033[0m"

Przemek Tredak's avatar
Przemek Tredak committed
28
29
30
31

def print_ok(msg):
    print(f"{bcolors.OKGREEN}{msg}{bcolors.ENDC}")

32

Przemek Tredak's avatar
Przemek Tredak committed
33
34
35
def print_fail(msg):
    print(f"{bcolors.FAIL}{msg}{bcolors.ENDC}")

36

Przemek Tredak's avatar
Przemek Tredak committed
37
38
39
def print_warn(msg):
    print(f"{bcolors.WARNING}{msg}{bcolors.ENDC}")

40

Przemek Tredak's avatar
Przemek Tredak committed
41
42
43
44
45
46
47
48
with open(config_path, "r") as f:
    c = json.load(f)
    current_year = datetime.date.today().year
    if c["initial_year"] == current_year:
        year_string = str(current_year)
    else:
        year_string = str(c["initial_year"]) + "-" + str(current_year)
    copyright_string = c["copyright"].replace("<YEAR>", year_string)
49
    license = c["license"].split("\n")
Przemek Tredak's avatar
Przemek Tredak committed
50
51
52
53
54
55
56
    excludes = c["exclude"]
    root_path = os.path.abspath(path)
    copyright_only = c["copyright_only"]
    exclude_copyright = c["exclude_copyright"]

has_gitignore = os.path.exists(root_path + "/.gitignore")

57

Przemek Tredak's avatar
Przemek Tredak committed
58
59
def strip_star_slash(s):
    ret = s
60
    if ret.startswith("*"):
Przemek Tredak's avatar
Przemek Tredak committed
61
        ret = ret[1:]
62
    if ret.endswith("/"):
Przemek Tredak's avatar
Przemek Tredak committed
63
64
65
        ret = ret[:-1]
    return ret

66

Przemek Tredak's avatar
Przemek Tredak committed
67
68
69
70
71
if has_gitignore:
    with open(root_path + "/.gitignore", "r") as f:
        for line in f.readlines():
            excludes.append(strip_star_slash(line.strip()))

72

Przemek Tredak's avatar
Przemek Tredak committed
73
def get_file_type(path):
74
75
76
77
78
79
80
81
82
    ext = {
        "c": ["c", "cpp", "cu", "h", "cuh"],
        "py": ["py"],
        "rst": ["rst"],
        "txt": ["txt"],
        "cfg": ["cfg"],
        "sh": ["sh"],
        "md": ["md"],
    }
Przemek Tredak's avatar
Przemek Tredak committed
83
84
85
86
87
88
    tmp = path.split(".")
    for filetype, ext_list in ext.items():
        if tmp[-1] in ext_list:
            return filetype
    return "unknown"

89

Przemek Tredak's avatar
Przemek Tredak committed
90
91
success = True

92

Przemek Tredak's avatar
Przemek Tredak committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def check_file(path):
    global success
    N = 10
    ftype = get_file_type(path)
    if ftype == "unknown":
        print_warn("Unknown filetype")
        return
    check_copyright = True
    for e in exclude_copyright:
        if path.endswith(e):
            check_copyright = False
    with open(path, "r") as f:
        copyright_found = False
        license_found = True
        try:
            if check_copyright:
                for _ in range(N):
                    line = f.readline()
                    if line.find(copyright_string) != -1:
                        copyright_found = True
                        break
            if not copyright_only:
                first_license_line = True
                for l in license:
                    if first_license_line:
                        # may skip some lines
                        first_license_line = False
                        for _ in range(N):
                            line = f.readline()
                            if line.find(l) != -1:
                                break
                    else:
                        line = f.readline()
                    if line.find(l) == -1:
                        license_found = False
                        break
        except:
            pass
        finally:
            if not copyright_found:
                print_fail("No copyright found!")
                success = False
            if not license_found:
                print_fail("No license found!")
                success = False
            if copyright_found and license_found:
                print_ok("OK")

141

Przemek Tredak's avatar
Przemek Tredak committed
142
143
for root, dirs, files in os.walk(root_path):
    print(f"Entering {root}")
144
    hidden = [d for d in dirs if d.startswith(".")] + [f for f in files if f.startswith(".")]
Przemek Tredak's avatar
Przemek Tredak committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    all_excludes = excludes + hidden
    to_remove = []
    for d in dirs:
        d_path = root + "/" + d
        for e in all_excludes:
            if d_path.endswith(e):
                to_remove.append(d)
    for f in files:
        f_path = root + "/" + f
        for e in all_excludes:
            if f_path.endswith(e):
                to_remove.append(f)
    for d in to_remove:
        if d in dirs:
            dirs.remove(d)
        if d in files:
            files.remove(d)
    for filename in files:
        print(f"Checking {filename}")
        check_file(os.path.abspath(root + "/" + filename))

if not success:
    raise Exception("Some copyrights/licenses are missing!")