diff --git a/CHANGES.rst b/CHANGES.rst
index 0d4f67a..3ae6154 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -2,6 +2,14 @@ Unreleased
==========
* Python 3.13 or newer, following `SPEC 0 `__
(tested on 3.13 to 3.15).
+* New command ``tfmgr generate atlases|cohorts|templates|dataset|all [--check] [PATH]``
+ writes the files generated from metadata: the atlas descriptions and the cohorts table
+ of a template, and templates.tsv and dataset_description.json at the root of the
+ Archive. dataset_description.json follows BIDS 1.11 (``DatasetType: derivative``,
+ ``License: LicenseRef-TemplateFlow-PerTemplate``), and its ``TemplateFlowVersion``
+ becomes 2.0.0 once every template is at 2.0.0. ``--check`` changes nothing and exits
+ with 1 when there are files to write.
+* ``tfmgr add`` writes the generated files of the template before validating it.
* New internals for ``tfmgr generate`` and ``tfmgr migrate``: ``GitTree`` reads a template
from a git commit without checking it out, ``collect_archive`` gathers what the
Archive's files and checks need from its templates, and ``renames_problems`` checks a
diff --git a/README.rst b/README.rst
index 7472f27..cef3842 100644
--- a/README.rst
+++ b/README.rst
@@ -19,6 +19,23 @@ and values are only checked with ``--level content``, which needs ``tfmanager[co
and the images' data. The command exits with 1 when there are errors, and 2 when it
could not run.
+Generating files
+----------------
+Some files are generated from the metadata, and ``tfmgr validate`` reports them when they
+are missing or out of date. ``tfmgr generate`` writes them::
+
+ tfmgr generate all tpl-MyTemplate # atlas descriptions and cohorts table
+ tfmgr generate all path/to/templateflow # templates.tsv and dataset_description.json
+ tfmgr generate all tpl-MyTemplate --check # list what would change; change nothing
+
+In a template, ``atlases`` writes an ``atlas-_description.json`` for each row of
+``tpl-_atlases.tsv``, and ``cohorts`` writes ``tpl-_cohorts.tsv`` (and its
+sidecar) from the ``cohort`` block of template_description.json. At the root of the
+Archive, ``templates`` writes templates.tsv and ``dataset`` writes dataset_description.json,
+whose ``TemplateFlowVersion`` becomes 2.0.0 once every template is at 2.0.0. Files no
+longer generated are deleted. With ``--check``, the command exits with 1 when there are
+files to write.
+
Checking and fixing images
--------------------------
``tfmgr sanitize`` works like a linter on the images of a template (rules TF701 to
@@ -46,8 +63,8 @@ Adding a template needs DataLad, the GitHub CLI (``gh``) and the TemplateFlow cl
``tfmgr add`` asks for the metadata that template_description.json misses (with an SPDX
license identifier), copies the template into a DataLad dataset without changing it
-(``--fix`` and ``--fix-unsafe`` apply ``tfmgr sanitize`` fixes to the copies), and checks
-it with ``tfmgr validate --mode strict --level content``: errors stop it before anything
+(``--fix`` and ``--fix-unsafe`` apply ``tfmgr sanitize`` fixes to the copies), writes the
+generated files (as ``tfmgr generate all``), and checks it with ``tfmgr validate --mode strict --level content``: errors stop it before anything
is uploaded. The data then go to GIN, the dataset to GitHub, and a pull request proposes
the template to the Archive. Each step is recorded in a work directory (by default in
the user's cache directory; ``--workdir`` sets another one), so a run that fails resumes
diff --git a/tfmanager/add.py b/tfmanager/add.py
index c696d0a..5e33555 100644
--- a/tfmanager/add.py
+++ b/tfmanager/add.py
@@ -5,7 +5,8 @@
1. ``copy``: the source folder is copied, byte for byte, into a DataLad dataset, with the
template's metadata and LICENSE (``--fix``/``--fix-unsafe`` then apply
- ``tfmgr sanitize`` to the copies);
+ ``tfmgr sanitize`` to the copies), and the generated files are written (atlas
+ descriptions and the cohorts table, as ``tfmgr generate all`` does);
2. ``validate``: the TemplateFlow rules, strict and with image content: errors stop the
run here, before anything is uploaded;
3. ``save``: ``datalad save``;
@@ -421,6 +422,21 @@ def step_copy(self, state: State) -> None:
self.echo(f' fixed {path}: {", ".join(codes)}')
for line in updated:
self.echo(f' updated {line}')
+ self.generate(dataset)
+
+ def generate(self, dataset: Path) -> None:
+ """Write the atlas descriptions and the cohorts table (``tfmgr generate all``)."""
+ from .generate import GenerateError, pending, template_outputs, write_outputs
+ from .tree import DirectoryTree
+
+ try:
+ outputs = template_outputs(DirectoryTree(dataset))
+ except GenerateError as exc:
+ raise AddError(str(exc)) from exc
+ changes = pending(dataset, outputs)
+ write_outputs(dataset, outputs, changes)
+ for change in changes:
+ self.echo(f' {change.action}d {change.path}')
def step_validate(self, state: State) -> None:
from .tree import DirectoryTree
diff --git a/tfmanager/cli.py b/tfmanager/cli.py
index d336d77..4ca1d50 100644
--- a/tfmanager/cli.py
+++ b/tfmanager/cli.py
@@ -178,6 +178,62 @@ def validate(paths, mode, level, fmt, archive, show_info, trusted, output):
raise SystemExit(1 if summary(issues)['error'] else 0)
+@cli.command()
+@click.argument('kind', type=click.Choice(('atlases', 'cohorts', 'templates', 'dataset', 'all')))
+@click.argument('path', type=click.Path(exists=True, file_okay=False), default='.', required=False)
+@click.option(
+ '--check',
+ is_flag=True,
+ help='Change nothing: list the files to write, and exit with 1 if there are any.',
+)
+def generate(kind, path, check):
+ """Write the files generated from metadata.
+
+ In a template (PATH is a tpl- directory): `atlases` writes an atlas
+ description for each row of tpl-_atlases.tsv, `cohorts` writes the cohorts
+ table from template_description.json, and `all` does both. At the root of the
+ Archive: `templates` writes templates.tsv, `dataset` writes dataset_description.json,
+ `all` does both, and `atlases` or `cohorts` apply to every template. Files no longer
+ generated are deleted.
+
+ Exits with 1 when --check finds files to write, and with 2 on errors.
+ """
+ from . import generate as gen
+ from .tree import DirectoryTree
+ from .validate.archive import template_dirs
+
+ root = Path(path).resolve()
+ try:
+ if root.name.startswith('tpl-'):
+ if kind in gen.ARCHIVE_KINDS:
+ raise gen.GenerateError(f'{kind}: generated at the root of the Archive.')
+ kinds = gen.TEMPLATE_KINDS if kind == 'all' else (kind,)
+ jobs = [('', root, gen.template_outputs(DirectoryTree(root), kinds))]
+ elif kind in gen.TEMPLATE_KINDS:
+ jobs = [
+ (f'{t.name}/', t, gen.template_outputs(DirectoryTree(t), (kind,)))
+ for t in template_dirs(root)
+ ]
+ else:
+ kinds = gen.ARCHIVE_KINDS if kind == 'all' else (kind,)
+ jobs = [('', root, gen.archive_outputs(root, kinds))]
+ found = 0
+ for prefix, where, outputs in jobs:
+ changes = gen.pending(where, outputs)
+ found += len(changes)
+ if not check:
+ gen.write_outputs(where, outputs, changes)
+ for change in changes:
+ verb = f'would {change.action}' if check else f'{change.action}d'
+ click.echo(f'{verb} {prefix}{change.path}')
+ except (gen.GenerateError, OSError) as exc:
+ click.echo(f'tfmgr generate failed: {exc}', err=True)
+ raise SystemExit(2) from exc
+ if not found:
+ click.echo('Up to date.')
+ raise SystemExit(1 if check and found else 0)
+
+
@cli.command()
@click.argument(
'template_dir', type=click.Path(exists=True, file_okay=False), default='.', required=False
diff --git a/tfmanager/generate.py b/tfmanager/generate.py
index 7706cea..7284e5c 100644
--- a/tfmanager/generate.py
+++ b/tfmanager/generate.py
@@ -8,17 +8,32 @@
- ``tpl-_cohorts.tsv`` is generated from the ``cohort`` block of
template_description.json.
- ``templates.tsv`` (root of the Archive) is generated from every template_description.json.
+- ``dataset_description.json`` (root of the Archive) describes the Archive; its
+ ``TemplateFlowVersion`` becomes 2.0.0 once every template is at 2.0.0.
"""
from __future__ import annotations
import json
-from collections.abc import Iterable
+import os
+import re
+from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
+from pathlib import Path
from .naming import parse
-from .tables import NA, Table, dump_json, json_cell, write_tsv
-from .tree import Tree, visible
+from .ruleset import TEMPLATEFLOW_VERSION
+from .tables import NA, Table, dump_json, json_cell, read_tsv, write_tsv
+from .tree import DirectoryTree, Tree, visible
+
+#: A generated atlas description, at the root of a template
+DESCRIPTION = re.compile(r'^atlas-([0-9a-zA-Z+]+)_description\.json$')
+#: What ``tfmgr generate`` writes in a template, and at the root of the Archive
+TEMPLATE_KINDS = ('atlases', 'cohorts')
+ARCHIVE_KINDS = ('templates', 'dataset')
+#: Root files of the Archive
+TEMPLATES_TSV = 'templates.tsv'
+DATASET_DESCRIPTION = 'dataset_description.json'
#: atlases.tsv column -> atlas-_description.json field (BIDS 1.11)
ATLAS_FIELDS = {
@@ -216,3 +231,199 @@ def collect_archive(trees: Iterable[Tree]) -> ArchiveIndex:
if key in f.entities:
index.targets.append((f'{tree.name}/{path}', f.entities[key]))
return index
+
+
+class GenerateError(ValueError):
+ """The files cannot be generated (malformed metadata, uninstalled templates)."""
+
+
+@dataclass(frozen=True)
+class Change:
+ """A generated file to create, update or delete."""
+
+ path: str
+ action: str # 'create', 'update' or 'delete'
+
+
+def _unreadable(tree: Tree, path: str) -> str:
+ """Why a file that the generators need cannot be read."""
+ if not tree.exists(path):
+ return 'missing'
+ if tree.is_annexed(path):
+ return 'annexed (files are generated from metadata in git)'
+ return 'too large'
+
+
+def _atlas_outputs(tree: Tree) -> dict[str, str]:
+ """The atlas descriptions the atlases table generates (none without a table)."""
+ path = f'{tree.name}_atlases.tsv'
+ if not tree.exists(path):
+ return {}
+ data = tree.read_bytes(path)
+ if data is None:
+ raise GenerateError(f'{tree.name}/{path}: {_unreadable(tree, path)}.')
+ table = read_tsv(data)
+ if 'atlas_id' not in table.columns:
+ raise GenerateError(f'{tree.name}/{path}: no atlas_id column.')
+ try:
+ expected = atlas_descriptions(table)
+ except (TypeError, ValueError, AttributeError) as exc:
+ raise GenerateError(
+ f'{tree.name}/{path}: cannot generate the descriptions ({exc}).'
+ ) from exc
+ for name in expected:
+ if not DESCRIPTION.match(name):
+ raise GenerateError(f'{tree.name}/{path}: not an atlas label: {name}.')
+ return expected
+
+
+def _cohort_outputs(tree: Tree) -> tuple[str, str] | None:
+ """The cohorts table and its sidecar, or ``None`` when the template has no cohorts."""
+ where = f'{tree.name}/template_description.json'
+ data = tree.read_bytes('template_description.json')
+ if data is None:
+ raise GenerateError(f'{where}: {_unreadable(tree, "template_description.json")}.')
+ try:
+ description = json.loads(data)
+ except ValueError as exc:
+ raise GenerateError(f'{where}: not JSON ({exc}).') from exc
+ if not isinstance(description, dict):
+ raise GenerateError(f'{where}: not a JSON object.')
+ block = description.get('cohort')
+ if block is not None and not isinstance(block, dict):
+ raise GenerateError(f'{where}: "cohort" is not an object.')
+ try:
+ return cohorts_table(description)
+ except (TypeError, ValueError, AttributeError) as exc:
+ raise GenerateError(f'{where}: cannot read its cohorts ({exc}).') from exc
+
+
+def template_outputs(tree: Tree, kinds: Iterable[str] = TEMPLATE_KINDS) -> dict[str, str | None]:
+ """The generated files of a template: ``{path: content}``, ``None`` to delete one.
+
+ ``atlases``: an ``atlas-_description.json`` for each row of the atlases table,
+ and none without a table (descriptions no row generates are deleted). ``cohorts``:
+ ``tpl-_cohorts.tsv`` and its sidecar, from the ``cohort`` block of
+ template_description.json (deleted when there is none).
+
+ Files are deleted only when readable metadata says they are not generated: a
+ description or atlases table that cannot be read (annexed, not JSON, not an object,
+ without an ``atlas_id`` column...) raises :class:`GenerateError`.
+ """
+ kinds = set(kinds)
+ outputs: dict[str, str | None] = {}
+ if 'atlases' in kinds:
+ expected = _atlas_outputs(tree)
+ for path in tree.files():
+ if DESCRIPTION.match(path) and path not in expected:
+ outputs[path] = None
+ outputs.update(expected)
+ if 'cohorts' in kinds:
+ cohorts = _cohort_outputs(tree)
+ paths = (f'{tree.name}_cohorts.tsv', f'{tree.name}_cohorts.json')
+ if cohorts is None:
+ outputs.update((path, None) for path in paths if tree.exists(path))
+ else:
+ outputs.update(zip(paths, cohorts, strict=True))
+ return outputs
+
+
+def dataset_description(at_version: bool, current: Mapping | None = None) -> str:
+ """The Archive's dataset_description.json.
+
+ ``TemplateFlowVersion`` is the rule set's version when ``at_version`` (every template
+ of the Archive is at that version), and otherwise stays as it is: the Archive's checks
+ become strict when it changes. No tfmanager version is recorded, so that the file does
+ not change when tfmanager does.
+ """
+ from .ruleset import load_ruleset
+
+ current = current or {}
+ version = TEMPLATEFLOW_VERSION if at_version else current.get('TemplateFlowVersion', '1.0.0')
+ return dump_json(
+ {
+ 'Name': 'TemplateFlow',
+ 'BIDSVersion': load_ruleset().bids_version,
+ 'DatasetType': 'derivative',
+ 'TemplateFlowVersion': version,
+ 'License': 'LicenseRef-TemplateFlow-PerTemplate',
+ 'GeneratedBy': [
+ {'Name': 'tfmanager', 'CodeURL': 'https://github.com/templateflow/python-manager'}
+ ],
+ 'ReferencesAndLinks': ['https://doi.org/10.1038/s41592-022-01681-2'],
+ }
+ )
+
+
+def archive_outputs(
+ root: str | os.PathLike, kinds: Iterable[str] = ARCHIVE_KINDS
+) -> dict[str, str]:
+ """The generated files at the root of an Archive checkout.
+
+ Every template registered in ``.gitmodules`` must be installed: the table would
+ otherwise leave it out.
+ """
+ from .validate.archive import submodules, template_dirs
+ from .validate.core import is_legacy
+
+ root = Path(root)
+ kinds = set(kinds)
+ names = {p.name for p in template_dirs(root)} | submodules(root)
+ absent = sorted(n for n in names if not (root / n).is_dir() or not any((root / n).iterdir()))
+ if absent:
+ raise GenerateError(f'Templates not installed: {", ".join(absent)}.')
+ index = collect_archive(DirectoryTree(root / name) for name in sorted(names))
+ outputs = {}
+ if 'templates' in kinds:
+ outputs[TEMPLATES_TSV] = templates_table(index.descriptions, index.atlases)
+ if 'dataset' in kinds:
+ current = None
+ if (root / DATASET_DESCRIPTION).is_file():
+ try:
+ current = json.loads((root / DATASET_DESCRIPTION).read_text())
+ except ValueError as exc:
+ raise GenerateError(f'{DATASET_DESCRIPTION}: {exc}') from exc
+ at_version = len(index.descriptions) == len(names) and not any(
+ is_legacy(d) for d in index.descriptions.values()
+ )
+ outputs[DATASET_DESCRIPTION] = dataset_description(at_version, current)
+ return outputs
+
+
+def _current(path: Path) -> bytes | None:
+ """Content of a regular file (never through a symlink), else ``None``."""
+ if path.is_symlink() or not path.is_file():
+ return None
+ return path.read_bytes()
+
+
+def pending(root: str | os.PathLike, outputs: Mapping[str, str | None]) -> list[Change]:
+ """What writing ``outputs`` under ``root`` would change."""
+ root = Path(root)
+ changes = []
+ for path, content in sorted(outputs.items()):
+ target = root / path
+ present = target.is_symlink() or target.exists()
+ if content is None:
+ if present:
+ changes.append(Change(path, 'delete'))
+ elif not present:
+ changes.append(Change(path, 'create'))
+ elif _current(target) != content.encode():
+ changes.append(Change(path, 'update'))
+ return changes
+
+
+def write_outputs(
+ root: str | os.PathLike, outputs: Mapping[str, str | None], changes: Iterable[Change]
+) -> None:
+ """Apply ``changes``: each file is replaced atomically (an annex link included)."""
+ root = Path(root)
+ for change in changes:
+ target = root / change.path
+ if change.action == 'delete':
+ target.unlink()
+ continue
+ tmp = target.parent / f'.tfmgr-{target.name}'
+ tmp.write_bytes(outputs[change.path].encode())
+ os.replace(tmp, target)
diff --git a/tfmanager/tests/test_add.py b/tfmanager/tests/test_add.py
index a1bd356..31ce62d 100644
--- a/tfmanager/tests/test_add.py
+++ b/tfmanager/tests/test_add.py
@@ -261,6 +261,15 @@ def test_add_resumes_where_it_failed(template, tmp_path, datalad, commands):
assert datalad.calls == []
+def test_generated_files_are_written(template, tmp_path, datalad, commands):
+ (template / 'atlas-Smith2020_description.json').unlink()
+ _add(template, tmp_path / 'work').run() # strict validation fails without it (TF607)
+ dataset = tmp_path / 'work' / f'tpl-{LABEL}'
+ assert json.loads((dataset / 'atlas-Smith2020_description.json').read_text())['Name'] == (
+ 'The Smith atlas'
+ )
+
+
def test_validation_errors_stop_before_uploading(template, tmp_path, datalad, commands):
(template / f'tpl-{LABEL}_T1w_res-1.nii.gz').write_bytes(b'')
with pytest.raises(AddError, match='TF100'):
diff --git a/tfmanager/tests/test_generate.py b/tfmanager/tests/test_generate.py
new file mode 100644
index 0000000..f212ab0
--- /dev/null
+++ b/tfmanager/tests/test_generate.py
@@ -0,0 +1,255 @@
+"""``tfmgr generate``: the files written agree with what the validator expects."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from tfmanager.cli import cli
+from tfmanager.generate import (
+ Change,
+ GenerateError,
+ archive_outputs,
+ pending,
+ template_outputs,
+ write_outputs,
+)
+from tfmanager.tests.conftest import ATLASES_TSV, LABEL, description, template_files
+from tfmanager.tree import DirectoryTree
+from tfmanager.validate import check_archive, validate_template
+
+T = f'tpl-{LABEL}'
+KEY = 'MD5E-s1--9dd4e461268c8034f5c8564e155c67a6.nii.gz'
+
+
+def _write(root: Path, files: dict) -> Path:
+ """Write a template: text files, and annex links for ``None``."""
+ for path, content in files.items():
+ target = root / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if content is None:
+ os.symlink(f'.git/annex/objects/Xx/Yy/{KEY}/{KEY}', target)
+ else:
+ target.write_text(content)
+ return root
+
+
+def _generate(root: Path) -> list[Change]:
+ outputs = template_outputs(DirectoryTree(root))
+ changes = pending(root, outputs)
+ write_outputs(root, outputs, changes)
+ return changes
+
+
+def _codes(root: Path) -> set[str]:
+ return {i.code for i in validate_template(DirectoryTree(root), mode='strict')}
+
+
+def test_valid_template_is_up_to_date(tmp_path):
+ root = _write(tmp_path / T, template_files())
+ assert pending(root, template_outputs(DirectoryTree(root))) == []
+
+
+def test_atlas_descriptions(tmp_path):
+ root = _write(tmp_path / T, template_files(**{'atlas-Smith2020_description.json': False}))
+ (root / 'atlas-Old2000_description.json').write_text('{}')
+ assert {'TF607'} <= _codes(root)
+ assert _generate(root) == [
+ Change('atlas-Old2000_description.json', 'delete'),
+ Change('atlas-Smith2020_description.json', 'create'),
+ ]
+ assert 'TF607' not in _codes(root)
+ assert _generate(root) == []
+
+ # Without the atlases table, no description is generated
+ (root / f'{T}_atlases.tsv').unlink()
+ assert _generate(root) == [Change('atlas-Smith2020_description.json', 'delete')]
+
+
+def test_cohorts(tmp_path):
+ cohorts = {'1': {'age': [20, 40], 'units': 'years'}, '2': {'name': 'Older adults'}}
+ desc = json.dumps(description(cohort=cohorts))
+ root = _write(tmp_path / T, template_files(**{'template_description.json': desc}))
+ assert _generate(root) == [
+ Change(f'{T}_cohorts.json', 'create'),
+ Change(f'{T}_cohorts.tsv', 'create'),
+ ]
+ assert 'TF410' not in _codes(root)
+ assert 'Older adults' in (root / f'{T}_cohorts.tsv').read_text()
+
+ (root / 'template_description.json').write_text(json.dumps(description()))
+ assert _generate(root) == [
+ Change(f'{T}_cohorts.json', 'delete'),
+ Change(f'{T}_cohorts.tsv', 'delete'),
+ ]
+
+
+def test_malformed_cohorts(tmp_path):
+ desc = json.dumps(description(cohort={'1': 'not a block'}))
+ root = _write(tmp_path / T, template_files(**{'template_description.json': desc}))
+ with pytest.raises(GenerateError, match='cohorts'):
+ template_outputs(DirectoryTree(root))
+
+
+@pytest.mark.parametrize(
+ ('changes', 'message'),
+ [
+ ({'template_description.json': '[]'}, 'not a JSON object'),
+ ({'template_description.json': '{"Name": '}, 'not JSON'),
+ ({'template_description.json': False}, 'missing'),
+ ({'template_description.json': None}, 'annexed'),
+ ({'template_description.json': json.dumps(description(cohort=[1]))}, '"cohort" is not'),
+ ({f'{T}_atlases.tsv': None}, 'annexed'),
+ ({f'{T}_atlases.tsv': 'atlas,name\nSmith2020,Smith\n'}, 'no atlas_id column'),
+ ({f'{T}_atlases.tsv': ''}, 'no atlas_id column'),
+ (
+ {f'{T}_atlases.tsv': ATLASES_TSV.replace('atlas-Smith2020', 'atlas-x/../../y')},
+ 'not an atlas label',
+ ),
+ ],
+)
+def test_unreadable_metadata(tmp_path, changes, message):
+ """Generated files are never deleted on the word of metadata that cannot be read."""
+ cohorts = {'1': {'age': [20, 40], 'units': 'years'}}
+ files = template_files(
+ **{'template_description.json': json.dumps(description(cohort=cohorts))}
+ )
+ root = _write(tmp_path / T, files)
+ _generate(root)
+ for path in changes:
+ (root / path).unlink()
+ _write(root, {p: c for p, c in changes.items() if c is not False})
+ before = sorted(p.name for p in root.iterdir())
+ assert f'{T}_cohorts.tsv' in before and 'atlas-Smith2020_description.json' in before
+ with pytest.raises(GenerateError, match=message):
+ template_outputs(DirectoryTree(root))
+ result = CliRunner().invoke(cli, ['generate', 'all', str(root)])
+ assert result.exit_code == 2
+ assert message in result.stderr
+ assert sorted(p.name for p in root.iterdir()) == before
+
+
+def test_malformed_atlas_row(tmp_path):
+ table = ATLASES_TSV.replace('["Smith J"]', '["unclosed')
+ root = _write(tmp_path / T, template_files(**{f'{T}_atlases.tsv': table}))
+ with pytest.raises(GenerateError, match='cannot generate the descriptions'):
+ template_outputs(DirectoryTree(root), ('atlases',))
+
+
+def test_empty_cohort_block(tmp_path):
+ """A readable description without cohorts (no block, null or empty) deletes the table."""
+ cohorts = {'1': {'age': [20, 40], 'units': 'years'}}
+ for n, block in enumerate(('absent', None, {})):
+ desc = json.dumps(description(cohort=cohorts))
+ files = template_files(**{'template_description.json': desc})
+ root = _write(tmp_path / str(n) / T, files)
+ _generate(root)
+ changed = description()
+ if block != 'absent':
+ changed['cohort'] = block
+ (root / 'template_description.json').write_text(json.dumps(changed))
+ assert [c.action for c in _generate(root)] == ['delete', 'delete']
+
+
+def test_annexed_output_is_replaced(tmp_path):
+ root = _write(tmp_path / T, template_files(**{'atlas-Smith2020_description.json': None}))
+ assert DirectoryTree(root).is_annexed('atlas-Smith2020_description.json')
+ assert _generate(root) == [Change('atlas-Smith2020_description.json', 'update')]
+ assert not (root / 'atlas-Smith2020_description.json').is_symlink()
+ assert not DirectoryTree(root).is_annexed('atlas-Smith2020_description.json')
+
+
+def _archive(root: Path, versions: dict[str, str | None]) -> Path:
+ for label, version in versions.items():
+ desc = {'Identifier': label, 'Name': label}
+ if version:
+ desc['TemplateFlowVersion'] = version
+ tpl = root / f'tpl-{label}'
+ tpl.mkdir(parents=True)
+ (tpl / 'template_description.json').write_text(json.dumps(desc))
+ (root / 'dataset_description.json').write_text(
+ '{"Name": "TemplateFlow", "TemplateFlowVersion": "1.0.0"}\n'
+ )
+ (root / '.gitmodules').write_text(
+ ''.join(
+ f'[submodule "tpl-{x}"]\n\tpath = tpl-{x}\n\turl = https://x/tpl-{x}\n'
+ for x in versions
+ )
+ )
+ return root
+
+
+def _version(root: Path) -> str:
+ content = archive_outputs(root)['dataset_description.json']
+ return json.loads(content)['TemplateFlowVersion']
+
+
+def test_archive_outputs(tmp_path):
+ root = _archive(tmp_path, {'A': '2.0.0', 'B': None})
+ outputs = archive_outputs(root)
+ write_outputs(root, outputs, pending(root, outputs))
+ assert 'TF801' not in {i.code for i in check_archive(root)}
+ assert pending(root, archive_outputs(root)) == []
+ desc = json.loads((root / 'dataset_description.json').read_text())
+ assert desc['BIDSVersion'] == '1.11.0'
+ assert desc['DatasetType'] == 'derivative'
+ assert desc['TemplateFlowVersion'] == '1.0.0'
+
+
+def test_archive_version_flips_last(tmp_path):
+ root = _archive(tmp_path, {'A': '2.0.0', 'B': '1.0.0'})
+ assert _version(root) == '1.0.0'
+ (root / 'tpl-B' / 'template_description.json').write_text('{"TemplateFlowVersion": "2.0.0"}')
+ assert _version(root) == '2.0.0'
+ (root / 'tpl-B' / 'template_description.json').write_text('not JSON')
+ assert _version(root) == '1.0.0'
+
+
+def test_uninstalled_templates(tmp_path):
+ root = _archive(tmp_path, {'A': '2.0.0'})
+ (root / 'tpl-C').mkdir()
+ (root / '.gitmodules').write_text(
+ (root / '.gitmodules').read_text() + '[submodule "tpl-D"]\n\tpath = tpl-D\n\turl = x\n'
+ )
+ with pytest.raises(GenerateError, match='tpl-C, tpl-D'):
+ archive_outputs(root)
+
+
+def test_cli_template(tmp_path):
+ root = _write(tmp_path / T, template_files(**{'atlas-Smith2020_description.json': False}))
+ runner = CliRunner()
+ result = runner.invoke(cli, ['generate', 'all', str(root), '--check'])
+ assert (result.exit_code, result.output) == (
+ 1,
+ 'would create atlas-Smith2020_description.json\n',
+ )
+ assert not (root / 'atlas-Smith2020_description.json').exists()
+ result = runner.invoke(cli, ['generate', 'atlases', str(root)])
+ assert (result.exit_code, result.output) == (0, 'created atlas-Smith2020_description.json\n')
+ result = runner.invoke(cli, ['generate', 'all', str(root), '--check'])
+ assert (result.exit_code, result.output) == (0, 'Up to date.\n')
+ result = runner.invoke(cli, ['generate', 'templates', str(root)])
+ assert result.exit_code == 2
+
+
+def test_cli_archive(tmp_path):
+ root = _archive(tmp_path, {'A': '2.0.0'})
+ (root / 'tpl-A' / 'tpl-A_atlases.tsv').write_text(ATLASES_TSV)
+ runner = CliRunner()
+ result = runner.invoke(cli, ['generate', 'atlases', str(root)])
+ assert (result.exit_code, result.output) == (
+ 0,
+ 'created tpl-A/atlas-Smith2020_description.json\n',
+ )
+ result = runner.invoke(cli, ['generate', 'all', str(root)])
+ assert result.exit_code == 0
+ assert result.output.splitlines() == [
+ 'updated dataset_description.json',
+ 'created templates.tsv',
+ ]
+ result = runner.invoke(cli, ['generate', 'all', str(root), '--check'])
+ assert (result.exit_code, result.output) == (0, 'Up to date.\n')
diff --git a/tfmanager/validate/atlases.py b/tfmanager/validate/atlases.py
index 419241a..da51e94 100644
--- a/tfmanager/validate/atlases.py
+++ b/tfmanager/validate/atlases.py
@@ -5,7 +5,13 @@
import json
import re
-from ..generate import ATLAS_ARRAYS, ATLAS_COLUMNS, atlas_descriptions, atlas_label
+from ..generate import (
+ ATLAS_ARRAYS,
+ ATLAS_COLUMNS,
+ DESCRIPTION,
+ atlas_descriptions,
+ atlas_label,
+)
from ..ruleset import load_ruleset
from ..tables import NA, Table, read_tsv
from .core import Context, check
@@ -27,7 +33,6 @@
'LevelType',
'DerivedFrom',
)
-DESCRIPTION = re.compile(r'^atlas-([0-9a-zA-Z+]+)_description\.json$')
def _people(value: str) -> list[str]: