Browse Source

fix: check license headers against CE history in the unified codebase

The check compared each branch against a CE counterpart branch fetched from
thingsboard/thingsboard, which is now the unified codebase itself, so every
file was compared with itself and 5,468 files were reported with a wrong
header.

CE is now the history that does not contain the relicensing commit
31936b09d2. The check compares each file against the latest CE commits merged
into the branch:

- a path that exists in CE is apache when its content equals a CE version or a
  clean merge of its CE versions, and ce-modified otherwise;
- a new path is busl unless it is at least 50% similar to a CE file or CE
  history had this path, which needs a decision;
- --ce-ref keeps the previous mode of comparing against a fetched CE ref.

The third header kind is named after its template, license-header-busl.txt,
and curations use busl instead of pe-only. --fix also removes redundant
curations and curations of files that are no longer in scope, and the check
lists redundant curations.
pull/16249/head
Dmytro Skarzhynets 2 months ago
committed by Andrew Shvayka
parent
commit
e254a4e500
  1. 26
      .github/workflows/check-license-headers.yml
  2. 19
      check-license-headers.sh
  3. 54
      tools/src/main/python/license-headers/README.md
  4. 503
      tools/src/main/python/license-headers/check_license_headers.py
  5. 546
      tools/src/main/python/license-headers/curations.json
  6. 610
      tools/src/main/python/license-headers/test_check_license_headers.py

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

@ -11,19 +11,12 @@ on:
- master
- rc
- 'lts-[0-9]+.[0-9]+'
- 'license-lts-[0-9]+.[0-9]+'
pull_request:
branches:
- master
- rc
- 'lts-[0-9]+.[0-9]+'
- 'license-lts-[0-9]+.[0-9]+'
workflow_dispatch:
inputs:
ce-branch:
description: CE branch to compare against; defaults to the counterpart of the current branch
required: false
type: string
permissions:
contents: read
@ -53,27 +46,10 @@ jobs:
java-version: 21
cache: maven
- name: Resolve CE branch
id: ce
env:
PE_BRANCH: ${{ github.base_ref || github.ref_name }}
CE_BRANCH: ${{ inputs.ce-branch }}
run: |
if [[ -z "$CE_BRANCH" ]]; then
case "$PE_BRANCH" in
master|rc) CE_BRANCH="$PE_BRANCH" ;;
lts-*|license-lts-*) CE_BRANCH="${PE_BRANCH#license-}" ;;
*) echo "::error::No CE counterpart is defined for branch $PE_BRANCH"; exit 1 ;;
esac
fi
echo "branch=$CE_BRANCH" >> "$GITHUB_OUTPUT"
- name: Check license headers
env:
CE_BRANCH: ${{ steps.ce.outputs.branch }}
run: |
mkdir -p target/license-provenance
./check-license-headers.sh "${CE_BRANCH}" 2>&1 | tee target/license-provenance/console.log
./check-license-headers.sh 2>&1 | tee target/license-provenance/console.log
- name: Add findings to the job summary
if: failure() && hashFiles('target/license-provenance/console.log') != ''

19
check-license-headers.sh

@ -8,21 +8,18 @@ set -euo pipefail
usage() {
echo "Checks SPDX license headers against CE provenance."
echo "usage: $0 <ce-ref> [--fix] [--ce-remote <url>] [--output target/...]"
echo " ce-ref CE branch, tag or commit matching this PE branch, e.g. lts-4.2;"
echo " fetched from the CE repository on every run"
echo "usage: $0 [--fix] [--ce-ref <ref>] [--ce-remote <url>] [--output target/...]"
echo " --fix restamp files whose expected header the check determined"
echo " --ce-remote CE repository to fetch from (default: https://github.com/thingsboard/thingsboard.git)"
echo " and remove redundant or orphaned curations"
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)"
}
if [[ $# -eq 0 || "$1" == "-h" || "$1" == "--help" || "$1" == -* ]]; then
if [[ $# -gt 0 && ( "$1" == "-h" || "$1" == "--help" ) ]]; then
usage
[[ $# -gt 0 && ( "$1" == "-h" || "$1" == "--help" ) ]] && exit 0
exit 2
exit 0
fi
ce_ref="$1"
shift
cd "$(git rev-parse --show-toplevel)"
exec python3 tools/src/main/python/license-headers/check_license_headers.py check --ce-ref "$ce_ref" "$@"
exec python3 tools/src/main/python/license-headers/check_license_headers.py check "$@"

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

@ -1,29 +1,50 @@
# License header provenance check
Verifies that every file carries the SPDX header its origin requires: `apache`
for unchanged CE files, `ce-modified` for CE files with PE changes, `pe-only`
for files that do not exist in CE. A `pom.xml` added in PE under a directory
that has no files in CE is `pe-only` even when it resembles a CE `pom.xml`:
module identity, dependencies and packaging define the PE artifact.
for unchanged CE files, `ce-modified` for CE files with changes, and the third
header of this repository, `busl`, for files that do not come from CE. The
third header is the only `templates/license-header-<kind>.txt` besides the
`ce-modified` one, and its `<kind>` names it in the output and in curations.
CE is the history of the ThingsBoard Community Edition under Apache-2.0. The
check compares against the latest CE commits merged into the current branch:
- By default, CE commits are the ones that do not have the relicensing commit
`31936b09d24` in their history, for example pre-4.4 master and the lts-4.3
commits merged into lts-4.4.
- With `--ce-ref`, CE commits are the history of the given CE branch, tag, or
commit. It is fetched from `https://github.com/thingsboard/thingsboard.git`
on every run; pass `--ce-remote` to fetch from another URL or a local clone.
## Rules
A file whose path exists in CE is `apache` when its content without the
header equals a CE version of it, or a clean merge of its CE versions, and
`ce-modified` otherwise.
A 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
had this path. A `pom.xml` added under a directory that has no files in CE is
`busl` even when it resembles a CE `pom.xml`: module identity, dependencies and
packaging define the new artifact.
## Run
```sh
./check-license-headers.sh lts-4.2
./check-license-headers.sh
```
The argument is the CE branch, tag, or commit matching the current PE branch. It
is fetched from `https://github.com/thingsboard/thingsboard.git` on every run, so
the clone needs network access but no CE remote of its own. Pass `--ce-remote`
to fetch from another URL or a local CE clone instead.
The check needs the full Git history of the clone.
## Fix automatically
```sh
./check-license-headers.sh lts-4.2 --fix
./check-license-headers.sh --fix
```
Restamps every file whose expected header the check determined by itself.
Restamps every file whose expected header the check determined by itself and
removes curations that are redundant, because the check decides the same header
by itself, or that belong to files no longer in scope.
## Add a curation
@ -31,15 +52,18 @@ For files the check cannot decide ("Needs a decision"), record the decision in
`curations.json` next to this file:
1. Put the correct header on the file. A file that exists in CE, even renamed
or moved, is `ce-modified`; a file that does not exist in CE is `pe-only`.
or moved, is `ce-modified`; a file that does not exist in CE is `busl`.
2. Run `sha256sum path/to/File.java`.
3. Add an entry and rerun the check:
```json
{
"path": "path/to/File.java",
"contentHash": "sha256:<64 hex digits>",
"header": "pe-only",
"reason": "Which CE file this was compared against and why the header follows."
"header": "busl",
"reason": "Which CE file this was compared against and why the header follows.",
"contentHash": "sha256:<64 hex digits>"
}
```
A curation whose file changed since the review is stale and fails the check
until someone reviews the file again and updates `contentHash`.

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

@ -24,11 +24,24 @@ import uuid
import xml.etree.ElementTree as ET
TEMPLATE_DIRECTORY = "tools/src/main/python/license-headers/templates"
def non_ce_header(directory):
kinds = sorted(path.name[len("license-header-"):-len(".txt")] for path in directory.glob("license-header-*.txt"))
kinds = [kind for kind in kinds if kind != "ce-modified"]
if len(kinds) != 1:
raise RuntimeError(f"Expected exactly one license-header-<kind>.txt besides the ce-modified one in {directory}")
return kinds[0]
NON_CE = non_ce_header(Path(__file__).resolve().parent / "templates")
TEMPLATES = {
"apache": "tools/src/main/python/license-headers/templates/license-header.txt",
"ce-modified": "tools/src/main/python/license-headers/templates/license-header-ce-modified.txt",
"pe-only": "tools/src/main/python/license-headers/templates/license-header-busl.txt",
"apache": f"{TEMPLATE_DIRECTORY}/license-header.txt",
"ce-modified": f"{TEMPLATE_DIRECTORY}/license-header-ce-modified.txt",
NON_CE: f"{TEMPLATE_DIRECTORY}/license-header-{NON_CE}.txt",
}
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"
@ -152,16 +165,35 @@ def fetch(repo, remote, ref):
return resolve(repo, "FETCH_HEAD")
def unique_base(repo, left, right):
bases = git(repo, "merge-base", "--all", left, right).decode().splitlines()
if len(bases) != 1:
raise Failure(f"found {len(bases)} merge bases between PE HEAD and the CE ref, expected exactly one. "
"Check that the right CE branch was passed.")
return bases[0]
def independent(repo, commits):
return sorted(git(repo, "merge-base", "--independent", *commits).decode().split())
def contains(repo, ancestor, descendant):
return run(["git", "merge-base", "--is-ancestor", ancestor, descendant], repo, ok=(0, 1, 128)).returncode == 0
def first_parent_commits(repo, revision):
return git(repo, "rev-list", "--first-parent", revision).decode().splitlines()
def relicensed_ce_bases(repo, head):
if not contains(repo, RELICENSING_COMMIT, head):
raise Failure(f"the relicensing commit {RELICENSING_COMMIT[:11]} is not in the history of HEAD. "
"Pass --ce-ref with the CE branch that this branch integrates.")
records = git(repo, "rev-list", "--parents", "--ancestry-path", f"{RELICENSING_COMMIT}..{head}").decode().splitlines()
records.append(git(repo, "rev-list", "--parents", "-1", RELICENSING_COMMIT).decode().strip())
commits = {record.split()[0] for record in records}
parents = {parent for record in records for parent in record.split()[1:]}
return independent(repo, sorted(parents - commits))
def merged_ce_bases(repo, head, baseline):
bases = run(["git", "merge-base", "--all", head, baseline], repo, ok=(0, 1)).stdout.decode().split()
if not bases:
raise Failure("HEAD shares no history with the CE ref. Check that the right CE branch was passed.")
return independent(repo, bases)
def merge_blobs(repo, ours, base, theirs):
result = run(["git", "merge-file", "-p", "--object-id", ours, base, theirs], repo, ok=range(0, 256))
return result.stdout if result.returncode == 0 else None
def tree(repo, revision):
@ -203,10 +235,6 @@ class Change:
new: str
status: str
@property
def deleted(self):
return self.status == "D"
def history(repo, revision, *options):
raw = git(repo, "log", "--first-parent", "--diff-merges=first-parent", "--root", "--raw", "--no-abbrev",
@ -239,21 +267,6 @@ def parse_history(raw):
raise Failure(f"Unexpected Git history token: {token[:80]!r}")
def integration_boundary(repo, anchor, head):
chain = first_parent_commits(repo, head)
low, high = 0, len(chain)
while low < high:
middle = (low + high) // 2
code = run(["git", "merge-base", "--is-ancestor", anchor, chain[middle]], repo, ok=(0, 1)).returncode
if code == 0:
low = middle + 1
else:
high = middle
if not low:
raise Failure("CE anchor is not in PE history")
return chain[low - 1]
def git_ignored(repo, paths):
if not paths:
return set()
@ -513,7 +526,7 @@ class Mycila:
(directory / name).write_bytes(self.templates[header])
def add(self, key, name, content):
group = "pe" if key[0] == "pe" else "ce"
group = "head" if key[0] == "head" else "ce"
path = self.root / "files" / group / str(len(self.paths)) / PurePosixPath(name).name
path.parent.mkdir(parents=True)
path.write_bytes(content)
@ -561,11 +574,11 @@ class Mycila:
def remove_headers(self, keys):
before = {key: self.contents[key] for key in keys}
with self.guarded(keys):
results = self.invoke("remove", "pe-only", keys, styles=(STRICT_XML,))
results = self.invoke("remove", NON_CE, keys, styles=(STRICT_XML,))
unchanged = [key for key, result in results.items()
if result == "NOOP" and PurePosixPath(self.paths[key]).suffix in BLOCK_COMMENT_SUFFIXES]
if unchanged:
self.invoke("remove", "pe-only", unchanged, styles=(STRICT_XML, STRICT_BLOCK))
self.invoke("remove", NON_CE, unchanged, styles=(STRICT_XML, STRICT_BLOCK))
removed = {}
for key in keys:
content, removed[key] = split_removed(before[key], self.contents[key])
@ -690,14 +703,14 @@ class Mycila:
selected = set(keys)
if selected == set(self.paths):
return ["files/**"]
if selected == {key for key in self.paths if key[0] == "pe"}:
return ["files/pe/**"]
if selected == {key for key in self.paths if key[0] == "head"}:
return ["files/head/**"]
return [str(PurePosixPath(self.paths[key]).parent) + "/*" for key in keys]
def normalized_copies(mycila, source_refs, names, nonempty):
sources = set(source_refs) & nonempty
destinations = {("pe", name) for name in names} & nonempty
destinations = {("head", name) for name in names} & nonempty
if not sources or not destinations:
return {}
git(mycila.root, "init", "--quiet")
@ -712,7 +725,7 @@ def normalized_copies(mycila, source_refs, names, nonempty):
for source, destination, similarity in parse_copies(raw):
source_key, destination_key = keys[source], keys[destination]
if source_key not in sources or destination_key not in destinations:
raise Failure("Normalized copy escaped the selected CE/PE inputs")
raise Failure("Normalized copy escaped the selected CE and HEAD inputs")
copies[destination_key[1]].append({"path": source_key[0], "blob": source_key[1],
"ref": source_refs[source_key], "similarity": similarity})
return dict(copies)
@ -742,160 +755,78 @@ class Evidence:
path: str
content_hash: str
current: str
curation: dict | None
inherited: bool
recreated: bool
ce_hash: str | None
pe_hash: str
candidates: list
historical: list
in_comparison: bool
pe_addition: bool = False
curation: dict | None = None
ce_versions: tuple = ()
identical: dict | None = None
copies: tuple = ()
deleted: dict | None = None
directory_in_ce: bool = True
ce_ref: str | None = None
ce_blob: str | None = None
@property
def strong(self):
return [c for c in self.historical if c["path"] == self.path or c.get("contentMatches")]
def ce_traces(self):
return bool(self.candidates or self.copies or self.in_comparison or self.strong)
def pe_module_descriptor(self):
def module_descriptor(self):
return (PurePosixPath(self.path).name == MODULE_DESCRIPTOR and not self.directory_in_ce
and not (self.candidates or self.in_comparison or self.strong))
and self.deleted is None and all(copy["similarity"] < 100 for copy in self.copies))
def decide(evidence):
row = {"path": evidence.path, "contentHash": evidence.content_hash, "currentHeader": evidence.current}
if evidence.curation is not None:
return row | curated_verdict(evidence)
if evidence.recreated:
return row | {"status": "unresolved", "expectedHeader": None,
"reason": "deleted and recreated at this path, origin unclear"}
if evidence.inherited and evidence.ce_hash is not None:
comparison = {"comparison": {"path": evidence.path, "ref": evidence.ce_ref, "blob": evidence.ce_blob}}
if evidence.pe_hash == evidence.ce_hash:
return row | verdict(evidence.current, "apache", "same path in CE, content identical") | comparison
return row | verdict(evidence.current, "ce-modified", "same path in CE, content differs") | comparison
if evidence.pe_addition and not evidence.ce_traces():
return row | verdict(evidence.current, "pe-only", "added in PE, no CE evidence")
if evidence.pe_addition and evidence.pe_module_descriptor():
return row | verdict(evidence.current, "pe-only", "build descriptor of a module that does not exist in CE")
return row | open_question(evidence)
inferred = infer(evidence)
curation = evidence.curation
if curation is None:
return row | inferred
if curation["contentHash"] != evidence.content_hash:
return row | {"status": "stale-curation", "expectedHeader": None,
"reason": "file changed since the curation, re-review and update contentHash"}
if inferred["expectedHeader"] == curation["header"]:
return row | inferred | {"redundantCuration": True}
return row | verdict(evidence.current, curation["header"], "curation: " + curation["reason"])
def infer(evidence):
if evidence.ce_versions:
versions = {"ceVersions": list(evidence.ce_versions)}
if evidence.identical is None:
return verdict(evidence.current, "ce-modified", "same path in CE, content differs") | versions
reason = ("same path in CE, content identical" if "blob" in evidence.identical
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}
if evidence.module_descriptor():
return verdict(evidence.current, NON_CE, "build descriptor of a module that does not exist in CE")
if evidence.copies:
suggested = "apache" if evidence.copies[0]["similarity"] == 100 else None
return unresolved("similar content exists in CE under another path", suggested,
copyCandidates=list(evidence.copies))
if evidence.deleted is not None:
return unresolved("CE history had this path", None, historicalCandidate=evidence.deleted)
return verdict(evidence.current, NON_CE, "not in CE, no CE evidence")
def verdict(current, expected, reason):
return {"status": "match" if current == expected else "mismatch", "expectedHeader": expected, "reason": reason}
def curated_verdict(evidence):
curation = evidence.curation
if curation["contentHash"] != evidence.content_hash:
return {"status": "stale-curation", "expectedHeader": None,
"reason": "file changed since the curation, re-review and update contentHash"}
return verdict(evidence.current, curation["header"], "curation: " + curation["reason"])
def open_question(evidence):
strong = evidence.strong
ranked = [
(evidence.candidates, "identical content exists in CE under another path", "apache"),
(evidence.copies, "similar content exists in CE under another path", None),
(strong, "CE history has this path or content", None),
(evidence.in_comparison, "present in CE, but not in the shared ancestry", None),
(True, "no CE evidence, but not proven to be added in PE", "pe-only"),
]
_, reason, suggested = next(item for item in ranked if item[0])
return {
"status": "unresolved",
"expectedHeader": None,
"suggestedHeader": suggested,
"reason": reason,
"candidates": evidence.candidates[:10],
"historicalCandidates": strong[:10],
"copyCandidates": list(evidence.copies),
"candidateCount": len(evidence.candidates),
"historicalCandidateCount": len(strong),
}
def unresolved(reason, suggested, **candidates):
return {"status": "unresolved", "expectedHeader": None, "suggestedHeader": suggested, "reason": reason} | candidates
@dataclass(frozen=True)
class Lineage:
head: str
baseline: str
anchor: str
boundary: str
ce_commits: frozenset
ce_changes: list
comparison: dict
shared: dict
pe_tree: dict
additions: dict
recreated: frozenset
bases: tuple
trees: dict
deleted: dict
@classmethod
def load(cls, repo, head, baseline):
def load(cls, repo, head, bases):
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.")
anchor = unique_base(repo, head, baseline)
ce_chain = first_parent_commits(repo, baseline)
ce_commits = frozenset(ce_chain)
if anchor not in ce_commits:
raise Failure("the shared ancestor is not on the CE ref's first-parent chain. "
"Pass the CE mainline branch that the PE branch integrates.")
boundary = integration_boundary(repo, anchor, head)
shared = tree(repo, anchor)
additions = {}
for change in history(repo, head, "--diff-filter=A"):
additions.setdefault(change.path, change.commit)
ce_changes = history(repo, baseline)
divergent = frozenset(ce_chain[:ce_chain.index(anchor)])
divergence = (history(repo, f"{boundary}..{head}")
+ [change for change in ce_changes if change.commit in divergent])
return cls(
head=head,
baseline=baseline,
anchor=anchor,
boundary=boundary,
ce_commits=ce_commits,
ce_changes=ce_changes,
comparison=tree(repo, baseline),
shared=shared,
pe_tree=tree(repo, head),
additions=additions,
recreated=frozenset(change.path for change in divergence
if change.status in {"A", "D"} and change.path in shared),
)
def unmatched(self, names):
return {name for name in names
if name not in self.shared or name not in self.comparison or name in self.recreated}
def pe_addition(self, name):
if name not in self.pe_tree:
return True
return name in self.additions and self.additions[name] not in self.ce_commits
def added_by(self, name):
if name not in self.pe_tree:
return self.additions.get(name, "working-tree addition")
return self.additions.get(name)
def historical_versions(ce_changes, unmatched):
basenames = {PurePosixPath(name).name for name in unmatched}
versions = {}
for change in ce_changes:
if change.path not in unmatched and PurePosixPath(change.path).name not in basenames:
continue
oid = change.old if change.deleted else change.new
if set(oid) == {"0"}:
continue
versions.setdefault((change.path, oid), change.commit + "^1" if change.deleted else change.commit)
return versions
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})
return cls(head=head, bases=tuple(bases), trees={base: tree(repo, base) for base in bases}, deleted=deleted)
def versions(self, name):
return [(base, files[name]) for base, files in self.trees.items() if name in files]
def comparable_ce_files(comparison, names):
@ -909,108 +840,114 @@ def comparable_ce_files(comparison, names):
class Comparison:
lineage: Lineage
contents: dict
unmatched: set
headers: dict
normalized: dict
nonempty: set
copies: dict
exact_index: dict
historic_index: dict
merges: dict
ce_directories: frozenset
def classify(self, name, curation):
key = ("pe", name)
lineage = self.lineage
unmatched = name in self.unmatched
historic = self.historical_candidates(name) if unmatched else []
evidence = Evidence(
key = ("head", name)
versions = self.lineage.versions(name)
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))
copies = sorted(self.copies.get(name, []), key=lambda copy: (-copy["similarity"], copy["path"]))
return decide(Evidence(
path=name,
content_hash=raw_hash(self.contents[name]),
current=self.headers[key],
curation=curation,
inherited=name in lineage.shared,
recreated=name in lineage.recreated,
ce_hash=self.normalized.get((name, lineage.comparison.get(name))),
pe_hash=self.normalized[key],
candidates=self.exact_index.get(self.normalized[key], []) if unmatched else [],
historical=historic,
in_comparison=name in lineage.comparison,
pe_addition=lineage.pe_addition(name),
copies=self.copies.get(name, []),
ce_versions=tuple({"path": name, "ref": base, "blob": oid} for base, oid in versions),
identical=identical,
copies=tuple(copies),
deleted=self.lineage.deleted.get(name),
directory_in_ce=str(PurePosixPath(name).parent) in self.ce_directories,
ce_ref=lineage.baseline,
ce_blob=lineage.comparison.get(name),
)
row = decide(evidence)
if unmatched:
row["peAddition"] = lineage.added_by(name)
row["basenameHintCount"] = len(historic) - len(evidence.strong)
return row
def historical_candidates(self, name):
key = ("pe", name)
candidates = []
for version in self.historic_index.get(PurePosixPath(name).name, []):
matches = (key in self.nonempty
and self.normalized[key] == self.normalized[(version["path"], version["blob"])])
candidates.append(version | {"contentMatches": matches})
candidates.sort(key=lambda candidate: (not candidate["contentMatches"], candidate["path"] != name))
return candidates
))
def compare(repo, plugin, lineage, contents):
names = list(contents)
unmatched = lineage.unmatched(names)
versions = historical_versions(lineage.ce_changes, unmatched)
counterparts = comparable_ce_files(lineage.comparison, names)
source_refs = versions | {key: lineage.baseline for key in counterparts.items()}
bytes_by_id = blobs(repo, [oid for _, oid in source_refs])
new_paths = {name for name in names if not lineage.versions(name)}
sources = {}
for base, files in lineage.trees.items():
for name in names:
if name in files:
sources.setdefault((name, files[name]), base)
for key in comparable_ce_files(files, new_paths).items():
sources.setdefault(key, base)
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(("pe", name), name, content)
for path, oid in sorted(source_refs):
mycila.add(("head", name), name, content)
for path, oid in sorted(sources):
mycila.add((path, oid), path, bytes_by_id[oid])
console.begin("Recognizing headers")
recognized = mycila.current_headers([("pe", name) for name in names])
recognized = mycila.current_headers([("head", name) for name in names])
console.end()
console.begin("Comparing against CE")
normalized = mycila.strip_headers()
headers = mycila.header_states(recognized)
nonempty = mycila.nonempty()
copies = normalized_copies(mycila, source_refs, unmatched, nonempty)
exact_index = defaultdict(list)
for path, oid in counterparts.items():
if (path, oid) in nonempty:
exact_index[normalized[(path, oid)]].append({"path": path, "ref": lineage.baseline, "blob": oid})
historic_index = defaultdict(list)
for (path, oid), ref in versions.items():
historic_index[PurePosixPath(path).name].append({"path": path, "ref": ref, "blob": oid})
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)")
return Comparison(
lineage=lineage,
contents=contents,
unmatched=unmatched,
headers=headers,
normalized=normalized,
nonempty=nonempty,
copies=copies,
exact_index=dict(exact_index),
historic_index=dict(historic_index),
ce_directories=frozenset(str(parent) for path in lineage.comparison for parent in PurePosixPath(path).parents),
merges=merges,
ce_directories=frozenset(str(parent) for files in lineage.trees.values()
for path in files for parent in PurePosixPath(path).parents),
)
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:
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]})
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()
result = {}
for key, (_, description) in merged.items():
if hashes[key] == normalized[("head", key[0])]:
result.setdefault(key[0], description)
return result
def current_branch(repo):
branch = git(repo, "rev-parse", "--abbrev-ref", "HEAD").decode().strip()
return "" if branch == "HEAD" else branch
def print_banner(repo, head, ce_remote, ce_ref, baseline):
def print_banner(repo, head, ce):
console.line("License header provenance check")
console.line(f" PE head {head[:11]} {current_branch(repo)}".rstrip())
console.line(f" CE remote {ce_remote}")
console.line(f" CE ref {ce_ref}" + (f" → {baseline[:11]}" if baseline != ce_ref else ""))
console.line(f" HEAD {head[:11]} {current_branch(repo)}".rstrip())
if "ref" in ce:
console.line(f" CE remote {ce['remote']}")
console.line(f" CE ref {ce['ref']}" + (f" → {ce['commit'][:11]}" if ce["commit"] != ce["ref"] else ""))
else:
console.line(f" CE commits without the relicensing commit {ce['relicensingCommit'][:11]} in their history")
console.line()
@ -1039,16 +976,15 @@ def describe_mismatch(row):
def describe_unresolved(row, ref_names):
hint = f" (hint: {row['suggestedHeader']})" if row.get("suggestedHeader") else ""
details = [f"has {header_name(row['currentHeader'])}, no expected header yet{hint}"]
evidence = ([("exact CE match", candidate) for candidate in row.get("candidates", [])]
+ [(f"similar CE file ({candidate['similarity']}%)", candidate)
for candidate in row.get("copyCandidates", [])]
+ [("CE history", candidate) for candidate in row.get("historicalCandidates", [])])
evidence = [(f"similar CE file ({candidate['similarity']}%)", candidate)
for candidate in row.get("copyCandidates", [])]
if "historicalCandidate" in row:
evidence.append(("CE history", row["historicalCandidate"]))
if not evidence:
return details + [row["reason"]]
label, candidate = evidence[0]
details.append(f"{label}: {candidate['path']} at {ref_name(candidate['ref'], ref_names)}")
others = (row.get("candidateCount", 0) + len(row.get("copyCandidates", []))
+ row.get("historicalCandidateCount", 0) - 1)
others = len(evidence) - 1
if others > 0:
details.append(f"another {others} candidate{'s' if others != 1 else ''} in the report")
return details
@ -1058,8 +994,12 @@ def describe_stale(row):
return [row["reason"]]
def print_group(title, rows, describe, hint):
console.line(f"{title} ({len(rows)})", "red")
def describe_redundant(row):
return [f"curated {row['expectedHeader']}, the check decides {row['expectedHeader']} by itself"]
def print_group(title, rows, describe, hint, style="red"):
console.line(f"{title} ({len(rows)})", style)
for row in rows:
console.line(f" {row['path']}")
for detail in describe(row):
@ -1084,6 +1024,16 @@ def print_restamped(rows):
console.line()
def print_removed_curations(removed):
if not removed:
return
console.line(f"Removed curations ({len(removed)})", "green")
for entry in removed:
console.line(f" {entry['path']}")
console.line(f" {entry['reason']}")
console.line()
def print_findings(rows, curation_issues, ref_names):
mismatches = [row for row in rows if row["status"] == "mismatch"]
unresolved = [row for row in rows if row["status"] == "unresolved"]
@ -1096,7 +1046,14 @@ def print_findings(rows, curation_issues, ref_names):
print_group("Needs a decision", unresolved, lambda row: describe_unresolved(row, ref_names),
f"Decide the origin and add a curation, see {README}")
if stale:
print_group("Stale curations", stale, describe_stale, f"Remove or update the entry in {CURATIONS}")
hint = (f"Review the file and update the entry in {CURATIONS}; --fix removes entries of files no longer in scope"
if any(row["status"] == "stale-curation" and "contentHash" in row for row in stale)
else "Rerun with --fix to remove them")
print_group("Stale curations", stale, describe_stale, hint)
redundant = [row for row in rows if row.get("redundantCuration")]
if redundant:
print_group("Redundant curations", redundant, describe_redundant,
f"Rerun with --fix to remove them from {CURATIONS}", style=None)
def print_summary(rows, curation_issues, report):
@ -1145,8 +1102,8 @@ def restamp(repo, plugin, rows, contents):
templates = {header: template_lines(content) for header, content in mycila.templates.items()}
for name, header in current.items():
if header not in TEMPLATES:
expected[("pe", name)] = wanted[name]
mycila.add(("pe", name), name, contents[name])
expected[("head", name)] = wanted[name]
mycila.add(("head", name), name, contents[name])
continue
try:
stamped[name] = swap_header(contents[name], templates[header], templates[wanted[name]])
@ -1157,9 +1114,9 @@ def restamp(repo, plugin, rows, contents):
stamped |= {key[1]: content for key, content in results.items()}
skipped |= {key[1]: reason for key, reason in rejected.items()}
for name, content in stamped.items():
if ("pe", name) not in mycila.paths:
mycila.add(("pe", name), name, content)
headers = mycila.current_headers([("pe", name) for name in stamped])
if ("head", name) not in mycila.paths:
mycila.add(("head", name), name, content)
headers = mycila.current_headers([("head", name) for name in stamped])
wrong = sorted(key[1] for key, header in headers.items() if header != wanted[key[1]])
if wrong:
raise Failure(f"Restamping did not produce the expected header: {wrong[:20]}")
@ -1174,13 +1131,32 @@ def restamp(repo, plugin, rows, contents):
console.end(f"{len(stamped)} files" + (f", {len(skipped)} skipped" if skipped else ""))
def prune_curations(path, rows, orphaned):
obsolete = {row["path"]: "the check decides the same header by itself" for row in rows if row.get("redundantCuration")}
obsolete |= {row["path"]: row["reason"] for row in orphaned}
if not obsolete:
return []
data = json.loads(path.read_text(encoding="utf-8"))
data["curations"] = [entry for entry in data["curations"] if entry["path"] not in obsolete]
path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
for row in rows:
row.pop("redundantCuration", None)
return [{"path": name, "reason": reason} for name, reason in sorted(obsolete.items())]
def check(args):
repo = repository_root()
head = resolve(repo, "HEAD")
console.begin(f"Fetching {args.ce_ref} from {args.ce_remote}")
baseline = fetch(repo, args.ce_remote, args.ce_ref)
console.end()
print_banner(repo, head, args.ce_remote, args.ce_ref, baseline)
if args.ce_ref:
console.begin(f"Fetching {args.ce_ref} from {args.ce_remote}")
baseline = fetch(repo, args.ce_remote, args.ce_ref)
console.end()
ce = {"remote": args.ce_remote, "ref": args.ce_ref, "commit": baseline}
ref_names = {baseline: args.ce_ref}
else:
ce = {"relicensingCommit": RELICENSING_COMMIT}
ref_names = {}
print_banner(repo, head, ce)
destination = report_destination(repo, args.output)
plugin = read_plugin(repo)
reject_module_overrides(repo)
@ -1188,8 +1164,9 @@ def check(args):
curation_bytes = curation_path.read_bytes()
curations = load_curations(curation_path)
console.begin("Resolving Git history")
lineage = Lineage.load(repo, head, baseline)
console.end()
bases = merged_ce_bases(repo, head, ce["commit"]) if "ref" in ce else relicensed_ce_bases(repo, head)
lineage = Lineage.load(repo, head, bases)
console.end("done (CE base " + ", ".join(ref_name(base, ref_names) for base in bases) + ")")
console.begin("Collecting Mycila scope")
scope = discover_scope(repo, plugin)
console.end(f"{len(scope.eligible)} files ({scope.ignored} Git-ignored skipped)")
@ -1200,19 +1177,21 @@ def check(args):
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)
removed = []
if args.fix:
restamp(repo, plugin, rows, contents)
removed = prune_curations(curation_path, rows, orphaned)
orphaned = []
summary = Counter(row["status"] for row in rows)
result = {
"schemaVersion": 1,
"peHead": lineage.head,
"ceComparison": {"remote": args.ce_remote, "input": args.ce_ref, "commit": lineage.baseline},
"ceHistory": {"tip": lineage.baseline, "firstParent": True},
"sharedAncestor": lineage.anchor,
"peIntegrationBoundary": lineage.boundary,
"schemaVersion": 2,
"head": lineage.head,
"ce": ce | {"bases": list(lineage.bases)},
"scope": {"supported": len(scope.eligible), "unknown": scope.unknown, "modules": scope.modules},
"summary": dict(summary),
"restamped": sorted(row["path"] for row in rows if "previousHeader" in row),
"removedCurations": removed,
"redundantCurations": sorted(row["path"] for row in rows if row.get("redundantCuration")),
"curationIssues": orphaned,
"files": rows,
}
@ -1220,7 +1199,8 @@ def check(args):
destination.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
report = destination.relative_to(repo) if destination.is_relative_to(repo) else destination
print_restamped(rows)
print_findings(rows, orphaned, {baseline: args.ce_ref})
print_removed_curations(removed)
print_findings(rows, orphaned, ref_names)
print_summary(rows, orphaned, report)
return 1 if orphaned or summary.keys() - {"match"} else 0
@ -1228,14 +1208,15 @@ def check(args):
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["check"])
parser.add_argument("--ce-ref", required=True,
help="CE tree and first-parent history to check against; a branch, tag, or commit "
"of the CE repository, fetched from --ce-remote on every run")
parser.add_argument("--ce-ref",
help="CE branch, tag, or commit that this branch integrates, fetched from --ce-remote; "
"without it, CE is the history 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("--output", default="target/license-provenance/report.json")
parser.add_argument("--fix", action="store_true",
help="restamp files whose expected header the check determined; unrecognized headers are kept")
help="restamp files whose expected header the check determined and remove redundant or "
"orphaned curations; unrecognized headers are kept")
args = parser.parse_args(argv)
try:
return check(args)

546
tools/src/main/python/license-headers/curations.json

File diff suppressed because it is too large

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

@ -54,72 +54,91 @@ class GitFixture:
class DecisionTests(unittest.TestCase):
VERSION = {"path": "a.java", "ref": "b" * 40, "blob": "c" * 40}
COPY = {"path": "source.java", "ref": "a" * 40, "blob": "c" * 40, "similarity": 78}
def decide(self, **changes):
evidence = dict(path="a.java", content_hash=p.raw_hash(b"reviewed"), current="pe-only", curation=None,
inherited=True, recreated=False, ce_hash="same", pe_hash="same",
candidates=[], historical=[], in_comparison=True)
evidence = dict(path="a.java", content_hash=p.raw_hash(b"reviewed"), current=p.NON_CE,
ce_versions=(self.VERSION,), identical=self.VERSION)
return p.decide(p.Evidence(**(evidence | changes)))
def new(self, **changes):
return self.decide(**(dict(ce_versions=(), identical=None) | changes))
def test_current_header_does_not_establish_origin(self):
row = self.decide()
self.assertEqual("apache", row["expectedHeader"])
self.assertEqual("mismatch", row["status"])
self.assertEqual("ce-modified", self.decide(pe_hash="changed")["expectedHeader"])
self.assertEqual(("mismatch", "apache"), (row["status"], row["expectedHeader"]))
self.assertEqual(self.VERSION, row["identicalTo"])
row = self.decide(identical=None)
self.assertEqual(("ce-modified", "same path in CE, content differs"), (row["expectedHeader"], row["reason"]))
self.assertEqual([self.VERSION], row["ceVersions"])
def test_clean_merge_of_ce_versions_is_apache(self):
merge = {"path": "a.java", "merge": ["b" * 40, "d" * 40], "base": "e" * 40}
row = self.decide(current="apache", identical=merge)
self.assertEqual(("match", "apache"), (row["status"], row["expectedHeader"]))
self.assertEqual("same path in CE, content identical to a clean merge of its CE versions", row["reason"])
self.assertEqual(merge, row["identicalTo"])
def test_new_path_without_ce_evidence_is_non_ce(self):
row = self.new()
self.assertEqual(("match", p.NON_CE, "not in CE, no CE evidence"),
(row["status"], row["expectedHeader"], row["reason"]))
def test_ce_evidence_for_a_new_path_needs_a_decision(self):
row = self.new(copies=(self.COPY,))
self.assertEqual(("unresolved", None, None), (row["status"], row["expectedHeader"], row["suggestedHeader"]))
self.assertEqual([self.COPY], row["copyCandidates"])
self.assertEqual("apache", self.new(copies=(self.COPY | {"similarity": 100},))["suggestedHeader"])
deleted = {"path": "a.java", "ref": "f" * 40 + "^1", "blob": "c" * 40}
row = self.new(deleted=deleted)
self.assertEqual(("unresolved", "CE history had this path"), (row["status"], row["reason"]))
self.assertEqual(deleted, row["historicalCandidate"])
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"}
descriptor = dict(path="integration/mqtt/pom.xml", copies=(copy,), directory_in_ce=False)
row = self.new(**descriptor)
self.assertEqual(("match", p.NON_CE), (row["status"], row["expectedHeader"]))
for evidence in (dict(directory_in_ce=True),
dict(path="integration/mqtt/Mqtt.java"),
dict(copies=(copy | {"similarity": 100},)),
dict(deleted={"path": "integration/mqtt/pom.xml", "ref": "f" * 40, "blob": "c" * 40})):
self.assertEqual("unresolved", self.new(**(descriptor | evidence))["status"], evidence)
def test_matching_curation_precedes_inference(self):
curation = dict(contentHash=p.raw_hash(b"reviewed"), header="pe-only", reason="Independent replacement")
self.assertEqual("match", self.decide(curation=curation)["status"])
curation = dict(contentHash=p.raw_hash(b"reviewed"), header="ce-modified", reason="Reviewed")
row = self.decide(current="ce-modified", curation=curation)
self.assertEqual(("match", "ce-modified", "curation: Reviewed"),
(row["status"], row["expectedHeader"], row["reason"]))
self.assertNotIn("redundantCuration", row)
row = self.new(copies=(self.COPY,), curation=curation | {"header": p.NON_CE})
self.assertEqual(("match", p.NON_CE), (row["status"], row["expectedHeader"]))
self.assertNotIn("redundantCuration", row)
curation["contentHash"] = p.raw_hash(b"different")
self.assertEqual("stale-curation", self.decide(curation=curation)["status"])
def test_recreated_and_missing_ce_files_do_not_silently_pass(self):
self.assertEqual("unresolved", self.decide(recreated=True)["status"])
row = self.decide(inherited=False, in_comparison=False, ce_hash=None)
self.assertEqual("unresolved", row["status"])
self.assertEqual("pe-only", row["suggestedHeader"])
self.assertIsNone(row["expectedHeader"])
def test_identical_cross_path_source_is_not_proof(self):
row = self.decide(inherited=False, candidates=[{"path": "original.java"}])
self.assertEqual("unresolved", row["status"])
self.assertEqual("apache", row["suggestedHeader"])
def test_pe_additions_pass_without_strong_ce_evidence(self):
added = dict(inherited=False, in_comparison=False, ce_hash=None, pe_addition=True)
self.assertEqual("match", self.decide(**added)["status"])
self.assertEqual("match", self.decide(**added, historical=[{"path": "other/a.java"}])["status"])
for evidence in (dict(historical=[{"path": "a.java"}]),
dict(historical=[{"path": "other/a.java", "contentMatches": True}]),
dict(copies=[{"path": "other.java", "similarity": 78}])):
self.assertEqual("unresolved", self.decide(**added, **evidence)["status"])
def test_descriptor_of_a_module_absent_in_ce_is_pe_only_despite_similar_ce_descriptors(self):
descriptor = dict(path="integration/mqtt/pom.xml", inherited=False, in_comparison=False, ce_hash=None,
pe_addition=True, copies=[{"path": "transport/mqtt/pom.xml", "similarity": 78}],
directory_in_ce=False)
row = self.decide(**descriptor)
self.assertEqual("match", row["status"])
self.assertEqual("pe-only", row["expectedHeader"])
for evidence in (dict(directory_in_ce=True),
dict(path="integration/mqtt/Mqtt.java"),
dict(pe_addition=False),
dict(candidates=[{"path": "transport/mqtt/pom.xml"}]),
dict(historical=[{"path": "transport/mqtt/pom.xml", "contentMatches": True}])):
self.assertEqual("unresolved", self.decide(**(descriptor | evidence))["status"])
def test_curation_that_repeats_the_inferred_header_is_redundant(self):
curation = dict(contentHash=p.raw_hash(b"reviewed"), header="apache", reason="Reviewed")
row = self.decide(current="apache", curation=curation)
self.assertEqual(("match", "apache", "same path in CE, content identical", True),
(row["status"], row["expectedHeader"], row["reason"], row["redundantCuration"]))
row = self.new(curation=curation | {"header": p.NON_CE})
self.assertTrue(row["redundantCuration"])
def test_console_groups_findings_by_required_action(self):
missing = self.decide(current=p.MISSING)
foreign = self.decide(path="vendored.java", current=p.FOREIGN)
candidate = {"path": "original.java", "ref": "b" * 40, "blob": "c" * 40}
renamed = self.decide(path="new.java", inherited=False, candidates=[candidate, candidate])
copied = self.decide(path="copied.java", inherited=False, in_comparison=False, ce_hash=None,
copies=[{"path": "source.java", "ref": "a" * 40, "similarity": 78}])
changed = self.decide(curation=dict(contentHash=p.raw_hash(b"other"), header="pe-only", reason="Reviewed"))
copied = self.new(path="copied.java", copies=(self.COPY, self.COPY | {"path": "other.java", "similarity": 60}))
historical = self.new(path="gone.java", deleted={"path": "gone.java", "ref": "d" * 40 + "^1", "blob": "c" * 40})
changed = self.decide(curation=dict(contentHash=p.raw_hash(b"other"), header=p.NON_CE, reason="Reviewed"))
clean = self.decide(path="clean.java", current="apache")
redundant = self.decide(path="curated.java", current="apache",
curation=dict(contentHash=p.raw_hash(b"reviewed"), header="apache", reason="Reviewed"))
orphaned = dict(path="deleted.java", status="stale-curation", reason="file is no longer in scope")
stderr, stdout = io.StringIO(), io.StringIO()
with redirect_stderr(stderr), redirect_stdout(stdout):
rows = [missing, foreign, renamed, copied, changed, clean]
rows = [missing, foreign, copied, historical, changed, clean, redundant]
p.print_findings(rows, [orphaned], {"a" * 40: "ce/lts-4.2"})
p.print_summary(rows, [orphaned], "target/report.json")
output = stderr.getvalue()
@ -135,13 +154,13 @@ class DecisionTests(unittest.TestCase):
→ Rerun with --fix to restamp automatically
Needs a decision (2)
new.java
has pe-only, no expected header yet (hint: apache)
exact CE match: original.java at {"b" * 11}
another 1 candidate in the report
copied.java
has pe-only, no expected header yet
has {p.NON_CE}, no expected header yet
similar CE file (78%): source.java at ce/lts-4.2
another 1 candidate in the report
gone.java
has {p.NON_CE}, no expected header yet
CE history: gone.java at {"d" * 11}^1
→ Decide the origin and add a curation, see {p.README}
Stale curations (2)
@ -149,12 +168,31 @@ class DecisionTests(unittest.TestCase):
file changed since the curation, re-review and update contentHash
deleted.java
file is no longer in scope
→ Remove or update the entry in {p.CURATIONS}
→ Review the file and update the entry in {p.CURATIONS}; --fix removes entries of files no longer in scope
6 findings in 6 files. Report: target/report.json
Redundant curations (1)
curated.java
curated apache, the check decides apache by itself
→ Rerun with --fix to remove them from {p.CURATIONS}
6 findings in 7 files. Report: target/report.json
"""), output)
self.assertEqual("", stdout.getvalue())
def test_orphaned_curations_alone_point_to_fix(self):
orphaned = dict(path="deleted.java", status="stale-curation", reason="file is no longer in scope")
stderr = io.StringIO()
with redirect_stderr(stderr):
p.print_findings([self.decide(current="apache")], [orphaned], {})
self.assertIn(" → Rerun with --fix to remove them\n", stderr.getvalue())
def test_console_lists_removed_curations(self):
stderr = io.StringIO()
with redirect_stderr(stderr):
p.print_removed_curations([{"path": "a.java", "reason": "file is no longer in scope"}])
p.print_removed_curations([])
self.assertEqual("Removed curations (1)\n a.java\n file is no longer in scope\n\n", stderr.getvalue())
def test_console_closes_an_interrupted_phase_before_reporting(self):
stderr = io.StringIO()
with redirect_stderr(stderr):
@ -164,7 +202,7 @@ class DecisionTests(unittest.TestCase):
self.assertEqual("Resolving Git history ... failed\n\nError: boom\n", stderr.getvalue())
def test_console_summarizes_a_clean_run(self):
rows = [self.decide(current="apache"), self.decide(path="b.java", pe_hash="changed", current="ce-modified")]
rows = [self.decide(current="apache"), self.decide(path="b.java", identical=None, current="ce-modified")]
stderr = io.StringIO()
with redirect_stderr(stderr):
p.print_restamped(rows)
@ -173,7 +211,7 @@ class DecisionTests(unittest.TestCase):
"Report: target/report.json\n", stderr.getvalue())
def test_console_lists_restamped_files(self):
rows = [self.decide(current="apache"), self.decide(path="b.java", pe_hash="changed", current="ce-modified")]
rows = [self.decide(current="apache"), self.decide(path="b.java", identical=None, current="ce-modified")]
rows[1]["previousHeader"] = p.LEGACY
stderr = io.StringIO()
with redirect_stderr(stderr):
@ -297,11 +335,26 @@ class InputTests(unittest.TestCase):
write([entry])
self.assertEqual({"a.java"}, set(p.load_curations(path)))
for entries in ([entry, entry], [entry | {"reason": " "}],
[entry | {"path": "../a.java"}], [entry | {"header": "MIT"}]):
[entry | {"path": "../a.java"}], [entry | {"header": "MIT"}],
[entry | {"header": "pe-only"}]):
write(entries)
with self.assertRaises(p.Failure):
p.load_curations(path)
def test_non_ce_header_is_the_only_other_template(self):
directory = temporary_directory(self)
for name in ("license-header.txt", "license-header-ce-modified.txt", "notes.txt"):
(directory / name).write_text("header\n")
with self.assertRaises(RuntimeError):
p.non_ce_header(directory)
(directory / "license-header-busl.txt").write_text("header\n")
self.assertEqual("busl", p.non_ce_header(directory))
(directory / "license-header-pe.txt").write_text("header\n")
with self.assertRaises(RuntimeError):
p.non_ce_header(directory)
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_plugin_version_and_configuration_come_from_root_pom(self):
repo = temporary_directory(self)
p.git(repo, "init")
@ -341,33 +394,105 @@ class GitHistoryTests(unittest.TestCase):
self.assertEqual({initial, merged}, {change.commit for change in changes})
self.assertEqual(source, changes[0].path)
git("checkout", "side")
git.write("side-only.java", "not integrated\n")
git.commit("side only")
git("checkout", "lts-4.2")
self.assertNotIn("side-only.java", {change.path for change in p.history(git.root, "HEAD")})
git("rm", source)
git.commit("delete")
deleted = p.history(git.root, "HEAD")[0]
self.assertTrue(deleted.deleted)
self.assertEqual(b"merged result\n", p.blobs(git.root, [deleted.old])[deleted.old])
def test_integration_boundary_does_not_walk_preintegration_pe_history(self):
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])
def relicensed_fixture(self):
git = GitFixture(temporary_directory(self), "master")
git.write("Base.java", "base\n")
git.commit("CE base")
git("checkout", "-b", "lts-4.3")
git.write("Fix.java", "lts fix\n")
fix = git.commit("CE fix")
git("checkout", "master")
git.write("Feature.java", "CE feature\n")
last = git.commit("last Apache commit")
git.write("Tb.java", "TB feature\n")
relicensing = git.commit("relicensing")
git("merge", "--no-ff", "lts-4.3", "-m", "integrate CE fix")
return git, fix, last, relicensing
def test_relicensed_ce_bases_are_the_latest_ce_commits_merged_into_the_branch(self):
git, fix, last, relicensing = self.relicensed_fixture()
with patch.object(p, "RELICENSING_COMMIT", relicensing):
self.assertEqual(sorted([fix, last]), p.relicensed_ce_bases(git.root, git("rev-parse", "HEAD")))
git("checkout", "lts-4.3")
git.write("Fix.java", "second lts fix\n")
second = git.commit("second CE fix")
git("checkout", "master")
self.assertEqual(sorted([fix, last]), p.relicensed_ce_bases(git.root, git("rev-parse", "HEAD")))
git("merge", "--no-ff", "lts-4.3", "-m", "integrate second CE fix")
self.assertEqual(sorted([second, last]), p.relicensed_ce_bases(git.root, git("rev-parse", "HEAD")))
self.assertEqual([last], p.relicensed_ce_bases(git.root, relicensing))
def test_relicensed_ce_bases_need_the_relicensing_commit_in_history(self):
git, _, _, relicensing = self.relicensed_fixture()
with patch.object(p, "RELICENSING_COMMIT", relicensing), self.assertRaisesRegex(p.Failure, "Pass --ce-ref"):
p.relicensed_ce_bases(git.root, git("rev-parse", "lts-4.3"))
with patch.object(p, "RELICENSING_COMMIT", "0" * 40), self.assertRaisesRegex(p.Failure, "Pass --ce-ref"):
p.relicensed_ce_bases(git.root, git("rev-parse", "HEAD"))
def test_merged_ce_bases_follow_the_integrated_ce_commit(self):
git = GitFixture(temporary_directory(self), "ce")
git.write("initial", "initial")
git.commit("initial")
git("branch", "pe")
git.write("ce-file", "CE")
anchor = git.commit("CE addition")
git("checkout", "pe")
git.write("pe-file", "PE")
git.commit("PE addition")
git("merge", "ce", "-m", "CE integration")
boundary = git("rev-parse", "HEAD")
git.write("pe-file", "PE edit")
git.commit("PE edit")
self.assertEqual(boundary, p.integration_boundary(git.root, anchor, "HEAD"))
git.write("Base.java", "base\n")
git.commit("CE base")
git("checkout", "-b", "integrating")
git.write("Own.java", "own\n")
git.commit("own addition")
git("checkout", "ce")
git.write("Base.java", "CE fix\n")
integrated = git.commit("CE fix")
git("checkout", "integrating")
git("merge", "--no-ff", "ce", "-m", "integrate CE")
git("checkout", "ce")
git.write("Base.java", "later CE fix\n")
tip = git.commit("not yet integrated")
self.assertEqual([integrated], p.merged_ce_bases(git.root, git("rev-parse", "integrating"), tip))
git("checkout", "--orphan", "unrelated")
git.write("Other.java", "other\n")
unrelated = git.commit("unrelated history")
with self.assertRaisesRegex(p.Failure, "shares no history"):
p.merged_ce_bases(git.root, unrelated, tip)
def test_lineage_records_first_parent_ce_deletions(self):
git = GitFixture(temporary_directory(self), "ce")
git.write("Gone.java", "removed from CE\n")
git.write("Kept.java", "kept\n")
git.commit("CE base")
git("checkout", "-b", "side")
git.write("Temporary.java", "never on the mainline\n")
git.commit("side addition")
git("rm", "Temporary.java")
git.commit("side removal")
git("checkout", "ce")
git("merge", "--no-ff", "side", "-m", "integrate side")
git("rm", "Gone.java")
removal = git.commit("CE removal")
lineage = p.Lineage.load(git.root, removal, [removal])
self.assertEqual({"Gone.java"}, set(lineage.deleted))
self.assertEqual(removal + "^1", lineage.deleted["Gone.java"]["ref"])
self.assertEqual(b"removed from CE\n", p.blobs(git.root, [lineage.deleted["Gone.java"]["blob"]])
[lineage.deleted["Gone.java"]["blob"]])
self.assertEqual([(removal, git("rev-parse", f"{removal}:Kept.java"))], lineage.versions("Kept.java"))
self.assertEqual([], lineage.versions("Gone.java"))
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")
git.commit("base")
base = git("rev-parse", "HEAD:File.java")
def blob(content):
git.write("File.java", content)
git.commit(content.splitlines()[0])
return git("rev-parse", "HEAD:File.java")
ours, theirs = blob("ONE\ntwo\nthree\nfour\nfive\n"), blob("one\ntwo\nthree\nfour\nFIVE\n")
self.assertEqual(b"ONE\ntwo\nthree\nfour\nFIVE\n", p.merge_blobs(git.root, ours, base, theirs))
self.assertIsNone(p.merge_blobs(git.root, ours, base, blob("uno\ntwo\nthree\nfour\nfive\n")))
def test_ignore_filter_keeps_tracked_and_unignored_files(self):
repo = temporary_directory(self)
@ -393,10 +518,10 @@ class GitHistoryTests(unittest.TestCase):
original = b"class Source {\n" + b" void action() { doUsefulWork(); }\n" * 20 + b"}\n"
tool.add(source, "Source.java", original)
tool.add(empty, "Empty.java", b"\n")
tool.add(("pe", "Renamed.java"), "Renamed.java",
tool.add(("head", "Renamed.java"), "Renamed.java",
original.replace(b"Source", b"Renamed").replace(b"\n", b"\r\n"))
tool.add(("pe", "Other.java"), "Other.java", b"independent PE implementation\n")
tool.add(("pe", "Blank.java"), "Blank.java", b"\r\n")
tool.add(("head", "Other.java"), "Other.java", b"independent implementation\n")
tool.add(("head", "Blank.java"), "Blank.java", b"\r\n")
found = p.normalized_copies(tool, {source: "selected-mainline", empty: "selected-mainline"},
["Renamed.java", "Other.java", "Blank.java"], tool.nonempty())
self.assertEqual({"Renamed.java"}, set(found))
@ -412,19 +537,19 @@ class FetchTests(unittest.TestCase):
self.ce("tag", "-a", "v4.2.0", "-m", "release")
self.ce.write("Base.java", "second\n")
self.second = self.ce.commit("second")
self.pe = GitFixture(temporary_directory(self), "pe")
self.pe.write("Pe.java", "pe\n")
self.pe.commit("pe base")
self.local = GitFixture(temporary_directory(self), "main")
self.local.write("Own.java", "own\n")
self.local.commit("own base")
def fetch(self, ref):
return p.fetch(self.pe.root, str(self.ce.root), ref)
return p.fetch(self.local.root, str(self.ce.root), ref)
def test_fetches_branches_tags_and_commits(self):
self.assertEqual(self.second, self.fetch("lts-4.2"))
self.assertEqual(self.second, self.fetch("refs/heads/lts-4.2"))
self.assertEqual(self.first, self.fetch("v4.2.0"))
self.assertEqual(self.first, self.fetch(self.first))
self.assertEqual("second", self.pe("show", f"{self.second}:Base.java"))
self.assertEqual("second", self.local("show", f"{self.second}:Base.java"))
def test_every_run_fetches_the_current_tip(self):
self.assertEqual(self.second, self.fetch("lts-4.2"))
@ -440,33 +565,39 @@ class FetchTests(unittest.TestCase):
class CheckCommandTests(unittest.TestCase):
LINES = "".join(f"line {index}\n" for index in range(10))
def setUp(self):
self.repo = temporary_directory(self)
self.git = git = GitFixture(self.repo, "lts-4.2")
self.body = "new CE feature implementation\n" * 20
git.write("Base.java", "base implementation\n")
git.commit("release base")
git("branch", "pe")
git("checkout", "-b", "fix/my-fix")
git.write("Feature.java", self.body)
git.write("Deleted.java", "historical CE feature source\n")
git.commit("CE fix sources")
git("rm", "Deleted.java")
self.feature = git.commit("remove temporary source")
git("checkout", "-b", "unrelated", "lts-4.2")
git.write("Unrelated.java", "unrelated source\n")
git.commit("unrelated source")
git("checkout", "pe")
git.write("Renamed.java", fixture("pe-only") + self.body)
git.write("Deleted.java", fixture("pe-only") + "historical CE feature source\n")
git.write("Local.java", fixture("pe-only") + "unrelated source\n")
git.write("Swapped.java", fixture("apache") + "swapped source\n")
self.git = git = GitFixture(self.repo, "master")
self.body = "CE source implementation\n" * 20
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": []}')
git.write("Base.java", fixture("apache") + "base implementation\n")
git.write("Changed.java", fixture("apache") + "CE implementation\n")
git.write("Merged.java", fixture("apache") + self.LINES)
git.write("Source.java", fixture("apache") + self.body)
self.base = git.commit("CE base")
git("checkout", "-b", "lts-4.3")
git.write("Merged.java", fixture("apache") + self.LINES.replace("line 9", "lts fix"))
git.write("Fixed.java", fixture("apache") + "lts addition\n")
self.fix = git.commit("CE fix")
git("checkout", "master")
git.write("Deleted.java", fixture("apache") + "removed CE source\n")
self.addition = git.commit("CE addition")
git.write("Merged.java", fixture("apache") + self.LINES.replace("line 0", "master change"))
git("rm", "-q", "Deleted.java")
self.last = git.commit("last Apache commit")
git.write("Changed.java", fixture("ce-modified") + "CE implementation\nTB change\n")
git.write("New.java", fixture(p.NON_CE) + "TB feature\n")
self.relicensing = git.commit("relicensing")
git("merge", "--no-ff", "lts-4.3", "-m", "integrate CE fix")
self.scope = ["Base.java", "Changed.java", "Fixed.java", "Merged.java", "New.java", "Source.java"]
self.output = self.repo / "target/report.json"
def check(self, ref, scope, fix=False):
def check(self, *args, scope=None):
def recognized(content):
for header in p.TEMPLATES:
if content.startswith(fixture(header).encode()):
@ -483,30 +614,134 @@ class CheckCommandTests(unittest.TestCase):
def strip_headers(tool):
tool.removed = {key: split(body)[0] for key, body in tool.contents.items()}
tool.stacked = set()
return {key: p.comparison_hash(split(body)[1]) for key, body in tool.contents.items()}
for key, body in list(tool.contents.items()):
tool.write(key, split(body)[1])
return {key: p.comparison_hash(body) for key, body in tool.contents.items()}
def restamp(tool, expected):
for key, header in expected.items():
(tool.root / tool.paths[key]).write_bytes(fixture(header).encode() + split(tool.contents[key])[1])
return {key: (tool.root / tool.paths[key]).read_bytes() for key in expected}, {}
stderr = io.StringIO()
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, "discover_scope", return_value=p.Scope(scope, [], [], 0)),
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, "restamp", restamp),
redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO())):
code = p.main(["check", "--ce-ref", ref, "--ce-remote", str(self.repo), "--output", str(self.output)]
+ (["--fix"] if fix else []))
return code, json.loads(self.output.read_text())
redirect_stdout(io.StringIO()), redirect_stderr(stderr)):
code = p.main(["check", "--output", str(self.output), *args])
report = json.loads(self.output.read_text()) if self.output.exists() else None
return code, report, stderr.getvalue()
def test_matching_mainline_passes(self):
code, report = self.check("lts-4.2", ["Renamed.java", "Deleted.java", "Local.java"])
def rows(self, report):
return {row["path"]: row for row in report["files"]}
def test_relicensed_branch_passes(self):
code, report, _ = self.check()
self.assertEqual(0, code)
self.assertEqual({"match": 3}, report["summary"])
self.assertEqual({"remote": str(self.repo), "input": "lts-4.2", "commit": self.git("rev-parse", "lts-4.2")},
report["ceComparison"])
self.assertEqual({"match": 6}, report["summary"])
bases = sorted([self.fix, self.last])
self.assertEqual({"relicensingCommit": self.relicensing, "bases": bases}, report["ce"])
rows = self.rows(report)
self.assertEqual({"Base.java": "apache", "Changed.java": "ce-modified", "Fixed.java": "apache",
"Merged.java": "apache", "New.java": p.NON_CE, "Source.java": "apache"},
{name: row["expectedHeader"] for name, row in rows.items()})
self.assertEqual({"path": "Merged.java", "merge": bases, "base": self.base}, rows["Merged.java"]["identicalTo"])
self.assertEqual({"path": "Fixed.java", "ref": self.fix, "blob": self.git("rev-parse", f"{self.fix}:Fixed.java")},
rows["Fixed.java"]["identicalTo"])
def test_fix_restamps_decided_headers_only(self):
self.git.write("Base.java", FOREIGN_LINE.decode() + "base implementation\n")
self.git.write("New.java", fixture("apache") + "TB feature\n")
shortened = self.body.replace("CE source implementation\n", "", 1)
self.git.write("Source.java", fixture("apache") + shortened)
code, report, _ = self.check()
self.assertEqual(1, code)
self.assertEqual({"match": 3, "mismatch": 3}, report["summary"])
rows = self.rows(report)
self.assertEqual((p.FOREIGN, "apache"), (rows["Base.java"]["currentHeader"], rows["Base.java"]["expectedHeader"]))
self.assertEqual(("apache", p.NON_CE), (rows["New.java"]["currentHeader"], rows["New.java"]["expectedHeader"]))
self.assertEqual(("apache", "ce-modified"),
(rows["Source.java"]["currentHeader"], rows["Source.java"]["expectedHeader"]))
code, report, _ = self.check("--fix")
self.assertEqual(1, code)
self.assertEqual(["New.java", "Source.java"], report["restamped"])
self.assertEqual({"match": 5, "mismatch": 1}, report["summary"])
self.assertEqual(fixture(p.NON_CE) + "TB feature\n", (self.repo / "New.java").read_text())
self.assertEqual(fixture("ce-modified") + shortened, (self.repo / "Source.java").read_text())
self.assertEqual(FOREIGN_LINE.decode() + "base implementation\n", (self.repo / "Base.java").read_text())
code, report, _ = self.check("--fix")
self.assertEqual([], report["restamped"])
self.assertEqual({"match": 5, "mismatch": 1}, report["summary"])
def test_ce_evidence_for_new_paths_needs_a_decision(self):
self.git.write("Copy.java", fixture(p.NON_CE) + self.body)
self.git.write("Deleted.java", fixture(p.NON_CE) + "removed CE source\n")
code, report, output = self.check(scope=self.scope + ["Copy.java", "Deleted.java"])
self.assertEqual(1, code)
self.assertEqual({"match": 6, "unresolved": 2}, report["summary"])
rows = self.rows(report)
self.assertEqual("Source.java", rows["Copy.java"]["copyCandidates"][0]["path"])
self.assertEqual({"path": "Deleted.java", "ref": self.last + "^1",
"blob": self.git("rev-parse", f"{self.addition}:Deleted.java")},
rows["Deleted.java"]["historicalCandidate"])
self.assertIn("Needs a decision (2)\n", output)
def test_fix_removes_redundant_and_orphaned_curations(self):
self.git.write("Copy.java", fixture(p.NON_CE) + self.body)
def curation(name, header):
return dict(path=name, header=header, reason="Reviewed",
contentHash=p.raw_hash((self.repo / name).read_bytes()))
needed, redundant = curation("Copy.java", p.NON_CE), curation("New.java", p.NON_CE)
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=[needed, redundant, orphaned]),
indent=2) + "\n")
scope = self.scope + ["Copy.java"]
code, report, output = self.check(scope=scope)
self.assertEqual(1, code)
self.assertEqual({"match": 7}, report["summary"])
self.assertEqual(["New.java"], report["redundantCurations"])
self.assertEqual([dict(path="Gone.java", status="stale-curation", reason="file is no longer in scope")],
report["curationIssues"])
self.assertIn("Redundant curations (1)\n", output)
code, report, output = self.check("--fix", scope=scope)
self.assertEqual(0, code)
self.assertEqual([{"path": "Gone.java", "reason": "file is no longer in scope"},
{"path": "New.java", "reason": "the check decides the same header by itself"}],
report["removedCurations"])
self.assertEqual(([], []), (report["redundantCurations"], report["curationIssues"]))
self.assertEqual(json.dumps(dict(schemaVersion=1, curations=[needed]), indent=2) + "\n",
(self.repo / p.CURATIONS).read_text())
self.assertIn("Removed curations (2)\n", output)
code, report, _ = self.check("--fix", scope=scope)
self.assertEqual((0, []), (code, report["removedCurations"]))
def test_missing_relicensing_commit_fails_before_the_scan(self):
self.relicensing = "0" * 40
code, report, output = self.check()
self.assertEqual((2, None), (code, report))
self.assertIn("Resolving Git history ... failed\n", output)
self.assertIn("Pass --ce-ref", output)
def test_ce_ref_mode_compares_against_the_merged_ce_commit(self):
code, report, output = self.check("--ce-ref", "lts-4.3", "--ce-remote", str(self.repo))
self.assertEqual(1, code)
self.assertEqual({"remote": str(self.repo), "ref": "lts-4.3", "commit": self.fix, "bases": [self.fix]},
report["ce"])
rows = self.rows(report)
self.assertEqual(("mismatch", "ce-modified"), (rows["Merged.java"]["status"], rows["Merged.java"]["expectedHeader"]))
self.assertEqual({"match": 5, "mismatch": 1}, report["summary"])
self.assertIn(f" CE ref lts-4.3 → {self.fix[:11]}\n", output)
self.assertIn("Resolving Git history ... done (CE base lts-4.3)\n", output)
def test_ce_ref_is_fetched_from_the_public_ce_repository_by_default(self):
fetched = []
@ -520,9 +755,9 @@ class CheckCommandTests(unittest.TestCase):
patch.object(p, "read_plugin", return_value=fixture_plugin()),
patch.object(p, "discover_scope", return_value=p.Scope([], [], [], 0)),
redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO())):
code = p.main(["check", "--ce-ref", "lts-4.2", "--output", str(self.output)])
code = p.main(["check", "--ce-ref", "lts-4.3", "--output", str(self.output)])
self.assertEqual(0, code)
self.assertEqual([(p.CE_REMOTE, "lts-4.2")], fetched)
self.assertEqual([(p.CE_REMOTE, "lts-4.3")], fetched)
def test_unfetchable_ce_ref_fails_before_the_history_walk(self):
stderr = io.StringIO()
@ -535,71 +770,6 @@ class CheckCommandTests(unittest.TestCase):
self.assertIn(f"Fetching missing from {self.repo} ... failed\n", stderr.getvalue())
self.assertIn(f"Error: cannot fetch 'missing' from {self.repo}.", stderr.getvalue())
def test_feature_ref_exposes_rename_and_history_candidates(self):
code, report = self.check("fix/my-fix", ["Renamed.java", "Deleted.java", "Local.java"])
self.assertEqual(1, code)
rows = {row["path"]: row for row in report["files"]}
self.assertEqual("unresolved", rows["Renamed.java"]["status"])
candidate = rows["Renamed.java"]["candidates"][0]
self.assertEqual(("Feature.java", self.feature), (candidate["path"], candidate["ref"]))
self.assertEqual("unresolved", rows["Deleted.java"]["status"])
self.assertTrue(rows["Deleted.java"]["historicalCandidates"])
self.assertEqual("pe-only", rows["Local.java"]["expectedHeader"])
self.assertEqual({"tip": self.feature, "firstParent": True}, report["ceHistory"])
def test_curation_for_deleted_file_fails_the_check(self):
curation = dict(path="Gone.java", contentHash=p.raw_hash(b"gone"), header="pe-only", reason="Reviewed")
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[curation])))
code, report = self.check("lts-4.2", ["Renamed.java", "Deleted.java", "Local.java"])
self.assertEqual(1, code)
self.assertEqual({"match": 3}, report["summary"])
self.assertEqual([dict(path="Gone.java", status="stale-curation", reason="file is no longer in scope")],
report["curationIssues"])
def test_fix_restamps_decided_headers_only(self):
self.git("merge", "--no-ff", "fix/my-fix", "-m", "integrate CE fix")
self.git.write("Base.java", FOREIGN_LINE.decode() + "base implementation\n")
scope = ["Base.java", "Feature.java", "Renamed.java", "Swapped.java"]
code, report = self.check(self.feature, scope)
self.assertEqual(1, code)
self.assertEqual({"mismatch": 3, "unresolved": 1}, report["summary"])
self.assertEqual([], report["restamped"])
rows = {row["path"]: row for row in report["files"]}
self.assertEqual((p.FOREIGN, "apache"), (rows["Base.java"]["currentHeader"], rows["Base.java"]["expectedHeader"]))
self.assertEqual((p.MISSING, "apache"),
(rows["Feature.java"]["currentHeader"], rows["Feature.java"]["expectedHeader"]))
self.assertEqual(("apache", "pe-only"),
(rows["Swapped.java"]["currentHeader"], rows["Swapped.java"]["expectedHeader"]))
code, report = self.check(self.feature, scope, fix=True)
self.assertEqual(1, code)
self.assertEqual(["Feature.java", "Swapped.java"], report["restamped"])
self.assertEqual({"match": 2, "mismatch": 1, "unresolved": 1}, report["summary"])
rows = {row["path"]: row for row in report["files"]}
self.assertEqual(("match", "apache", p.MISSING),
(rows["Feature.java"]["status"], rows["Feature.java"]["currentHeader"],
rows["Feature.java"]["previousHeader"]))
self.assertEqual(fixture("apache") + self.body, (self.repo / "Feature.java").read_text())
self.assertEqual(fixture("pe-only") + "swapped source\n", (self.repo / "Swapped.java").read_text())
self.assertEqual("apache", rows["Swapped.java"]["previousHeader"])
self.assertEqual("mismatch", rows["Base.java"]["status"])
self.assertNotIn("previousHeader", rows["Base.java"])
self.assertEqual(FOREIGN_LINE.decode() + "base implementation\n", (self.repo / "Base.java").read_text())
self.assertEqual(fixture("pe-only") + self.body, (self.repo / "Renamed.java").read_text())
code, report = self.check(self.feature, scope, fix=True)
self.assertEqual([], report["restamped"])
self.assertEqual({"match": 2, "mismatch": 1, "unresolved": 1}, report["summary"])
def test_integrated_ce_file_compares_against_shared_ancestor(self):
self.git("merge", "--no-ff", "fix/my-fix", "-m", "integrate CE fix")
_, report = self.check(self.feature, ["Feature.java"])
self.assertEqual("apache", report["files"][0]["expectedHeader"])
self.assertEqual(self.feature, report["sharedAncestor"])
self.git.write("Feature.java", self.body + "PE-specific addition\n")
_, report = self.check(self.feature, ["Feature.java"])
self.assertEqual("ce-modified", report["files"][0]["expectedHeader"])
MANAGED_POM = textwrap.dedent("""\
<project xmlns="http://maven.apache.org/POM/4.0.0">
@ -748,30 +918,30 @@ class MavenTests(unittest.TestCase):
header = (repo / template).read_text()
for extension in SAMPLE_BODY:
for eol in ("\n", "\r\n"):
key = ("pe", category + extension + repr(eol))
key = ("head", category + extension + repr(eol))
sample = SAMPLE_PREFIX[extension] + commented(header, extension) + SAMPLE_BODY[extension]
tool.add(key, "sample." + extension, sample.replace("\n", eol).encode())
expected[key] = p.comparison_hash((SAMPLE_PREFIX[extension] + SAMPLE_BODY[extension]).encode())
missing = ("pe", "missing")
missing = ("head", "missing")
tool.add(missing, "missing.java", b"// Ordinary documentation\nclass Missing {}\n")
expected[missing] = p.comparison_hash(b"// Ordinary documentation\nclass Missing {}\n")
legacy = ("ce", "legacy")
tool.add(legacy, "legacy.java", LEGACY_JAVA)
expected[legacy] = p.comparison_hash(b"class Legacy {}\n")
foreign = ("pe", "foreign")
foreign = ("head", "foreign")
tool.add(foreign, "foreign.java", FOREIGN_LINE + b"class Foreign {}\n")
expected[foreign] = p.comparison_hash(b"class Foreign {}\n")
one_line = ("pe", "one-line")
one_line = ("head", "one-line")
tool.add(one_line, "one.sh", b"#!/bin/sh\n# Copyright 2024 The Thingsboard Authors\nset -e\necho x\n")
expected[one_line] = p.comparison_hash(b"#!/bin/sh\nset -e\necho x\n")
spdx = stamped((repo / p.TEMPLATES["apache"]).read_text(), "java").encode()
stacked = ("pe", "stacked")
stacked = ("head", "stacked")
tool.add(stacked, "stacked.java", spdx + LEGACY_JAVA)
expected[stacked] = p.comparison_hash(b"class Legacy {}\n")
reversed_stack = ("pe", "reversed")
reversed_stack = ("head", "reversed")
tool.add(reversed_stack, "reversed.java", LEGACY_JAVA.replace(b"class Legacy {}\n", spdx + b"class Legacy {}\n"))
expected[reversed_stack] = p.comparison_hash(b"class Legacy {}\n")
mentioned = ("pe", "mentioned")
mentioned = ("head", "mentioned")
tool.add(mentioned, "mentioned.java", spdx + b"\n" + FOREIGN_LINE + b"class Mentioned {}\n")
expected[mentioned] = p.comparison_hash(FOREIGN_LINE + b"class Mentioned {}\n")
pairs = {}
@ -780,18 +950,18 @@ class MavenTests(unittest.TestCase):
new = stamped((repo / p.TEMPLATES["apache"]).read_text(), extension).encode()
old = legacy_file[:-len(body)]
for order, content in (("new-old", new + old + body), ("old-new", old + new + body)):
key = ("pe", order + "." + extension)
key = ("head", order + "." + extension)
pairs[key] = content
tool.add(key, key[1], content)
expected[key] = p.comparison_hash(body)
header_only = {}
for extension in SAMPLE_BODY:
key = ("pe", "only." + extension)
header_only[key] = SAMPLE_PREFIX[extension] + commented((repo / p.TEMPLATES["pe-only"]).read_text(), extension)
key = ("head", "only." + extension)
header_only[key] = SAMPLE_PREFIX[extension] + commented((repo / p.TEMPLATES[p.NON_CE]).read_text(), extension)
tool.add(key, "only." + extension, header_only[key].encode())
expected[key] = p.comparison_hash(SAMPLE_PREFIX[extension].encode())
headers = tool.current_headers([key for key in expected if key[0] == "pe"])
headers = tool.current_headers([key for key in expected if key[0] == "head"])
recognized = dict(headers)
self.assertEqual(p.UNRECOGNIZED, headers.pop(missing))
@ -803,7 +973,7 @@ class MavenTests(unittest.TestCase):
for key in pairs:
headers.pop(key)
for key in header_only:
self.assertEqual("pe-only", headers.pop(key), key)
self.assertEqual(p.NON_CE, headers.pop(key), key)
for key, header in headers.items():
self.assertTrue(key[1].startswith(header), (key, header))
self.assertEqual(expected, tool.strip_headers())
@ -832,55 +1002,55 @@ class MavenTests(unittest.TestCase):
for extension in SAMPLE_BODY:
for eol in ("\n", "\r\n"):
body = (SAMPLE_PREFIX[extension] + SAMPLE_BODY[extension]).replace("\n", eol)
key = ("pe", "missing-" + category + extension + repr(eol))
key = ("head", "missing-" + category + extension + repr(eol))
tool.add(key, "sample." + extension, body.encode())
wanted[key] = category
expected[key] = (SAMPLE_PREFIX[extension] + stamped(header, extension) + SAMPLE_BODY[extension]).replace("\n", eol).encode()
legacy = ("pe", "legacy")
legacy = ("head", "legacy")
tool.add(legacy, "legacy.java", LEGACY_JAVA)
wanted[legacy], expected[legacy] = "apache", (stamped(templates["apache"], "java") + "class Legacy {}\n").encode()
confidential = ("pe", "confidential")
confidential = ("head", "confidential")
tool.add(confidential, "start.sh", b"#!/bin/bash\n#\n# ThingsBoard, Inc. (\"COMPANY\") CONFIDENTIAL\n#\n"
b"# Copyright \xc2\xa9 2016-2026 ThingsBoard, Inc. All Rights Reserved.\n#\n\nset -e\n")
wanted[confidential], expected[confidential] = "pe-only", ("#!/bin/bash\n" + stamped(templates["pe-only"], "sh") + "set -e\n").encode()
header_only = ("pe", "only")
wanted[confidential], expected[confidential] = p.NON_CE, ("#!/bin/bash\n" + stamped(templates[p.NON_CE], "sh") + "set -e\n").encode()
header_only = ("head", "only")
tool.add(header_only, "only.java", b"/**\n * Copyright 2024 The Thingsboard Authors\n */\n")
wanted[header_only], expected[header_only] = "ce-modified", stamped(templates["ce-modified"], "java").encode()
shebang = ("pe", "shebang")
shebang = ("head", "shebang")
tool.add(shebang, "shebang.sh", b"#!/bin/sh\n#\n# Copyright 2024 The Thingsboard Authors\n#\n")
wanted[shebang], expected[shebang] = "pe-only", ("#!/bin/sh\n" + stamped(templates["pe-only"], "sh")).encode()
glued = ("pe", "glued")
wanted[shebang], expected[shebang] = p.NON_CE, ("#!/bin/sh\n" + stamped(templates[p.NON_CE], "sh")).encode()
glued = ("head", "glued")
tool.add(glued, "glued.sh", b"#\n# Copyright 2024 The Thingsboard Authors\n#\n# helper\nset -e\n")
wanted[glued] = "pe-only"
doubled = ("pe", "doubled")
wanted[glued] = p.NON_CE
doubled = ("head", "doubled")
tool.add(doubled, "doubled.java", LEGACY_JAVA.replace(b"class Legacy {}\n", LEGACY_JAVA))
wanted[doubled], expected[doubled] = "pe-only", (stamped(templates["pe-only"], "java") + "class Legacy {}\n").encode()
damaged = ("pe", "damaged")
wanted[doubled], expected[doubled] = p.NON_CE, (stamped(templates[p.NON_CE], "java") + "class Legacy {}\n").encode()
damaged = ("head", "damaged")
tool.add(damaged, "damaged.java", stamped(templates["apache"], "java").replace("Apache-2.0", "Apache-2.0 test").encode()
+ b"class Damaged {}\n")
wanted[damaged], expected[damaged] = "apache", (stamped(templates["apache"], "java") + "class Damaged {}\n").encode()
truncated = ("pe", "truncated")
truncated = ("head", "truncated")
tool.add(truncated, "truncated.java", b"// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors\nclass Truncated {}\n")
wanted[truncated], expected[truncated] = "apache", (stamped(templates["apache"], "java") + "class Truncated {}\n").encode()
vendored = ("pe", "vendored")
vendored = ("head", "vendored")
tool.add(vendored, "vendored.java", LEGACY_JAVA.replace(b"class Legacy {}\n", FOREIGN_LINE + b"// MIT\nclass Legacy {}\n"))
wanted[vendored] = "pe-only"
wanted[vendored] = p.NON_CE
spdx = stamped(templates["apache"], "java").encode()
stacked = ("pe", "stacked")
stacked = ("head", "stacked")
tool.add(stacked, "stacked.java", spdx + LEGACY_JAVA)
wanted[stacked], expected[stacked] = "ce-modified", (stamped(templates["ce-modified"], "java") + "class Legacy {}\n").encode()
reversed_stack = ("pe", "reversed")
reversed_stack = ("head", "reversed")
tool.add(reversed_stack, "reversed.java", LEGACY_JAVA.replace(b"class Legacy {}\n", spdx + b"\nclass Legacy {}\n"))
wanted[reversed_stack], expected[reversed_stack] = "apache", (stamped(templates["apache"], "java") + "class Legacy {}\n").encode()
mentioned = ("pe", "mentioned")
mentioned = ("head", "mentioned")
tool.add(mentioned, "mentioned.java", spdx + b"\n" + FOREIGN_LINE + b"class Mentioned {}\n")
wanted[mentioned] = "pe-only"
wanted[mentioned] = p.NON_CE
for extension, legacy_file, body in (("ts", LEGACY_TS, b"export const legacy = 1;\n"),
("xml", LEGACY_XML, b"<example/>\n")):
new = stamped(templates["apache"], extension).encode()
old = legacy_file[:-len(body)]
for order, content in (("new-old", new + old + body), ("old-new", old + new + body)):
key = ("pe", order + "." + extension)
key = ("head", order + "." + extension)
tool.add(key, key[1], content)
wanted[key] = "ce-modified"
expected[key] = stamped(templates["ce-modified"], extension).encode() + body

Loading…
Cancel
Save