Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ Unreleased
replaces is no longer converted first, and planning a migrated template writes it no
more. WHS's ``res-2`` ``atlas-v3`` image, a tissue map, becomes ``desc-tissues``.
Closes templateflow/templateflow#203.
* The licenses of the migration to TemplateFlow 2.0 (``tfmanager.migrate.licensing``, T07):
the config's ``licenses.table`` gives the license of each template of the Archive, of
each atlas and of three subsets of files, citing its upstream statement (URL, a verbatim
quote, the evidence saved on 2026-12-05), or saying that there is none and TemplateFlow's
assertion stands. template_description.json takes the SPDX ``License``; LICENSE starts
with its ``SPDX-License-Identifier`` line, and the six missing LICENSE files are written
from the license texts; the ``License`` of JSON sidecars and the ``license`` of rows of
the atlases table follow their atlas or files; and ``docs/licenses/`` gets the text of
each other license in use. Texts that tfmanager does not bundle are under
``migrate/config/licenses/``, each cited with its URL and sha256. A template or sidecar
without an entry keeps its License (M203); a license
without a text blocks a plan (M211). CHANGES entries say what changed in the licenses.
* New warning TF118 redundant-entity: a ``desc``, ``seg`` or ``label`` that tells its file
apart from no other file of the template (``res``, ``den``, ``hemi`` and ``cohort``
aside). Masks keep ``desc``, probabilistic segmentations keep ``label``, and
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ tfmanager =
migrate/config/*.yaml
migrate/config/*.json
migrate/config/tables/*.tsv
migrate/config/licenses/*.txt

[options.packages.find]
exclude =
Expand Down
164 changes: 163 additions & 1 deletion tfmanager/migrate/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,51 @@ class Participants:
evidence: str = ''


@dataclass(frozen=True)
class LicenseText:
"""The text of a license that tfmanager does not bundle (``licenses.texts``)."""

license: str
file: str
"""Its file, under ``licenses/`` next to the config."""
sha256: str
url: str
why: str
text: str = ''


@dataclass(frozen=True)
class License:
"""The license of a template, an atlas or a subset of files (``licenses.table``).
An entry with neither ``atlas`` nor ``files`` is the template's: its License field and its
LICENSE file (``license_file``: ``keep`` the text, after the ``replace`` edits, or
``write`` the license's text). An atlas entry gives the License of the atlas; a ``files``
entry, that of the ``count`` data files whose entities include ``files`` (declared in
JSON sidecars).
"""

id: str
template: str
license: str
basis: str
"""``upstream``, ``derived`` (from data under other terms) or ``templateflow`` (no source)."""
url: str
why: str
retrieved: str
quote: str = ''
evidence: tuple[str, ...] = ()
atlas: str | None = None
files: dict = field(default_factory=dict)
count: int | None = None
license_file: str | None = None
replace: tuple[tuple[str, str], ...] = ()

@property
def scope(self) -> str:
return 'atlas' if self.atlas else 'files' if self.files else 'template'


@dataclass(frozen=True)
class Config:
version: str
Expand All @@ -148,8 +193,24 @@ class Config:
layouts: tuple[Layout, ...] = ()
sources: tuple[Source, ...] = ()
participants: tuple[Participants, ...] = ()
license_texts: tuple[LicenseText, ...] = ()
licenses: tuple[License, ...] = ()
digest: str = ''

def licenses_for(self, template: str) -> list[License]:
return [item for item in self.licenses if item.template == template]

def license_text(self, license: str) -> str | None:
"""The text of a license: from the config, or bundled with tfmanager."""
from ..add import BUNDLED_LICENSES

for item in self.license_texts:
if item.license == license:
return item.text
if license in BUNDLED_LICENSES:
return (files('tfmanager') / 'data' / BUNDLED_LICENSES[license]).read_text()
return None

def atlas_label(self, template: str, label: str) -> str | None:
for item in self.atlas_labels:
if item['template'] == template and item['from'] == label:
Expand Down Expand Up @@ -301,6 +362,95 @@ def _source_data(item: dict, base) -> tuple[bytes, list[str]]:
return data, problems


def _license_texts(data: dict, base) -> tuple[list[LicenseText], list[str]]:
"""The ``licenses.texts`` entries, read from ``licenses/`` next to the config."""
from .. import licenses

texts, problems, seen = [], [], set()
for item in data.get('licenses', {}).get('texts', []):
where = f'licenses.texts {item["license"]}'
result = licenses.check(item['license'])
if not result.valid or result.normalized != item['license'] or result.deprecated:
problems.append(f'{where}: not a canonical SPDX identifier.')
if item['license'] in seen:
problems.append(f'{where}: listed twice.')
seen.add(item['license'])
text = ''
if '..' in item['file'].split('/'):
problems.append(f'{where}: {item["file"]} leaves licenses/.')
else:
try:
raw = (base / 'licenses' / item['file']).read_bytes()
except OSError:
problems.append(f'{where}: no file licenses/{item["file"]}.')
else:
if hashlib.sha256(raw).hexdigest() != item['sha256']:
problems.append(f'{where}: licenses/{item["file"]} does not match its sha256.')
text = raw.decode()
texts.append(LicenseText(**{**item, 'text': text}))
return texts, problems


def _license_table(data: dict, texts: list[LicenseText]) -> tuple[list[License], list[str]]:
"""The ``licenses.table`` entries, and what contradicts them."""
from .. import licenses
from ..add import BUNDLED_LICENSES

rs = load_ruleset()
have = {t.license for t in texts} | set(BUNDLED_LICENSES)
entries, problems = [], []
for item in data.get('licenses', {}).get('table', []):
where = f'licenses.table {item["id"]}'
entry = License(
id=item['id'],
template=item['template'],
license=item['license'],
basis=item['basis'],
url=item['url'],
why=item['why'],
retrieved=str(item['retrieved']),
quote=item.get('quote', ''),
evidence=tuple(item.get('evidence', ())),
atlas=item.get('atlas'),
files=dict(item.get('files', {})),
count=item.get('count'),
license_file=item.get('license_file'),
replace=tuple((r['old'], r['new']) for r in item.get('replace', ())),
)
entries.append(entry)
result = licenses.check(entry.license)
if not result.valid or result.normalized != entry.license or result.deprecated:
problems.append(f'{where}: {entry.license!r} is not a canonical SPDX expression.')
if not entry.quote and entry.basis != 'templateflow':
problems.append(f'{where}: quote the upstream statement (basis {entry.basis}).')
if (entry.scope == 'template') != (entry.license_file is not None):
problems.append(f'{where}: license_file is for the template entry, and only it.')
if entry.replace and entry.license_file != 'keep':
problems.append(f'{where}: replace edits a kept LICENSE.')
if (entry.scope == 'files') != (entry.count is not None):
problems.append(f'{where}: count is for files entries, and only them.')
unknown = sorted(set(entry.files) - set(rs.entities))
if unknown:
problems.append(f'{where}: unknown entities {", ".join(unknown)}.')
if entry.license_file == 'write' and entry.license not in have:
problems.append(f'{where}: no text for {entry.license} (licenses.texts).')
keys = [(e.template, e.scope, e.atlas, tuple(sorted(e.files.items()))) for e in entries]
for i, key in enumerate(keys):
if keys.index(key) != i:
problems.append(f'licenses.table {entries[i].id}: a second entry for the same files.')
ids = [e.id for e in entries]
for dup in sorted({i for i in ids if ids.count(i) > 1}):
problems.append(f'licenses.table: the id {dup} is used twice.')
# Licenses other than the template's need their text in docs/licenses/
own = {e.template: e.license for e in entries if e.scope == 'template'}
for entry in entries:
if entry.scope != 'template' and entry.license != own.get(entry.template):
for key in licenses.check(entry.license).identifiers:
if key not in have:
problems.append(f'licenses.table {entry.id}: no text for {key}.')
return entries, problems


def load_config(path: str | Path | None = None, version: str = '2.0.0') -> Config:
"""Load and check a config (by default, the one shipped for ``version``).
Expand Down Expand Up @@ -332,8 +482,18 @@ def load_config(path: str | Path | None = None, version: str = '2.0.0') -> Confi
describe=dict(item.get('describe', {})),
)
)
texts, found = _license_texts(data, base)
problems += found
table, found = _license_table(data, texts)
problems += found
if problems:
raise ConfigError('\n'.join(problems))
# The digest covers the files the config cites (tables, license texts)
digest = hashlib.sha256(text.encode())
for item in sources:
digest.update(f'\0tables/{item.file}\0'.encode() + item.data)
for item in texts:
digest.update(f'\0licenses/{item.file}\0{item.text}'.encode())
return Config(
version=data['version'],
policies=data['policies'],
Expand Down Expand Up @@ -395,7 +555,9 @@ def load_config(path: str | Path | None = None, version: str = '2.0.0') -> Confi
)
for item in data.get('participants', [])
),
digest=hashlib.sha256(text.encode()).hexdigest(),
license_texts=tuple(texts),
licenses=tuple(table),
digest=digest.hexdigest(),
)


Expand Down
Loading