Browse Source

Sped up the license header check: changed files in pull requests, parallel subprocesses, CE normalization cache

- Pull requests check the files they change (--since), with a full check when
  the CE bases, the Mycila configuration or the check itself changed.
- One history walk for CE deletions instead of one per CE base.
- Distinct three-way merges run once and in parallel; Mycila invocations no
  longer share pom.xml/report.json and run in parallel.
- The copy search skips CE files that Git cannot match by size.
- Header-free CE contents are cached in target/license-headers-cache; pushes
  save the cache, pull requests only restore it.
pull/16632/head
Vladyslav Prykhodko 3 weeks ago
parent
commit
0cd8a80210
  1. 29
      .github/workflows/check-license-headers.yml
  2. 6
      check-license-headers.sh
  3. 33
      tools/src/main/python/license-headers/README.md
  4. 442
      tools/src/main/python/license-headers/check_license_headers.py
  5. 440
      tools/src/main/python/license-headers/test_check_license_headers.py

29
.github/workflows/check-license-headers.yml

@ -46,10 +46,37 @@ jobs:
java-version: 21
cache: maven
# Header-free CE contents from earlier runs. A pull request reads the cache of its base branch, then of master;
# only pushes and manual runs write one, so a pull request never feeds the cache that other runs trust.
- name: Restore normalized CE contents
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: target/license-headers-cache
key: license-headers-ce-v1-${{ github.ref_name }}-${{ github.run_id }}
restore-keys: |
license-headers-ce-v1-${{ github.ref_name }}-
license-headers-ce-v1-
- name: Check license headers
env:
# Pull requests check only the files they change; pushes and manual runs check every file.
SINCE: ${{ github.event_name == 'pull_request' && format('origin/{0}', github.base_ref) || '' }}
run: |
mkdir -p target/license-provenance
./check-license-headers.sh 2>&1 | tee target/license-provenance/console.log
# The runner does nothing else: use every CPU, not all but one as on a workstation.
LICENSE_HEADERS_JOBS="$(nproc)"
export LICENSE_HEADERS_JOBS
./check-license-headers.sh ${SINCE:+--since "$SINCE"} 2>&1 | tee target/license-provenance/console.log
# Saved even when the check finds problems, but only when the run normalized something the cache lacked.
- name: Save normalized CE contents
if: >-
always() && github.event_name != 'pull_request'
&& hashFiles('target/license-headers-cache/.updated') != ''
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: target/license-headers-cache
key: license-headers-ce-v1-${{ github.ref_name }}-${{ github.run_id }}
- name: Add findings to the job summary
if: failure() && hashFiles('target/license-provenance/console.log') != ''

6
check-license-headers.sh

@ -8,9 +8,13 @@ set -euo pipefail
usage() {
echo "Checks SPDX license headers against CE provenance."
echo "usage: $0 [--fix] [--ce-ref <ref>] [--ce-remote <url>] [--output target/...]"
echo "usage: $0 [--fix] [--since <ref>] [--ce-ref <ref>] [--ce-remote <url>] [--output target/...] [--no-cache]"
echo " --fix restamp files whose expected header the check determined"
echo " and remove redundant or orphaned curations"
echo " --since check only files changed since the merge base of <ref> and HEAD,"
echo " uncommitted and untracked files included, e.g. --since origin/lts-4.4;"
echo " runs the full check when CE commits, Mycila settings or the check itself changed"
echo " --no-cache normalize every CE file again instead of reusing target/license-headers-cache"
echo " --ce-ref CE branch, tag or commit that this branch integrates, fetched on every run;"
echo " without it, CE is the history that does not contain the relicensing commit"
echo " --ce-remote CE repository to fetch --ce-ref from (default: https://github.com/thingsboard/thingsboard.git)"

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

@ -36,7 +36,38 @@ packaging define the new artifact.
./check-license-headers.sh
```
The check needs the full Git history of the clone.
The check needs the full Git history of the clone. It runs Git and Mycila
subprocesses in parallel on all CPUs but one; set `LICENSE_HEADERS_JOBS` to
another number, for example `1` for a sequential run.
## Cache
The check removes the header of every CE file it compares with Mycila. CE files
never change, so their header-free contents are kept in
`target/license-headers-cache` and reused by the next run. The cache is valid
while the Mycila version and configuration in the root `pom.xml`, the templates
and the check itself stay the same; anything else starts a new cache, and the
check normalizes again instead of using the old one. Pass `--no-cache` to
normalize every CE file again, or `--cache` to keep the cache elsewhere.
In GitHub Actions, pushes and manual runs save the cache and pull requests only
read it: a pull request takes the cache of its base branch, then of `master`.
## Check only changed files
```sh
./check-license-headers.sh --since origin/lts-4.4
```
Checks the files that differ between the merge base of the given ref and HEAD
and the working tree, untracked files included, and the files whose curation
changed. Pull requests run the check this way against their target branch;
pushes and manual runs check every file. Curations of files no longer in scope
are still reported for the whole repository.
The check falls back to every file when a change can move the verdict of an
unchanged file: new CE commits merged into the branch, a changed Mycila
configuration in the root `pom.xml`, or a change to the check itself.
## Fix automatically

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

@ -9,17 +9,21 @@ from __future__ import annotations
import argparse
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from copy import deepcopy
from dataclasses import dataclass
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import re
import sqlite3
import subprocess
import sys
import tempfile
import threading
import uuid
import xml.etree.ElementTree as ET
@ -45,6 +49,7 @@ RELICENSING_COMMIT = "31936b09d24871e421f212502a8342f9d8aabb20"
CE_REMOTE = "https://github.com/thingsboard/thingsboard.git"
CURATIONS = "tools/src/main/python/license-headers/curations.json"
README = "tools/src/main/python/license-headers/README.md"
CHECKER_PATHS = ("tools/src/main/python/license-headers/", "check-license-headers.sh")
CURATION_FIELDS = {"path", "contentHash", "header", "reason"}
CONTENT_HASH = re.compile(r"sha256:[0-9a-f]{64}")
UNRECOGNIZED = "unrecognized"
@ -65,6 +70,11 @@ RESTAMP_LISTING = 40
REPEATED_HEADERS = 3
HEADER_WINDOW = 4096
XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space"
JOBS_VARIABLE = "LICENSE_HEADERS_JOBS"
CACHE_DIRECTORY = "target/license-headers-cache"
CACHE_FORMAT = "1"
CACHE_UPDATED = ".updated"
CACHE_SIGNATURES_KEPT = 3
@dataclass(frozen=True)
@ -132,6 +142,26 @@ class Console:
console = Console()
def jobs():
"""Parallel subprocesses: LICENSE_HEADERS_JOBS when set, otherwise all CPUs but one to keep the machine responsive."""
configured = os.environ.get(JOBS_VARIABLE, "")
if configured:
if not configured.isdigit() or int(configured) < 1:
raise Failure(f"{JOBS_VARIABLE} must be a positive number, not {configured!r}")
return int(configured)
return max(1, (os.cpu_count() or 1) - 1)
def parallel(function, items):
"""Results of function for every item in item order; the first failure propagates."""
items = list(items)
workers = min(len(items), jobs())
if workers <= 1:
return [function(item) for item in items]
with ThreadPoolExecutor(max_workers=workers) as pool:
return list(pool.map(function, items))
def run(argv, cwd, *, data=None, ok=(0,)):
result = subprocess.run(argv, cwd=cwd, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode not in ok:
@ -238,9 +268,12 @@ class Change:
status: str
def history(repo, revision, *options):
def history(repo, revisions, *options):
"""First-parent changes of every revision in one walk: commits shared by several revisions appear once."""
if not revisions or any(revision.startswith("-") for revision in revisions):
raise Failure("history needs revisions that do not start with '-'")
raw = git(repo, "log", "--first-parent", "--diff-merges=first-parent", "--root", "--raw", "--no-abbrev",
"--no-renames", "-z", "--format=%x1e%H", *options, revision, "--")
"--no-renames", "-z", "--format=%x1e%H", *options, *revisions, "--")
return list(parse_history(raw))
@ -400,8 +433,8 @@ def validate_curation(entry):
return name
def xml_plain(path):
root = ET.parse(path).getroot()
def xml_plain(source):
root = ET.parse(source).getroot()
for element in root.iter():
element.tag = element.tag.rsplit("}", 1)[-1]
return root
@ -418,7 +451,15 @@ class Plugin:
def read_plugin(repo):
plugins = xml_plain(repo / "pom.xml").findall("./build/pluginManagement/plugins/plugin")
return parse_plugin(xml_plain(repo / "pom.xml"))
def plugin_signature(plugin):
return plugin.version, ET.tostring(plugin.configuration)
def parse_plugin(project):
plugins = project.findall("./build/pluginManagement/plugins/plugin")
plugin = next((p for p in plugins if p.findtext("artifactId") == "license-maven-plugin"), None)
if plugin is None:
raise Failure("Root pom.xml does not manage the Mycila license plugin")
@ -451,8 +492,8 @@ class Scope:
def discover_scope(repo, plugin):
states = defaultdict(set)
modules = []
for entry in SCOPE_POMS:
for report in scope_check(repo, plugin, entry):
for reports in parallel(lambda entry: scope_check(repo, plugin, entry), SCOPE_POMS):
for report in reports:
module = report.parent.parent
modules.append({"path": str(module.relative_to(repo)), "report": str(report.relative_to(repo))})
for name, result in read_scope_report(repo, module, report):
@ -516,7 +557,6 @@ class Mycila:
def __init__(self, repo, directory, plugin):
self.root = directory
self.plugin = plugin
self.report = directory / "report.json"
self.paths = {}
self.contents = {}
self.removed = {}
@ -527,9 +567,10 @@ class Mycila:
(directory / name).parent.mkdir(parents=True, exist_ok=True)
(directory / name).write_bytes(self.templates[header])
def add(self, key, name, content):
def add(self, key, name, content, slot=None):
group = "head" if key[0] == "head" else "ce"
path = self.root / "files" / group / str(len(self.paths)) / PurePosixPath(name).name
slot = len(self.paths) if slot is None else slot
path = self.root / "files" / group / str(slot) / PurePosixPath(name).name
path.parent.mkdir(parents=True)
path.write_bytes(content)
self.paths[key] = path.relative_to(self.root).as_posix()
@ -548,8 +589,9 @@ class Mycila:
def current_headers(self, keys):
keys = list(keys)
recognized = defaultdict(list)
for header in TEMPLATES:
for key, result in self.invoke("check", header, keys).items():
checks = parallel(lambda header: self.invoke("check", header, keys), TEMPLATES)
for header, results in zip(TEMPLATES, checks):
for key, result in results.items():
if result == "PRESENT":
recognized[key].append(header)
return {key: recognized[key][0] if len(recognized[key]) == 1 else UNRECOGNIZED for key in keys}
@ -631,43 +673,46 @@ class Mycila:
rejected[key] = "more than one header, review by hand"
accepted = [key for key in keys if key not in rejected]
with self.guarded(accepted):
for header in TEMPLATES:
group = [key for key in accepted if expected[key] == header]
if group:
self.invoke("format", header, group)
groups = {header: [key for key in accepted if expected[key] == header] for header in TEMPLATES}
parallel(lambda header: self.invoke("format", header, groups[header]), TEMPLATES)
return {key: self.contents[key] for key in accepted}, rejected
def invoke(self, goal, header, keys, *, styles=()):
keys = list(keys)
if not keys:
return {}
self.write_pom(header, keys, styles)
self.report.unlink(missing_ok=True)
invocation = uuid.uuid4().hex
pom, report = self.root / f"pom-{invocation}.xml", self.root / f"report-{invocation}.json"
self.write_pom(pom, report, header, keys, styles)
try:
maven(self.root, [self.plugin.coordinates + ":" + goal])
maven(self.root, ["-f", pom.name, self.plugin.coordinates + ":" + goal])
results = self.read_results(report)
except Failure as exc:
unknown = self.unknown_inputs(keys)
unknown = self.unknown_inputs(report, keys)
if unknown:
raise Failure(f"Mycila cannot normalize these inputs: {unknown[:20]}") from exc
raise
results = self.read_results()
finally:
pom.unlink(missing_ok=True)
report.unlink(missing_ok=True)
if set(results) != {self.paths[key] for key in keys} or "UNKNOWN" in results.values():
raise Failure("Mycila comparison scope was incomplete or unknown")
return {key: results[self.paths[key]] for key in keys}
def read_results(self):
if not self.report.exists():
@staticmethod
def read_results(report):
if not report.exists():
raise Failure("Mycila did not produce its comparison report")
return {item["path"]: item["result"] for item in json.loads(self.report.read_text())["files"]}
return {item["path"]: item["result"] for item in json.loads(report.read_text())["files"]}
def unknown_inputs(self, keys):
def unknown_inputs(self, report, keys):
try:
results = self.read_results()
results = self.read_results(report)
except Failure:
return []
return [str(key) for key in keys if results.get(self.paths[key]) == "UNKNOWN"]
def write_pom(self, header, keys, styles):
def write_pom(self, pom, report, header, keys, styles):
project = ET.Element("project", xmlns="http://maven.apache.org/POM/4.0.0")
append_elements(project, [("modelVersion", "4.0.0"), ("groupId", "license.provenance"),
("artifactId", "temporary-comparison"), ("version", "1")])
@ -677,7 +722,7 @@ class Mycila:
config = ET.SubElement(plugin, "configuration")
append_elements(config, [("encoding", "UTF-8"), ("strictCheck", "true"), ("quiet", "true"),
("failIfMissing", "false"), ("failIfUnknown", "true"),
("reportFormat", "json"), ("reportLocation", str(self.report))])
("reportFormat", "json"), ("reportLocation", str(report))])
config.append(self.mapping(styles))
license_set = ET.SubElement(ET.SubElement(config, "licenseSets"), "licenseSet")
append_elements(license_set, [("header", str(self.root / TEMPLATES[header])),
@ -688,7 +733,7 @@ class Mycila:
parent = ET.SubElement(license_set, "inlineHeaderStyles")
for style in styles:
append_elements(ET.SubElement(parent, "inlineHeaderStyle"), (("name", style.name),) + style.settings)
ET.ElementTree(project).write(self.root / "pom.xml", encoding="utf-8", xml_declaration=True)
ET.ElementTree(project).write(pom, encoding="utf-8", xml_declaration=True)
def mapping(self, styles):
mapping = self.plugin.configuration.find("mapping")
@ -822,9 +867,8 @@ class Lineage:
if git(repo, "rev-parse", "--is-shallow-repository").decode().strip() == "true":
raise Failure("this clone is shallow and the check needs full history. Run git fetch --unshallow.")
deleted = {}
for base in bases:
for change in history(repo, base, "--diff-filter=D"):
deleted.setdefault(change.path, {"path": change.path, "ref": change.commit + "^1", "blob": change.old})
for change in history(repo, list(bases), "--diff-filter=D"):
deleted.setdefault(change.path, {"path": change.path, "ref": change.commit + "^1", "blob": change.old})
return cls(head=head, bases=tuple(bases), trees={base: tree(repo, base) for base in bases}, deleted=deleted)
def versions(self, name):
@ -867,7 +911,116 @@ class Comparison:
))
def compare(repo, plugin, lineage, contents):
class NormalizationCache:
"""Header-free contents of CE inputs from earlier runs, keyed by content and file name (Mycila styles follow the
name). One SQLite file per normalization signature: a different Mycila setup, template or check misses the cache."""
def __init__(self, directory, signature):
self.directory = directory
self.lock = threading.Lock()
self.added = 0
self.hits = 0
directory.mkdir(parents=True, exist_ok=True)
(directory / CACHE_UPDATED).unlink(missing_ok=True)
self.path = directory / f"{signature}.sqlite"
try:
self.database = self.open()
except sqlite3.DatabaseError:
# A damaged cache only costs time: start it again instead of failing the check.
self.path.unlink()
self.database = self.open()
os.utime(self.path)
for stale in sorted(directory.glob("*.sqlite"), key=lambda path: path.stat().st_mtime)[:-CACHE_SIGNATURES_KEPT]:
stale.unlink()
def open(self):
database = sqlite3.connect(self.path, check_same_thread=False)
database.execute("CREATE TABLE IF NOT EXISTS normalized (input TEXT PRIMARY KEY, content BLOB NOT NULL)")
return database
@staticmethod
def input(name, raw):
return hashlib.sha256(raw).hexdigest() + "/" + PurePosixPath(name).name
def get(self, inputs):
found = {}
with self.lock:
for key, raw in inputs.items():
row = self.database.execute("SELECT content FROM normalized WHERE input = ?",
(self.input(key[0], raw),)).fetchone()
if row is not None:
found[key] = bytes(row[0])
self.hits += len(found)
return found
def put(self, entries):
with self.lock:
self.database.executemany("INSERT OR IGNORE INTO normalized VALUES (?, ?)",
[(self.input(key[0], raw), content) for key, raw, content in entries])
self.added += len(entries)
def close(self):
self.database.commit()
self.database.close()
if self.added:
(self.directory / CACHE_UPDATED).touch()
class NoCache:
added = hits = 0
def get(self, inputs):
return {}
def put(self, entries):
pass
def close(self):
pass
def cache_signature(repo, plugin):
digest = hashlib.sha256(CACHE_FORMAT.encode())
version, configuration = plugin_signature(plugin)
for part in (Path(__file__).read_bytes(), version.encode(), configuration,
*((repo / name).read_bytes() for name in TEMPLATES.values())):
digest.update(len(part).to_bytes(8, "big") + part)
return digest.hexdigest()[:32]
def normalize(repo, plugin, cache, inputs):
"""Header-free contents of CE inputs ({key: raw bytes}, key[0] the file name), from the cache when it has them."""
found = cache.get(inputs)
missing = {key: raw for key, raw in inputs.items() if key not in found}
if missing:
with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary:
mycila = Mycila(repo, Path(temporary), plugin)
for key, raw in missing.items():
mycila.add(key, key[0], raw)
mycila.strip_headers()
grown = [key[0] for key, raw in missing.items() if len(mycila.contents[key]) > len(raw)]
if grown:
raise Failure(f"Mycila grew these files while removing their headers: {grown[:20]}")
found |= {key: mycila.contents[key] for key in missing}
cache.put([(key, raw, found[key]) for key, raw in missing.items()])
return found
def staged_size(content):
return len(content.replace(b"\r\n", b"\n"))
def could_be_copy(size, destinations):
"""Git scores a pair 0 unless the smaller blob is at least half the larger (diffcore-rename estimate_similarity)."""
return any(2 * min(size, other) >= max(size, other) for other in destinations)
def could_shrink_to_copy(raw_size, destinations):
"""Normalizing never grows a file: below half the smallest destination it stays out of Git's reach."""
return 2 * raw_size >= min(destinations)
def compare(repo, plugin, lineage, contents, cache):
names = list(contents)
new_paths = {name for name in names if not lineage.versions(name)}
sources = {}
@ -877,22 +1030,32 @@ def compare(repo, plugin, lineage, contents):
sources.setdefault((name, files[name]), base)
for key in comparable_ce_files(files, new_paths).items():
sources.setdefault(key, base)
versions = {(name, oid) for name in names for _, oid in lineage.versions(name)}
# Every input keeps the slot it has among all inputs, so the copy search sees the same paths, and Git breaks
# ties between equally similar sources the same way, however many sources the size filter drops.
slots = {("head", name): index for index, name in enumerate(names)}
slots |= {key: len(names) + index for index, key in enumerate(sorted(sources))}
bytes_by_id = blobs(repo, [oid for _, oid in sources])
with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary:
mycila = Mycila(repo, Path(temporary), plugin)
for name, content in contents.items():
mycila.add(("head", name), name, content)
for path, oid in sorted(sources):
mycila.add((path, oid), path, bytes_by_id[oid])
mycila.add(("head", name), name, content, slots[("head", name)])
console.begin("Recognizing headers")
recognized = mycila.current_headers([("head", name) for name in names])
console.end()
console.begin("Comparing against CE")
normalized = mycila.strip_headers()
head_hashes, copy_sources = parallel(lambda job: job(), [
mycila.strip_headers,
lambda: normalize(repo, plugin, cache, {key: bytes_by_id[key[1]] for key in versions})])
headers = mycila.header_states(recognized)
copies = normalized_copies(mycila, sources, new_paths, mycila.nonempty())
merges = clean_merges(repo, plugin, lineage, names, normalized)
console.end(f"done ({len(normalized)} file versions)")
destinations = {name: mycila.contents[("head", name)] for name in sorted(new_paths)
if mycila.contents[("head", name)].strip()}
normalized = head_hashes | {key: comparison_hash(content) for key, content in copy_sources.items()}
copies, searched = copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id,
destinations, copy_sources, normalized)
merges = clean_merges(repo, plugin, cache, lineage, names, normalized)
console.end(f"done ({len(normalized)} file versions, {searched} of {len(sources) - len(versions)} "
f"other CE files searched for copies, {cache.hits} from the cache)")
return Comparison(
lineage=lineage,
contents=contents,
@ -905,31 +1068,57 @@ def compare(repo, plugin, lineage, contents):
)
def clean_merges(repo, plugin, lineage, names, normalized):
merged = {}
for index, left in enumerate(lineage.bases):
for right in lineage.bases[index + 1:]:
ancestors = git(repo, "merge-base", "--all", left, right).decode().split()
if len(ancestors) != 1:
def copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, destinations, copy_sources,
normalized):
"""CE files similar to the paths that CE does not have, normalized only when Git could match them by size."""
if not destinations:
return {}, 0
sizes = [staged_size(content) for content in destinations.values()]
others = sorted(key for key in sources if key not in versions
and could_shrink_to_copy(len(bytes_by_id[key[1]]), sizes))
found = normalize(repo, plugin, cache, {key: bytes_by_id[key[1]] for key in others})
normalized |= {key: comparison_hash(content) for key, content in found.items()}
with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary:
staging = Mycila(repo, Path(temporary), plugin)
for key, content in (found | copy_sources).items():
staging.add(key, key[0], content, slots[key])
for name, content in destinations.items():
staging.add(("head", name), name, content, slots[("head", name)])
reachable = {key: sources[key] for key in [*others, *copy_sources]
if could_be_copy(staged_size(staging.contents[key]), sizes)}
return normalized_copies(staging, reachable, set(destinations), staging.nonempty()), len(others)
def clean_merges(repo, plugin, cache, lineage, names, normalized):
pairs = [(left, right) for index, left in enumerate(lineage.bases) for right in lineage.bases[index + 1:]]
def ancestry(pair):
ancestors = git(repo, "merge-base", "--all", *pair).decode().split()
return (ancestors[0], tree(repo, ancestors[0])) if len(ancestors) == 1 else None
candidates = []
for (left, right), common in zip(pairs, parallel(ancestry, pairs)):
if common is None:
continue
ancestor, files = common
for name in names:
ours, theirs = lineage.trees[left].get(name), lineage.trees[right].get(name)
if ours is None or theirs is None or ours == theirs or name not in files:
continue
if normalized[("head", name)] in {normalized[(name, ours)], normalized[(name, theirs)]}:
continue
ancestry = tree(repo, ancestors[0])
for name in names:
ours, theirs = lineage.trees[left].get(name), lineage.trees[right].get(name)
if ours is None or theirs is None or ours == theirs or name not in ancestry:
continue
if normalized[("head", name)] in {normalized[(name, ours)], normalized[(name, theirs)]}:
continue
content = merge_blobs(repo, ours, ancestry[name], theirs)
if content is not None:
merged[(name, left, right)] = (content, {"path": name, "merge": [left, right],
"base": ancestors[0]})
candidates.append(((name, left, right), (ours, files[name], theirs), ancestor))
# Base pairs share most blobs: every distinct three-way merge runs once, all of them in parallel.
triples = list(dict.fromkeys(triple for _, triple, _ in candidates))
contents = dict(zip(triples, parallel(lambda triple: merge_blobs(repo, *triple), triples)))
merged = {}
for key, triple, ancestor in candidates:
if contents[triple] is not None:
merged[key] = (contents[triple], {"path": key[0], "merge": [key[1], key[2]], "base": ancestor})
if not merged:
return {}
with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary:
mycila = Mycila(repo, Path(temporary), plugin)
for key, (content, _) in merged.items():
mycila.add(key, key[0], content)
hashes = mycila.strip_headers()
found = normalize(repo, plugin, cache, {key: content for key, (content, _) in merged.items()})
hashes = {key: comparison_hash(content) for key, content in found.items()}
result = {}
for key, (_, description) in merged.items():
if hashes[key] == normalized[("head", key[0])]:
@ -937,6 +1126,85 @@ def clean_merges(repo, plugin, lineage, names, normalized):
return result
@dataclass(frozen=True)
class Selection:
since: str
merge_base: str
paths: frozenset | None
reason: str
@property
def full(self):
return self.paths is None
def report(self):
return {"since": self.since, "mergeBase": self.merge_base, "full": self.full, "reason": self.reason}
def merge_base(repo, since):
commit = resolve(repo, since)
bases = run(["git", "merge-base", commit, "HEAD"], repo, ok=(0, 1)).stdout.decode().split()
if not bases:
raise Failure(f"HEAD shares no history with {since}.")
return bases[0]
def changed_paths(repo, commit):
"""Paths that differ between the commit and the working tree, untracked files included."""
tracked = git(repo, "diff", "--name-only", "--no-renames", "-z", commit, "--")
untracked = git(repo, "ls-files", "--others", "--exclude-standard", "-z")
return {path.decode("utf-8") for path in (tracked + b"\0" + untracked).split(b"\0") if path}
def committed(repo, commit, name):
result = run(["git", "cat-file", "blob", f"{commit}:{name}"], repo, ok=(0, 128))
return result.stdout if result.returncode == 0 else None
def committed_plugin(repo, commit):
content = committed(repo, commit, "pom.xml")
try:
return None if content is None else plugin_signature(parse_plugin(xml_plain(io.BytesIO(content))))
except (Failure, ET.ParseError):
return None
def committed_curations(repo, commit):
content = committed(repo, commit, CURATIONS)
if content is None:
return {}
try:
return {entry["path"]: entry for entry in json.loads(content)["curations"]}
except (ValueError, KeyError, TypeError):
return None
def select_changes(repo, since, bases, ce_bases, plugin, curations):
"""Files to check against a PR target: the changed ones, unless a change can move verdicts of unchanged files."""
base = merge_base(repo, since)
def full(reason):
return Selection(since, base, None, reason)
try:
if sorted(ce_bases(base)) != sorted(bases):
return full("the CE commits merged into the branch changed")
except Failure:
return full("the CE commits merged at the merge base cannot be resolved")
if committed_plugin(repo, base) != plugin_signature(plugin):
return full("the Mycila configuration in the root pom.xml changed")
changed = changed_paths(repo, base)
checker = sorted(path for path in changed
if path.startswith(CHECKER_PATHS) and path not in {CURATIONS, README})
if checker:
return full(f"the check itself changed ({checker[0]})")
previous = committed_curations(repo, base)
curated = set(curations) if previous is None else {
name for name in set(previous) | set(curations) if previous.get(name) != curations.get(name)}
paths = frozenset(changed | curated)
return Selection(since, base, paths, f"{len(paths)} changed paths")
def current_branch(repo):
branch = git(repo, "rev-parse", "--abbrev-ref", "HEAD").decode().strip()
return "" if branch == "HEAD" else branch
@ -1058,15 +1326,19 @@ def print_findings(rows, curation_issues, ref_names):
f"Rerun with --fix to remove them from {CURATIONS}", style=None)
def print_summary(rows, curation_issues, report):
def print_summary(rows, curation_issues, report, label="files"):
findings = sum(row["status"] != "match" for row in rows) + len(curation_issues)
restamped = sum("previousHeader" in row for row in rows)
note = f" ({restamped} restamped)" if restamped else ""
if findings:
console.line(f"{findings} finding{'s' if findings != 1 else ''} in {len(rows)} files{note}. Report: {report}",
console.line(f"{findings} finding{'s' if findings != 1 else ''} in {len(rows)} {label}{note}. Report: {report}",
"red")
return
console.line(f"All {len(rows)} files carry the expected header{note}.", "green")
if not rows:
console.line(f"No {label} to check.", "green")
console.line(f"Report: {report}")
return
console.line(f"All {len(rows)} {label} carry the expected header{note}.", "green")
counts = Counter(row["expectedHeader"] for row in rows)
console.line(" " + " · ".join(f"{header} {counts[header]}" for header in TEMPLATES if counts[header]))
console.line(f"Report: {report}")
@ -1166,16 +1438,37 @@ def check(args):
curation_bytes = curation_path.read_bytes()
curations = load_curations(curation_path)
console.begin("Resolving Git history")
bases = merged_ce_bases(repo, head, ce["commit"]) if "ref" in ce else relicensed_ce_bases(repo, head)
def ce_bases(commit):
return merged_ce_bases(repo, commit, ce["commit"]) if "ref" in ce else relicensed_ce_bases(repo, commit)
bases = ce_bases(head)
lineage = Lineage.load(repo, head, bases)
console.end("done (CE base " + ", ".join(ref_name(base, ref_names) for base in bases) + ")")
selection = None
if args.since:
console.begin(f"Selecting files changed since {args.since}")
selection = select_changes(repo, args.since, bases, ce_bases, plugin, curations)
console.end(("full check: " if selection.full else "") + selection.reason
+ f" (merge base {selection.merge_base[:11]})")
console.begin("Collecting Mycila scope")
scope = discover_scope(repo, plugin)
console.end(f"{len(scope.eligible)} files ({scope.ignored} Git-ignored skipped)")
contents = {name: (repo / name).read_bytes() for name in scope.eligible}
comparison = compare(repo, plugin, lineage, contents)
checked = (scope.eligible if selection is None or selection.full
else [name for name in scope.eligible if name in selection.paths])
if selection is not None and not selection.full:
console.line(f"Checking {len(checked)} of {len(scope.eligible)} files in scope", "dim")
contents = {name: (repo / name).read_bytes() for name in checked}
rows = []
if contents:
cache = (NoCache() if args.no_cache
else NormalizationCache((repo / args.cache).resolve(), cache_signature(repo, plugin)))
try:
comparison = compare(repo, plugin, lineage, contents, cache)
finally:
cache.close()
rows = [comparison.classify(name, curations.get(name)) for name in checked]
console.line()
rows = [comparison.classify(name, curations.get(name)) for name in scope.eligible]
orphaned = [{"path": name, "status": "stale-curation", "reason": "file is no longer in scope"}
for name in sorted(set(curations) - set(scope.eligible))]
ensure_inputs_unchanged(repo, lineage, curation_path, curation_bytes, contents)
@ -1190,6 +1483,7 @@ def check(args):
"head": lineage.head,
"ce": ce | {"bases": list(lineage.bases)},
"scope": {"supported": len(scope.eligible), "unknown": scope.unknown, "modules": scope.modules},
"selection": selection.report() if selection is not None else None,
"summary": dict(summary),
"restamped": sorted(row["path"] for row in rows if "previousHeader" in row),
"removedCurations": removed,
@ -1203,7 +1497,7 @@ def check(args):
print_restamped(rows)
print_removed_curations(removed)
print_findings(rows, orphaned, ref_names)
print_summary(rows, orphaned, report)
print_summary(rows, orphaned, report, "files" if selection is None or selection.full else "changed files")
return 1 if orphaned or summary.keys() - {"match"} else 0
@ -1215,7 +1509,15 @@ def main(argv=None):
"without it, CE is the history of HEAD that does not contain the relicensing commit")
parser.add_argument("--ce-remote", default=CE_REMOTE,
help=f"Git URL or path of the CE repository to fetch --ce-ref from (default: {CE_REMOTE})")
parser.add_argument("--since", metavar="REF",
help="check only files changed since the merge base of REF and HEAD, uncommitted and "
"untracked files included; falls back to the full check when the CE commits, the "
"root Mycila configuration or the check itself changed")
parser.add_argument("--output", default="target/license-provenance/report.json")
parser.add_argument("--cache", default=CACHE_DIRECTORY, metavar="DIRECTORY",
help="header-free CE contents from earlier runs, reused while the Mycila setup, the "
f"templates and the check stay the same (default: {CACHE_DIRECTORY})")
parser.add_argument("--no-cache", action="store_true", help="normalize every CE input again")
parser.add_argument("--fix", action="store_true",
help="restamp files whose expected header the check determined and remove redundant or "
"orphaned curations; unrecognized headers are kept")

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

@ -240,6 +240,57 @@ class DecisionTests(unittest.TestCase):
stderr.getvalue())
class ParallelTests(unittest.TestCase):
def test_jobs_follow_the_machine_unless_configured(self):
for cpus, expected in ((12, 11), (2, 1), (1, 1), (None, 1)):
with patch.dict(os.environ, {p.JOBS_VARIABLE: ""}), patch.object(p.os, "cpu_count", return_value=cpus):
self.assertEqual(expected, p.jobs(), f"{cpus} CPUs")
with patch.dict(os.environ, {p.JOBS_VARIABLE: "3"}):
self.assertEqual(3, p.jobs())
for wrong in ("0", "-2", "many"):
with patch.dict(os.environ, {p.JOBS_VARIABLE: wrong}), self.assertRaisesRegex(p.Failure, p.JOBS_VARIABLE):
p.jobs()
def test_parallel_keeps_item_order_and_raises_the_first_failure(self):
with patch.dict(os.environ, {p.JOBS_VARIABLE: "4"}):
self.assertEqual([item * 2 for item in range(50)], p.parallel(lambda item: item * 2, range(50)))
self.assertEqual([], p.parallel(lambda item: item, []))
def failing(item):
if item == 7:
raise p.Failure("item 7")
return item
with self.assertRaisesRegex(p.Failure, "item 7"):
p.parallel(failing, range(20))
class MycilaGuardTests(unittest.TestCase):
def tool(self):
tool = p.Mycila(this_repository(), temporary_directory(self), fixture_plugin())
tool.add(("head", "A.java"), "A.java", b"// header\ncode")
return tool
def test_guard_restores_the_file_end_and_rejects_a_rewritten_one(self):
tool = self.tool()
with tool.guarded([("head", "A.java")]):
tool.file(("head", "A.java")).write_bytes(tool.file(("head", "A.java")).read_bytes().replace(b"// header\n", b""))
self.assertEqual(b"code", tool.contents[("head", "A.java")])
with self.assertRaisesRegex(p.Failure, "Mycila rewrote the end"):
with tool.guarded([("head", "A.java")]):
tool.file(("head", "A.java")).write_bytes(b"code\n")
def test_scope_reports_are_accepted_only_from_target_directories(self):
repo = temporary_directory(self)
(repo / "module/target").mkdir(parents=True)
(repo / "module/target/token.json").write_text("{}")
self.assertEqual([repo / "module/target/token.json"], p.scope_reports(repo, "token.json"))
(repo / "other").mkdir()
(repo / "other/token.json").write_text("{}")
with self.assertRaisesRegex(p.Failure, "Unexpected scope report location"):
p.scope_reports(repo, "token.json")
class InputTests(unittest.TestCase):
def test_header_state_recognizes_legacy_thingsboard_headers(self):
ce = b"/**\n * Copyright \xc2\xa9 2016-2025 The Thingsboard Authors\n *\n * Licensed under the Apache License\n */\n"
@ -270,6 +321,8 @@ class InputTests(unittest.TestCase):
self.assertEqual(b"// SPDX-A\n// SPDX-B", p.swap_header(b"// SPDX-X\n// SPDX-Y\n// SPDX-Z", new, old))
with self.assertRaises(p.Failure):
p.swap_header(b"// SPDX-A\n\n// SPDX-B\ncode\n", old, new)
with self.assertRaises(p.Failure):
p.swap_header(b"// SPDX-A\n# SPDX-B\ncode\n", old, new)
with self.assertRaises(p.Failure):
p.swap_header(b"code\n", old, new)
@ -355,6 +408,30 @@ class InputTests(unittest.TestCase):
self.assertEqual(f"{p.TEMPLATE_DIRECTORY}/license-header-{p.NON_CE}.txt", p.TEMPLATES[p.NON_CE])
self.assertTrue((this_repository() / p.TEMPLATES[p.NON_CE]).is_file())
def test_committed_plugin_tracks_the_root_mycila_configuration(self):
git = GitFixture(temporary_directory(self), "main")
def pom(header):
return textwrap.dedent(f"""\
<project xmlns="http://maven.apache.org/POM/4.0.0"><build><pluginManagement><plugins><plugin>
<groupId>com.mycila</groupId><artifactId>license-maven-plugin</artifactId><version>5.1.2</version>
<configuration><header>{header}</header></configuration>
</plugin></plugins></pluginManagement></build></project>
""")
git.write("pom.xml", pom("a.txt"))
first = git.commit("pom")
git.write("pom.xml", "<!-- reformatted -->\n" + pom("a.txt"))
same = git.commit("comment only")
git.write("pom.xml", pom("b.txt"))
changed = git.commit("other header")
current = p.plugin_signature(p.read_plugin(git.root))
self.assertEqual(p.committed_plugin(git.root, first), p.committed_plugin(git.root, same))
self.assertNotEqual(p.committed_plugin(git.root, same), current)
self.assertEqual(p.committed_plugin(git.root, changed), current)
git("rm", "-q", "pom.xml")
self.assertIsNone(p.committed_plugin(git.root, git.commit("no pom")))
def test_plugin_version_and_configuration_come_from_root_pom(self):
repo = temporary_directory(self)
p.git(repo, "init")
@ -390,13 +467,13 @@ class GitHistoryTests(unittest.TestCase):
git("checkout", "lts-4.2")
git("merge", "--no-ff", "side", "-m", "integrate")
merged = git("rev-parse", "HEAD")
changes = p.history(git.root, "HEAD")
changes = p.history(git.root, ["HEAD"])
self.assertEqual({initial, merged}, {change.commit for change in changes})
self.assertEqual(source, changes[0].path)
git("rm", source)
git.commit("delete")
deleted = p.history(git.root, "HEAD", "--diff-filter=D")
deleted = p.history(git.root, ["HEAD"], "--diff-filter=D")
self.assertEqual(["D"], [change.status for change in deleted])
self.assertEqual(b"merged result\n", p.blobs(git.root, [deleted[0].old])[deleted[0].old])
@ -491,6 +568,71 @@ class GitHistoryTests(unittest.TestCase):
self.assertEqual([(removal, git("rev-parse", f"{removal}:Kept.java"))], lineage.versions("Kept.java"))
self.assertEqual([], lineage.versions("Gone.java"))
def test_lineage_walks_shared_history_of_several_bases_once(self):
git = GitFixture(temporary_directory(self), "ce")
git.write("Shared.java", "deleted before the bases diverged\n")
git.write("Left.java", "deleted on the left base\n")
git.write("Right.java", "deleted on the right base\n")
git.commit("CE base")
git("rm", "Shared.java")
shared = git.commit("shared removal")
git("checkout", "-b", "right")
git("rm", "Right.java")
right = git.commit("right removal")
git("checkout", "ce")
git("rm", "Left.java")
left = git.commit("left removal")
separately = {}
for base in (left, right):
for change in p.history(git.root, [base], "--diff-filter=D"):
separately.setdefault(change.path, set()).add(change.commit)
together = p.history(git.root, [left, right], "--diff-filter=D")
self.assertEqual(3, len(together), "the shared removal is listed once")
self.assertEqual(separately, {change.path: {change.commit} for change in together})
lineage = p.Lineage.load(git.root, left, [left, right])
self.assertEqual({"Shared.java": shared + "^1", "Left.java": left + "^1", "Right.java": right + "^1"},
{path: entry["ref"] for path, entry in lineage.deleted.items()})
with self.assertRaises(p.Failure):
p.history(git.root, [])
with self.assertRaises(p.Failure):
p.history(git.root, ["--all"])
def test_clean_merges_match_each_file_with_its_own_merge_in_any_order(self):
git = GitFixture(temporary_directory(self), "ce")
for header, name in p.TEMPLATES.items():
git.write(name, f"fixture {header}\n")
lines = "".join(f"line {index}\n" for index in range(12))
git.write("A.java", "A\n" + lines)
git.write("B.java", "B\n" + lines)
base = git.commit("CE base")
bases = {}
for branch, line in (("left", "line 0"), ("middle", "line 5"), ("right", "line 11")):
git("checkout", "-q", "-b", branch, base)
git.write("A.java", "A\n" + lines.replace(line, branch))
git.write("B.java", "B\n" + lines.replace(line, branch))
bases[branch] = git.commit(branch)
lineage = p.Lineage.load(git.root, bases["left"], sorted(bases.values()))
# HEAD carries A merged from left and right, B merged from middle and right: two distinct merges.
head = {"A.java": "A\n" + lines.replace("line 0", "left").replace("line 11", "right"),
"B.java": "B\n" + lines.replace("line 5", "middle").replace("line 11", "right")}
normalized = {("head", name): p.comparison_hash(text.encode()) for name, text in head.items()}
for files in lineage.trees.values():
for name, oid in files.items():
normalized[(name, oid)] = p.comparison_hash(p.blobs(git.root, [oid])[oid])
def strip_headers(tool):
return {key: p.comparison_hash(content) for key, content in tool.contents.items()}
expected = {"A.java": sorted([bases["left"], bases["right"]]),
"B.java": sorted([bases["middle"], bases["right"]])}
with patch.object(p.Mycila, "strip_headers", strip_headers):
for workers in ("1", "4"):
with patch.dict(os.environ, {p.JOBS_VARIABLE: workers}):
merges = p.clean_merges(git.root, fixture_plugin(), p.NoCache(), lineage, list(head), normalized)
self.assertEqual(expected, {name: sorted(merge["merge"]) for name, merge in merges.items()},
f"{workers} workers")
self.assertEqual({base}, {merge["base"] for merge in merges.values()})
def test_merge_blobs_returns_only_clean_merges(self):
git = GitFixture(temporary_directory(self), "main")
git.write("File.java", "one\ntwo\nthree\nfour\nfive\n")
@ -569,6 +711,10 @@ class FetchTests(unittest.TestCase):
third = self.ce.commit("third")
self.assertEqual(third, self.fetch("lts-4.2"))
def test_a_local_branch_of_the_same_name_does_not_shadow_the_fetched_tip(self):
self.local("branch", "lts-4.2")
self.assertEqual(self.second, self.fetch("lts-4.2"))
def test_missing_ref_and_option_like_ref_are_rejected(self):
with self.assertRaisesRegex(p.Failure, r"(?s)cannot fetch 'missing' from .*couldn't find remote ref missing"):
self.fetch("missing")
@ -609,7 +755,7 @@ class CheckCommandTests(unittest.TestCase):
self.scope = ["Base.java", "Changed.java", "Fixed.java", "Merged.java", "New.java", "Source.java"]
self.output = self.repo / "target/report.json"
def check(self, *args, scope=None):
def check(self, *args, scope=None, base_plugin=fixture_plugin(), normalizer=None):
def recognized(content):
for header in p.TEMPLATES:
if content.startswith(fixture(header).encode()):
@ -639,9 +785,10 @@ class CheckCommandTests(unittest.TestCase):
with (patch.object(p.Path, "cwd", return_value=self.repo),
patch.object(p, "RELICENSING_COMMIT", self.relicensing),
patch.object(p, "read_plugin", return_value=fixture_plugin()),
patch.object(p, "committed_plugin", return_value=p.plugin_signature(base_plugin)),
patch.object(p, "discover_scope", return_value=p.Scope(scope or self.scope, [], [], 0)),
patch.object(p.Mycila, "current_headers", current_headers),
patch.object(p.Mycila, "strip_headers", strip_headers),
patch.object(p.Mycila, "strip_headers", normalizer or strip_headers),
patch.object(p.Mycila, "restamp", restamp),
redirect_stdout(io.StringIO()), redirect_stderr(stderr)):
code = p.main(["check", "--output", str(self.output), *args])
@ -737,6 +884,116 @@ class CheckCommandTests(unittest.TestCase):
code, report, _ = self.check("--fix", scope=scope)
self.assertEqual((0, []), (code, report["removedCurations"]))
def pull_request(self):
self.git("checkout", "-q", "-b", "feature")
return self.git("rev-parse", "master")
def checked(self, report):
return sorted(row["path"] for row in report["files"])
def test_files_changed_during_the_scan_fail_the_check(self):
compare = p.compare
def edit_while_scanning(*args):
result = compare(*args)
self.git.write("Base.java", fixture("apache") + "edited during the scan\n")
return result
with patch.object(p, "compare", edit_while_scanning):
code, report, output = self.check()
self.assertEqual((2, None), (code, report))
self.assertIn("changed during the scan", output)
def test_since_checks_only_changed_and_untracked_files(self):
target = self.pull_request()
self.git.write("New.java", fixture("apache") + "TB feature\n")
self.git.commit("wrong header on a TB file")
self.git.write("Added.java", fixture(p.NON_CE) + "untracked TB file\n")
code, report, output = self.check("--since", "master", scope=self.scope + ["Added.java"])
self.assertEqual(1, code)
self.assertEqual(["Added.java", "New.java"], self.checked(report))
self.assertEqual("mismatch", self.rows(report)["New.java"]["status"])
self.assertEqual({"since": "master", "mergeBase": target, "full": False, "reason": "2 changed paths"},
report["selection"])
self.assertEqual(7, report["scope"]["supported"])
self.assertIn("Checking 2 of 7 files in scope", output)
self.assertIn("1 finding in 2 changed files", output)
def test_since_without_changes_checks_nothing_but_orphaned_curations(self):
self.pull_request()
code, report, output = self.check("--since", "master")
self.assertEqual((0, []), (code, report["files"]))
self.assertIn("No changed files to check.", output)
orphaned = dict(path="Gone.java", header=p.NON_CE, reason="Reviewed", contentHash=p.raw_hash(b"gone"))
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[orphaned])))
self.git.commit("curation of a file that is not in scope")
code, report, _ = self.check("--since", "master")
self.assertEqual(1, code)
self.assertEqual(["Gone.java"], [issue["path"] for issue in report["curationIssues"]])
def test_since_checks_files_whose_curation_changed(self):
curation = dict(path="New.java", header="apache", reason="Reviewed",
contentHash=p.raw_hash((self.repo / "New.java").read_bytes()))
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[curation])))
self.git.commit("curate New.java")
self.pull_request()
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[])))
self.git.commit("drop the curation")
code, report, _ = self.check("--since", "master")
self.assertEqual(0, code)
self.assertEqual(["New.java"], self.checked(report))
self.assertEqual("not in CE, no CE evidence", self.rows(report)["New.java"]["reason"])
def test_since_checks_every_file_when_new_ce_commits_are_merged(self):
self.pull_request()
self.git("checkout", "-q", "lts-4.3")
self.git.write("Fixed.java", fixture("apache") + "second lts addition\n")
self.git.commit("second CE fix")
self.git("checkout", "-q", "feature")
self.git("merge", "-q", "--no-ff", "lts-4.3", "-m", "integrate second CE fix")
code, report, output = self.check("--since", "master")
self.assertEqual(0, code)
self.assertEqual(sorted(self.scope), self.checked(report))
self.assertEqual("the CE commits merged into the branch changed", report["selection"]["reason"])
self.assertTrue(report["selection"]["full"])
self.assertIn("full check: the CE commits merged into the branch changed", output)
def test_since_checks_every_file_when_the_check_changes(self):
self.pull_request()
self.git.write(p.TEMPLATES["apache"], "fixture apache, reworded\n")
self.git.commit("change a template")
_, report, _ = self.check("--since", "master")
self.assertEqual(sorted(self.scope), self.checked(report))
self.assertEqual(f"the check itself changed ({p.TEMPLATES['apache']})", report["selection"]["reason"])
def test_since_checks_every_file_when_the_mycila_configuration_changes(self):
self.pull_request()
_, report, _ = self.check("--since", "master", base_plugin=fixture_plugin("1"))
self.assertEqual(sorted(self.scope), self.checked(report))
self.assertEqual("the Mycila configuration in the root pom.xml changed", report["selection"]["reason"])
def test_since_does_not_orphan_curations_of_unchanged_files(self):
curation = dict(path="Source.java", header="apache", reason="Reviewed",
contentHash=p.raw_hash((self.repo / "Source.java").read_bytes()))
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[curation])))
self.git.commit("curate Source.java")
self.pull_request()
self.git.write("New.java", fixture(p.NON_CE) + "TB feature, changed\n")
self.git.commit("unrelated change")
code, report, _ = self.check("--since", "master")
self.assertEqual(0, code)
self.assertEqual(["New.java"], self.checked(report))
self.assertEqual([], report["curationIssues"])
def test_since_needs_shared_history(self):
self.git("checkout", "-q", "--orphan", "unrelated")
self.git.write("Other.java", "other\n")
self.git.commit("unrelated")
self.git("checkout", "-q", "master")
code, _, output = self.check("--since", "unrelated")
self.assertEqual(2, code)
self.assertIn("HEAD shares no history with unrelated", output)
def test_missing_relicensing_commit_fails_before_the_scan(self):
self.relicensing = "0" * 40
code, report, output = self.check()
@ -886,10 +1143,183 @@ def stamped(header, extension):
return text[:-1] if extension in {"java", "ts"} else text
class CopySearchTests(unittest.TestCase):
check = CheckCommandTests.check
rows = CheckCommandTests.rows
BODY = "".join(f" copied statement number {index};\n" for index in range(40))
def test_size_filter_follows_git_similarity_threshold(self):
git = GitFixture(temporary_directory(self), "main")
destination = ("".join(f"line {index:04d}\n" for index in range(100))).encode()
half = destination[:len(destination) // 2]
for source, expected in ((half, True), (half[:-1], False)):
self.assertEqual(expected, p.could_be_copy(len(source), [len(destination)]))
tool = p.Mycila.__new__(p.Mycila)
tool.root, tool.paths, tool.contents = git.root, {}, {}
tool.add(("Source.java", "0" * 40), "Source.java", source)
tool.add(("head", "Destination.java"), "Destination.java", destination)
found = p.normalized_copies(tool, {("Source.java", "0" * 40): "ref"}, {"Destination.java"},
tool.nonempty())
self.assertEqual(expected, "Destination.java" in found, f"{len(source)} of {len(destination)} bytes")
for path in ("files", ".git"):
p.run(["rm", "-rf", path], git.root)
def test_filter_before_normalizing_drops_exactly_the_unreachable_sources(self):
# Normalizing removes a header and never grows a file: a source of raw size r can end up at any size up to r.
for destinations in ([7], [7, 30], [30, 7], [12, 13, 60]):
for raw in range(1, 70):
reachable = any(p.could_be_copy(size, destinations) for size in range(1, raw + 1))
self.assertEqual(reachable, p.could_shrink_to_copy(raw, destinations), f"{raw} → {destinations}")
def setUp(self):
self.repo = temporary_directory(self)
self.git = git = GitFixture(self.repo, "master")
git.write(".gitignore", "target/\n")
for category, name in p.TEMPLATES.items():
git.write(name, f"fixture {category}\n")
git.write(p.CURATIONS, '{"schemaVersion": 1, "curations": []}')
# Sorted CE sources: a/ (small), b/Alpha, c/ (small), e/Gamma. Among all inputs Gamma takes slot 12 and
# Alpha slot 3, so Gamma comes first in the copy search and wins the tie between the identical sources.
for name in ("a/Small0.java", "a/Small1.java", *(f"c/Small{index}.java" for index in range(2, 10))):
git.write(name, fixture("apache") + "x\n")
git.write("b/Alpha.java", fixture("apache") + self.BODY)
git.write("e/Gamma.java", fixture("apache") + self.BODY)
git.commit("CE")
git.write("d/Delta.java", fixture(p.NON_CE) + self.BODY)
self.relicensing = git.commit("relicensing")
self.scope = ["d/Delta.java"]
self.output = self.repo / "target/report.json"
def test_size_filter_keeps_the_copy_search_result(self):
_, filtered, output = self.check()
with (patch.object(p, "could_shrink_to_copy", return_value=True),
patch.object(p, "could_be_copy", return_value=True)):
_, unfiltered, unfiltered_output = self.check()
self.assertEqual(unfiltered, filtered)
row = self.rows(filtered)["d/Delta.java"]
self.assertEqual(("unresolved", "apache"), (row["status"], row["suggestedHeader"]))
self.assertEqual(["e/Gamma.java"], [copy["path"] for copy in row["copyCandidates"]])
self.assertIn("2 of 12 other CE files searched for copies", output)
self.assertIn("12 of 12 other CE files searched for copies", unfiltered_output)
def test_a_file_grown_by_normalizing_fails_the_check(self):
def strip_headers(tool):
tool.removed, tool.stacked = {key: b"" for key in tool.contents}, set()
for key, content in list(tool.contents.items()):
tool.write(key, content + b"appended by a broken normalizer\n")
return {key: p.comparison_hash(content) for key, content in tool.contents.items()}
code, _, output = self.check(normalizer=strip_headers)
self.assertEqual(2, code)
self.assertIn("Mycila grew these files while removing their headers", output)
class CacheTests(unittest.TestCase):
LINES = CheckCommandTests.LINES
setUp = CheckCommandTests.setUp
check = CheckCommandTests.check
def normalizer(self, seen):
def strip_headers(tool):
seen.append(sorted(tool.contents))
tool.removed, tool.stacked = {}, set()
for key, body in list(tool.contents.items()):
first, _, rest = body.partition(b"\n")
header = first.startswith(b"// ")
tool.removed[key] = first + b"\n" if header else b""
tool.write(key, rest if header else body)
return {key: p.comparison_hash(body) for key, body in tool.contents.items()}
return strip_headers
def cache(self):
return self.repo / p.CACHE_DIRECTORY
def test_a_second_run_takes_ce_inputs_from_the_cache_and_reports_the_same(self):
first, second = [], []
_, cold, _ = self.check(normalizer=self.normalizer(first))
self.assertTrue((self.cache() / p.CACHE_UPDATED).exists())
_, warm, output = self.check(normalizer=self.normalizer(second))
self.assertEqual(cold, warm)
self.assertTrue(any(key[0] != "head" for batch in first for key in batch))
self.assertEqual({"head"}, {key[0] for batch in second for key in batch})
self.assertFalse((self.cache() / p.CACHE_UPDATED).exists())
self.assertRegex(output, r"[1-9][0-9]* from the cache")
def test_without_the_cache_nothing_is_read_or_written(self):
self.check()
seen = []
_, report, output = self.check("--no-cache", normalizer=self.normalizer(seen))
self.assertTrue(any(key[0] != "head" for batch in seen for key in batch))
self.assertIn(" 0 from the cache", output)
shutil_tree = sorted(path.name for path in self.cache().iterdir())
self.check("--no-cache")
self.assertEqual(shutil_tree, sorted(path.name for path in self.cache().iterdir()))
def test_entries_are_keyed_by_content_and_file_name(self):
cache = p.NormalizationCache(temporary_directory(self), "signature")
cache.put([(("A.java", "a"), b"// header\nbody\n", b"body\n")])
self.assertEqual({("moved/A.java", "b"): b"body\n"}, cache.get({("moved/A.java", "b"): b"// header\nbody\n"}))
self.assertEqual({}, cache.get({("B.java", "b"): b"// header\nbody\n"}))
self.assertEqual({}, cache.get({("A.xml", "a"): b"// header\nbody\n"}))
self.assertEqual({}, cache.get({("A.java", "a"): b"// header\nother\n"}))
cache.close()
def test_signature_follows_everything_that_shapes_normalization(self):
repo = temporary_directory(self)
for header, name in p.TEMPLATES.items():
(repo / name).parent.mkdir(parents=True, exist_ok=True)
(repo / name).write_text(f"fixture {header}\n")
signature = p.cache_signature(repo, fixture_plugin("1"))
self.assertEqual(signature, p.cache_signature(repo, fixture_plugin("1")))
self.assertNotEqual(signature, p.cache_signature(repo, fixture_plugin("2")))
other = p.Plugin("1", ET.fromstring("<configuration><mapping><java>SLASHSTAR_STYLE</java></mapping></configuration>"))
self.assertNotEqual(signature, p.cache_signature(repo, other))
with patch.object(p, "CACHE_FORMAT", "other"):
self.assertNotEqual(signature, p.cache_signature(repo, fixture_plugin("1")))
(repo / p.TEMPLATES["apache"]).write_text("reworded\n")
self.assertNotEqual(signature, p.cache_signature(repo, fixture_plugin("1")))
def test_only_recent_signatures_are_kept_and_the_update_mark_is_fresh(self):
directory = temporary_directory(self)
for index in range(p.CACHE_SIGNATURES_KEPT + 2):
stale = directory / f"old{index}.sqlite"
stale.write_bytes(b"")
os.utime(stale, (index, index))
(directory / p.CACHE_UPDATED).touch()
cache = p.NormalizationCache(directory, "current")
self.assertFalse((directory / p.CACHE_UPDATED).exists())
kept = sorted(path.name for path in directory.glob("*.sqlite"))
self.assertEqual(p.CACHE_SIGNATURES_KEPT, len(kept))
self.assertIn("current.sqlite", kept)
cache.close()
self.assertFalse((directory / p.CACHE_UPDATED).exists())
def test_a_damaged_cache_is_started_again(self):
directory = temporary_directory(self)
(directory / "damaged.sqlite").write_bytes(b"not a database, cut off by a failed restore")
cache = p.NormalizationCache(directory, "damaged")
self.assertEqual({}, cache.get({("A.java", "a"): b"raw"}))
cache.put([(("A.java", "a"), b"raw", b"normalized")])
cache.close()
self.assertEqual({("A.java", "a"): b"normalized"},
p.NormalizationCache(directory, "damaged").get({("A.java", "a"): b"raw"}))
def test_the_cache_of_a_branch_checked_long_ago_survives_newer_signatures(self):
directory = temporary_directory(self)
p.NormalizationCache(directory, "revisited").close()
os.utime(directory / "revisited.sqlite", (1, 1))
for index in range(p.CACHE_SIGNATURES_KEPT):
(directory / f"newer{index}.sqlite").write_bytes(b"")
cache = p.NormalizationCache(directory, "revisited")
cache.put([(("A.java", "a"), b"raw", b"normalized")])
cache.close()
self.assertTrue((directory / "revisited.sqlite").exists())
@unittest.skipUnless(os.environ.get("LICENSE_HEADERS_MAVEN_TESTS") == "1", "opt-in Maven fixtures")
class MavenTests(unittest.TestCase):
def test_scope_reports_respect_module_relative_exclusions(self):
repo = temporary_directory(self)
repo = temporary_directory(self).resolve() # macOS: /var/folders is a symlink to /private/var/folders
p.git(repo, "init")
(repo / "header.txt").write_text("SPDX-FileCopyrightText: Copyright Example\n"
"SPDX-License-Identifier: Apache-2.0\n")

Loading…
Cancel
Save