Browse Source

Require 50% header-less similarity for a rename from CE in the license check

pull/16341/head
Viacheslav Klimov 2 months ago
parent
commit
ec61ef00a8
Failed to extract signature
  1. 5
      tools/src/main/python/license-headers/README.md
  2. 64
      tools/src/main/python/license-headers/check_license_headers.py
  3. 28
      tools/src/main/python/license-headers/test_check_license_headers.py

5
tools/src/main/python/license-headers/README.md

@ -28,7 +28,10 @@ A file whose path does not exist in CE but that a commit after the CE commits
renamed from a CE path is `ce-modified`. Renames come from Git's rename renamed from a CE path is `ce-modified`. Renames come from Git's rename
detection in non-merge commits other than the relicensing commit. A chain of detection in non-merge commits other than the relicensing commit. A chain of
renames stops where its path was added or deleted, so a file created at a path renames stops where its path was added or deleted, so a file created at a path
that a CE file was once renamed to does not inherit that CE file. that a CE file was once renamed to does not inherit that CE file. Git scores a
rename with the header included, so the rename counts only when the content
without the header is at least 50% similar to the CE file; a weaker rename needs
a decision.
Any other file whose path does not exist in CE is `busl`, except when it needs a Any other file whose path does not exist in CE is `busl`, except when it needs a
decision: its content is at least 50% similar to a CE file, or CE history once decision: its content is at least 50% similar to a CE file, or CE history once

64
tools/src/main/python/license-headers/check_license_headers.py

@ -64,6 +64,7 @@ BLOCK_CLOSERS = {b"*/", b"-->"} | set(LINE_COMMENT_TOKENS)
RESTAMP_LISTING = 40 RESTAMP_LISTING = 40
REPEATED_HEADERS = 3 REPEATED_HEADERS = 3
HEADER_WINDOW = 4096 HEADER_WINDOW = 4096
SIMILARITY = 50
XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space" XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space"
@ -722,16 +723,14 @@ def normalized_copies(mycila, source_refs, names, nonempty):
destinations = {("head", name) for name in names} & nonempty destinations = {("head", name) for name in names} & nonempty
if not sources or not destinations: if not sources or not destinations:
return {} return {}
git(mycila.root, "init", "--quiet") index_repository(mycila)
git(mycila.root, "config", "core.autocrlf", "false")
git(mycila.root, "config", "core.attributesFile", "/dev/null")
before = stage(mycila, sources) before = stage(mycila, sources)
after = stage(mycila, destinations) after = stage(mycila, destinations)
raw = git(mycila.root, "diff-tree", "--no-commit-id", "-r", "--raw", "--no-abbrev", "-z", raw = git(mycila.root, "diff-tree", "--no-commit-id", "-r", "--raw", "--no-abbrev", "-z",
"-C50%", "--find-copies-harder", "-l0", before, after) f"-C{SIMILARITY}%", "--find-copies-harder", "-l0", before, after)
keys = {path: key for key, path in mycila.paths.items()} keys = {path: key for key, path in mycila.paths.items()}
copies = defaultdict(list) copies = defaultdict(list)
for source, destination, similarity in parse_copies(raw): for source, destination, similarity in parse_pairs(raw, "C"):
source_key, destination_key = keys[source], keys[destination] source_key, destination_key = keys[source], keys[destination]
if source_key not in sources or destination_key not in destinations: if source_key not in sources or destination_key not in destinations:
raise Failure("Normalized copy escaped the selected CE and HEAD inputs") raise Failure("Normalized copy escaped the selected CE and HEAD inputs")
@ -740,6 +739,27 @@ def normalized_copies(mycila, source_refs, names, nonempty):
return dict(copies) return dict(copies)
def normalized_similarity(mycila, source, destination):
before, after = mycila.contents[source], mycila.contents[destination]
if comparison_hash(before) == comparison_hash(after):
return 100
if not before.strip() or not after.strip():
return 0
index_repository(mycila)
trees = []
for key in (source, destination):
git(mycila.root, "read-tree", "--empty")
trees.append(stage(mycila, [key]))
raw = git(mycila.root, "diff-tree", "--no-commit-id", "-r", "--raw", "--no-abbrev", "-z", "-M1%", "-l0", *trees)
return max((similarity for _, _, similarity in parse_pairs(raw, "R")), default=0)
def index_repository(mycila):
git(mycila.root, "init", "--quiet")
git(mycila.root, "config", "core.autocrlf", "false")
git(mycila.root, "config", "core.attributesFile", "/dev/null")
def stage(mycila, keys): def stage(mycila, keys):
for key in keys: for key in keys:
mycila.write(key, mycila.contents[key].replace(b"\r\n", b"\n")) mycila.write(key, mycila.contents[key].replace(b"\r\n", b"\n"))
@ -749,13 +769,13 @@ def stage(mycila, keys):
return git(mycila.root, "write-tree").decode().strip() return git(mycila.root, "write-tree").decode().strip()
def parse_copies(raw): def parse_pairs(raw, kind):
tokens = iter(raw.split(b"\0")) tokens = iter(raw.split(b"\0"))
for token in tokens: for token in tokens:
token = token.lstrip(b"\n") token = token.lstrip(b"\n")
if token: if token:
_, status, paths = raw_change(token, tokens) _, status, paths = raw_change(token, tokens)
if status[0] == "C": if status[0] == kind:
yield paths[0], paths[1], int(status[1:]) yield paths[0], paths[1], int(status[1:])
@ -800,8 +820,13 @@ def infer(evidence):
else "same path in CE, content identical to a clean merge of its CE versions") else "same path in CE, content identical to a clean merge of its CE versions")
return verdict(evidence.current, "apache", reason) | versions | {"identicalTo": evidence.identical} return verdict(evidence.current, "apache", reason) | versions | {"identicalTo": evidence.identical}
if evidence.renamed_from: if evidence.renamed_from:
return (verdict(evidence.current, "ce-modified", f"renamed from CE {evidence.renamed_from[0]['path']}") renames = sorted(evidence.renamed_from, key=lambda version: -version["similarity"])
| {"renamedFrom": list(evidence.renamed_from)}) if renames[0]["similarity"] >= SIMILARITY:
return (verdict(evidence.current, "ce-modified", f"renamed from CE {renames[0]['path']}")
| {"renamedFrom": renames})
return unresolved(f"renamed from CE {renames[0]['path']}, but less than {SIMILARITY}% similar to it "
"without the header", None, renameCandidates=renames,
copyCandidates=list(evidence.copies))
if evidence.module_descriptor(): if evidence.module_descriptor():
return verdict(evidence.current, NON_CE, "build descriptor of a module that does not exist in CE") return verdict(evidence.current, NON_CE, "build descriptor of a module that does not exist in CE")
if evidence.copies: if evidence.copies:
@ -882,13 +907,15 @@ class Comparison:
normalized: dict normalized: dict
copies: dict copies: dict
merges: dict merges: dict
rename_similarities: dict
ce_directories: frozenset ce_directories: frozenset
def classify(self, name, curation): def classify(self, name, curation):
key = ("head", name) key = ("head", name)
versions = self.lineage.versions(name) versions = self.lineage.versions(name)
source = self.lineage.renames.get(name) source = None if versions else self.lineage.renames.get(name)
renamed_from = tuple({"path": source, "ref": base, "blob": oid} renamed_from = tuple({"path": source, "ref": base, "blob": oid,
"similarity": self.rename_similarities[(name, oid)]}
for base, oid in self.lineage.versions(source)) if source else () for base, oid in self.lineage.versions(source)) if source else ()
identical = next(({"path": name, "ref": base, "blob": oid} for base, oid in versions identical = next(({"path": name, "ref": base, "blob": oid} for base, oid in versions
if self.normalized[(name, oid)] == self.normalized[key]), self.merges.get(name)) if self.normalized[(name, oid)] == self.normalized[key]), self.merges.get(name))
@ -909,12 +936,16 @@ class Comparison:
def compare(repo, plugin, lineage, contents): def compare(repo, plugin, lineage, contents):
names = list(contents) names = list(contents)
new_paths = {name for name in names if not lineage.versions(name) and name not in lineage.renames} new_paths = {name for name in names if not lineage.versions(name)}
renames = {name: lineage.renames[name] for name in new_paths if name in lineage.renames}
sources = {} sources = {}
for base, files in lineage.trees.items(): for base, files in lineage.trees.items():
for name in names: for name in names:
if name in files: if name in files:
sources.setdefault((name, files[name]), base) sources.setdefault((name, files[name]), base)
for source in renames.values():
if source in files:
sources.setdefault((source, files[source]), base)
for key in comparable_ce_files(files, new_paths).items(): for key in comparable_ce_files(files, new_paths).items():
sources.setdefault(key, base) sources.setdefault(key, base)
bytes_by_id = blobs(repo, [oid for _, oid in sources]) bytes_by_id = blobs(repo, [oid for _, oid in sources])
@ -931,6 +962,8 @@ def compare(repo, plugin, lineage, contents):
normalized = mycila.strip_headers() normalized = mycila.strip_headers()
headers = mycila.header_states(recognized) headers = mycila.header_states(recognized)
copies = normalized_copies(mycila, sources, new_paths, mycila.nonempty()) copies = normalized_copies(mycila, sources, new_paths, mycila.nonempty())
rename_similarities = {(name, oid): normalized_similarity(mycila, (source, oid), ("head", name))
for name, source in renames.items() for _, oid in lineage.versions(source)}
merges = clean_merges(repo, plugin, lineage, names, normalized) merges = clean_merges(repo, plugin, lineage, names, normalized)
console.end(f"done ({len(normalized)} file versions)") console.end(f"done ({len(normalized)} file versions)")
return Comparison( return Comparison(
@ -940,6 +973,7 @@ def compare(repo, plugin, lineage, contents):
normalized=normalized, normalized=normalized,
copies=copies, copies=copies,
merges=merges, merges=merges,
rename_similarities=rename_similarities,
ce_directories=frozenset(str(parent) for files in lineage.trees.values() ce_directories=frozenset(str(parent) for files in lineage.trees.values()
for path in files for parent in PurePosixPath(path).parents), for path in files for parent in PurePosixPath(path).parents),
) )
@ -1018,8 +1052,10 @@ def describe_mismatch(row):
def describe_unresolved(row, ref_names): def describe_unresolved(row, ref_names):
hint = f" (hint: {row['suggestedHeader']})" if row.get("suggestedHeader") else "" hint = f" (hint: {row['suggestedHeader']})" if row.get("suggestedHeader") else ""
details = [f"has {header_name(row['currentHeader'])}, no expected header yet{hint}"] details = [f"has {header_name(row['currentHeader'])}, no expected header yet{hint}"]
evidence = [(f"similar CE file ({candidate['similarity']}%)", candidate) evidence = [(f"renamed from CE file ({candidate['similarity']}%)", candidate)
for candidate in row.get("copyCandidates", [])] for candidate in row.get("renameCandidates", [])]
evidence += [(f"similar CE file ({candidate['similarity']}%)", candidate)
for candidate in row.get("copyCandidates", [])]
if "historicalCandidate" in row: if "historicalCandidate" in row:
evidence.append(("CE history", row["historicalCandidate"])) evidence.append(("CE history", row["historicalCandidate"]))
if not evidence: if not evidence:

28
tools/src/main/python/license-headers/test_check_license_headers.py

@ -101,6 +101,16 @@ class DecisionTests(unittest.TestCase):
self.assertEqual(("unresolved", "CE history had this path"), (row["status"], row["reason"])) self.assertEqual(("unresolved", "CE history had this path"), (row["status"], row["reason"]))
self.assertEqual(deleted, row["historicalCandidate"]) self.assertEqual(deleted, row["historicalCandidate"])
def test_rename_from_ce_needs_header_less_similarity(self):
rename = {"path": "source.java", "ref": "a" * 40, "blob": "c" * 40, "similarity": p.SIMILARITY}
row = self.new(current="ce-modified", renamed_from=(rename,))
self.assertEqual(("match", "ce-modified", "renamed from CE source.java"),
(row["status"], row["expectedHeader"], row["reason"]))
weak = rename | {"similarity": p.SIMILARITY - 1}
row = self.new(current="ce-modified", renamed_from=(weak,), copies=(self.COPY,))
self.assertEqual(("unresolved", None, None), (row["status"], row["expectedHeader"], row["suggestedHeader"]))
self.assertEqual(([weak], [self.COPY]), (row["renameCandidates"], row["copyCandidates"]))
def test_descriptor_of_a_module_absent_in_ce_is_non_ce_despite_similar_ce_descriptors(self): def test_descriptor_of_a_module_absent_in_ce_is_non_ce_despite_similar_ce_descriptors(self):
copy = self.COPY | {"path": "transport/mqtt/pom.xml"} copy = self.COPY | {"path": "transport/mqtt/pom.xml"}
descriptor = dict(path="integration/mqtt/pom.xml", copies=(copy,), directory_in_ce=False) descriptor = dict(path="integration/mqtt/pom.xml", copies=(copy,), directory_in_ce=False)
@ -780,6 +790,24 @@ class CheckCommandTests(unittest.TestCase):
(row["status"], row["expectedHeader"], row["reason"])) (row["status"], row["expectedHeader"], row["reason"]))
self.assertEqual({"Source.java"}, {version["path"] for version in row["renamedFrom"]}) self.assertEqual({"Source.java"}, {version["path"] for version in row["renamedFrom"]})
@requires_merge_file_object_id
def test_rename_of_rewritten_ce_file_needs_a_decision(self):
rewritten = "".join(f"TB implementation {index}\n" for index in range(20))
self.git.write("Source.java", fixture(p.NON_CE) + rewritten)
self.git.commit("rewrite CE file")
self.git("mv", "Source.java", "Moved.java")
self.git.commit("rename rewritten file")
scope = [name if name != "Source.java" else "Moved.java" for name in self.scope]
for args in ((), ("--fix",)):
code, report, output = self.check(*args, scope=scope)
row = self.rows(report)["Moved.java"]
self.assertEqual((1, "unresolved", p.NON_CE), (code, row["status"], row["currentHeader"]))
self.assertEqual({"Source.java"}, {candidate["path"] for candidate in row["renameCandidates"]})
self.assertLess(max(candidate["similarity"] for candidate in row["renameCandidates"]), p.SIMILARITY)
self.assertEqual([], report["restamped"])
self.assertIn(" renamed from CE file (", output)
self.assertEqual(fixture(p.NON_CE) + rewritten, (self.repo / "Moved.java").read_text())
@requires_merge_file_object_id @requires_merge_file_object_id
def test_fix_removes_redundant_and_orphaned_curations(self): def test_fix_removes_redundant_and_orphaned_curations(self):
self.git.write("Copy.java", fixture(p.NON_CE) + self.body) self.git.write("Copy.java", fixture(p.NON_CE) + self.body)

Loading…
Cancel
Save