in automation/headerfy.py [0:0]
def update_header(root: Union[str, Path], filename: str) -> None:
"""Updates the Copyright header of the provided file.
Args:
root: Absolute path to the folder where `file` can be found.
filename: File name to be updated.
Returns:
None
Raises:
PermissionError, FileNotFoundError, FileExistsError: If the opening of the
file fails.
RuntimeError: The file extension isn't supported.
"""
path_to_file = os.path.join(root, filename)
pattern = None
if (
any((filename.endswith(ext) for ext in TARGET_SRC_PY_EXTS))
or filename in SRC_BUT_EXTENSIONLESS
):
pattern = PATTERN_HEADER_PY
elif any((filename.endswith(ext) for ext in TARGET_SRC_C_EXTS)):
pattern = PATTERN_HEADER_C
elif any((filename.endswith(ext) for ext in TARGET_SRC_PLAIN_EXTS)):
pattern = PATTERN_HEADER_PLAIN
else:
raise RuntimeError(f"Couldn't resolve extension for {filename}")
sol = None
if pattern == PATTERN_HEADER_PY:
sol = "#"
elif pattern == PATTERN_HEADER_C:
sol = " *"
elif pattern == PATTERN_HEADER_PLAIN:
sol = ""
with open(path_to_file, mode="r", encoding="utf8") as fp:
text_old = fp.read()
match_header = re.search(pattern, text_old)
# no copyright header
if match_header is None:
return
two_years_snippet = re.search(PATTERN_YEARS, match_header.group())
creation_year = (
two_years_snippet.group().split(",")[0].replace("Copyright (c)", "").strip()
if two_years_snippet is not None
else ""
)
logger.info("%s (%s)", path_to_file, creation_year if creation_year else "NULL")
creation_year = f"{creation_year}, " if creation_year else f"{DEFAULT_FOUND_YEAR}, "
text_new = re.sub(
pattern,
COPYRIGHT_HEADER.format(
sol=sol, creation_year=creation_year, current_year=CURRENT_YEAR
),
text_old,
)
with open(path_to_file, mode="w", encoding="utf8") as fp:
fp.write(text_new)