| 8 | |
| 9 | |
| 10 | class Copyright: |
| 11 | # Canonical license body, shared with every generator — see scripts/license_header.txt. |
| 12 | NOTICE = (SCRIPT_DIR / "license_header.txt").read_text(encoding="utf-8").rstrip("\n") |
| 13 | |
| 14 | def __init__(self, comment_characters="//", prefix=None): |
| 15 | self._comment_characters = comment_characters |
| 16 | self._prefix = prefix or [] |
| 17 | |
| 18 | def update(self, files): |
| 19 | for file in files: |
| 20 | with open(file, encoding="utf-8-sig") as f: |
| 21 | lines = f.readlines() |
| 22 | |
| 23 | # An interpreter only honours `#!` on the first line, so the notice goes after it. |
| 24 | shebang = lines[:1] if lines and lines[0].startswith("#!") else [] |
| 25 | lines = lines[len(shebang) :] |
| 26 | |
| 27 | index = -1 |
| 28 | for i, line in enumerate(lines): |
| 29 | if line.startswith(self._comment_characters) or self.valid_copyright_notice_line(line, index, file): |
| 30 | index += 1 |
| 31 | else: |
| 32 | break |
| 33 | |
| 34 | if index == -1: |
| 35 | self.write_update_notice(file, lines, shebang) |
| 36 | else: |
| 37 | current = "".join(lines[: index + 1]) |
| 38 | if current != self.copyright_notice(file): |
| 39 | self.write_update_notice(file, lines[index + 1 :], shebang) |
| 40 | |
| 41 | def valid_copyright_notice_line(self, line, index, file): |
| 42 | return index + 1 < len(self.copyright_notice_lines(file)) and line.startswith( |
| 43 | self.copyright_notice_lines(file)[index + 1] |
| 44 | ) |
| 45 | |
| 46 | def copyright_notice(self, file): |
| 47 | return "".join(self.copyright_notice_lines(file)) |
| 48 | |
| 49 | def copyright_notice_lines(self, file): |
| 50 | return self.dotnet(file) if file.endswith("cs") else self._prefix + self.commented_notice_lines |
| 51 | |
| 52 | def dotnet(self, file): |
| 53 | file_name = os.path.basename(file) |
| 54 | first = f'{self._comment_characters} <copyright file="{file_name}" company="Selenium Committers">\n' |
| 55 | last = f"{self._comment_characters} </copyright>" |
| 56 | return [first] + self.commented_notice_lines + [last] |
| 57 | |
| 58 | @property |
| 59 | def commented_notice_lines(self): |
| 60 | return [f"{self._comment_characters} {line}".rstrip() + "\n" for line in self.NOTICE.split("\n")] |
| 61 | |
| 62 | def write_update_notice(self, file, lines, shebang=()): |
| 63 | # Build new content |
| 64 | new_content = "".join(shebang) + self.copyright_notice(file) + "\n" |
| 65 | if lines and lines[0] != "\n": |
| 66 | new_content += "\n" |
| 67 | new_content += "".join(line.rstrip() + "\n" for line in lines) |