The Gaudi Framework  master (181af51f)
Loading...
Searching...
No Matches
update_copyright_year.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2
12import datetime
13import os
14import re
15from argparse import ArgumentParser
16
17COPYRIGHT_SIGNATURE = re.compile(r"\bcopyright\b", re.I)
18
19
20def update_year(line: str, year: int) -> str:
21 """
22 Replace the end year of a range with the given year.
23 """
24 match = re.search(r"(\d{4}-)?(\d{4})", line)
25 if match:
26 range_start, range_end = match.groups()
27 if range_start:
28 line = re.sub(r"\d{4}-?\d{4}", f"{range_start}{year:04d}", line)
29 elif int(range_end) < year:
30 line = re.sub(r"\d{4}", f"{range_end}-{year:04d}", line)
31 # if we have a line that is part of a table with borders, so we
32 # try to remove 5 spaces to compensate the added start of range
33 line = re.sub(r"\s{0,5}( [*#])$", r"\1", line)
34
35 return line
36
37
38def main():
39 parser = ArgumentParser(
40 "Simple script to update the copyright year in the files passed on the command line"
41 )
42 parser.add_argument(
43 "--check-only",
44 action="store_true",
45 default=os.environ.get("CHECK_ONLY"),
46 help="Check for presence of copyright (do not update years)",
47 )
48 parser.add_argument(
49 "--no-check-only",
50 dest="check_only",
51 action="store_false",
52 help="Check for presence of copyright (do not update years)",
53 )
54 parser.add_argument(
55 "-Y",
56 "--year",
57 type=int,
58 default=datetime.datetime.now().year,
59 help="Year to use [default: current year]",
60 )
61 parser.add_argument("files", nargs="+", help="Files to update")
62
63 args = parser.parse_args()
64
65 exp = re.compile(r"[Cc]opyright.*(\d{4}-)?\d{4} CERN")
66
67 missing_copyright = []
68 for file in args.files:
69 with open(file, "r") as f:
70 content = f.readlines()
71
72 if not any(COPYRIGHT_SIGNATURE.search(line) for line in content):
73 missing_copyright.append(file)
74
75 elif not args.check_only:
76 # update the copyright year
77 new_content = [
78 update_year(line, args.year) if exp.search(line) else line
79 for line in content
80 ]
81
82 if new_content != content:
83 with open(file, "w") as f:
84 f.writelines(new_content)
85
86 if missing_copyright:
87 print(
88 "The following files are missing a copyright line:\n - "
89 + "\n - ".join(missing_copyright)
90 )
91 exit(1)
92
93
94if __name__ == "__main__":
95 main()