[docs]defmerge_copyright_lines(copyright_lines:set[str])->set[str]:"""Parse all copyright lines and merge identical statements making years into a range. If a same statement uses multiple prefixes, use only the most frequent one. """# pylint: disable=too-many-locals# TODO: Rewrite this function. It's a bit of a mess.copyright_in=[]forlineincopyright_lines:forpatternin_COPYRIGHT_PATTERNS:match=pattern.search(line)ifmatchisnotNone:copyright_in.append({"statement":match.groupdict()["statement"],"year":_parse_copyright_year(match.groupdict()["year"]),"prefix":match.groupdict()["prefix"],})breakcopyright_out=set()forline_infoincopyright_in:statement=str(line_info["statement"])copyright_list=[itemforitemincopyright_inifitem["statement"]==statement]# Get the most common prefix.most_common=str(Counter([item["prefix"]foritemincopyright_list]).most_common(1)[0][0])prefix="spdx"forkey,valuein_COPYRIGHT_PREFIXES.items():ifmost_common==value:prefix=keybreak# get year range if anyyears:list[str]=[]forcopyincopyright_list:years+=copy["year"]year:Optional[str]=Noneifyears:ifmin(years)==max(years):year=min(years)else:year=f"{min(years)} - {max(years)}"copyright_out.add(make_copyright_line(statement,year,prefix))returncopyright_out
[docs]defmake_copyright_line(statement:str,year:Optional[str]=None,copyright_prefix:str="spdx")->str:"""Given a statement, prefix it with ``SPDX-FileCopyrightText:`` if it is not already prefixed with some manner of copyright tag. """if"\n"instatement:raiseRuntimeError(f"Unexpected newline in '{statement}'")prefix=_COPYRIGHT_PREFIXES.get(copyright_prefix)ifprefixisNone:# TODO: Maybe translate this. Also maybe reduce DRY here.raiseRuntimeError("Unexpected copyright prefix: Need 'spdx', 'spdx-c', ""'spdx-symbol', 'string', 'string-c', ""'string-symbol', or 'symbol'")forpatternin_COPYRIGHT_PATTERNS:match=pattern.search(statement)ifmatchisnotNone:returnstatementifyearisnotNone:returnf"{prefix}{year}{statement}"returnf"{prefix}{statement}"
def_parse_copyright_year(year:Optional[str])->list[str]:"""Parse copyright years and return list."""ret:list[str]=[]ifnotyear:returnretifre.match(r"\d{4}$",year):ret=[year]elifre.match(r"\d{4} ?- ?\d{4}$",year):ret=[year[:4],year[-4:]]returnret