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
4 changes: 4 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ Unreleased
==========
* Python 3.13 or newer, following `SPEC 0 <https://scientific-python.org/specs/spec-0000/>`__
(tested on 3.13 to 3.15).
* 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
root renames table from its text. The checks report the same issues as before.

26.0.0rc4 (December 3, 2026)
============================
Expand Down
45 changes: 45 additions & 0 deletions tfmanager/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@

from __future__ import annotations

import json
from collections.abc import Iterable
from dataclasses import dataclass, field

from .naming import parse
from .tables import NA, Table, dump_json, json_cell, write_tsv
from .tree import Tree, visible

#: atlases.tsv column -> atlas-<label>_description.json field (BIDS 1.11)
ATLAS_FIELDS = {
Expand Down Expand Up @@ -171,3 +177,42 @@ def templates_table(
}
)
return write_tsv(TEMPLATE_COLUMNS, rows)


@dataclass
class ArchiveIndex:
"""What the Archive-level files and checks need from the templates."""

descriptions: dict[str, dict] = field(default_factory=dict)
"""template_description.json of each template, by label."""
atlases: dict[str, list[str]] = field(default_factory=dict)
"""Atlas labels in each template's file names, in order of first appearance."""
targets: list[tuple[str, str]] = field(default_factory=list)
"""``(tpl-<label>/path, value)`` of every ``from`` and ``to`` entity of a transform."""


def collect_archive(trees: Iterable[Tree]) -> ArchiveIndex:
"""Read the templates of the Archive (templates.tsv, TF801 and TF803).

A template whose template_description.json is missing or not JSON is left out.
"""
index = ArchiveIndex()
for tree in trees:
data = tree.read_bytes('template_description.json')
if data is None:
continue
try:
index.descriptions[tree.label] = json.loads(data)
except ValueError:
continue
for path in visible(tree.files()):
f = parse(path)
if 'atlas' in f.entities:
found = index.atlases.setdefault(tree.label, [])
if f.entities['atlas'] not in found:
found.append(f.entities['atlas'])
if f.suffix == 'xfm':
for key in ('from', 'to'):
if key in f.entities:
index.targets.append((f'{tree.name}/{path}', f.entities[key]))
return index
25 changes: 25 additions & 0 deletions tfmanager/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,28 @@ def run_command(
output = (proc.stderr or proc.stdout or '').strip()
raise CommandError(f'`{" ".join(cmd[:2])}` failed: {output}')
return proc


def run_git(
repo: str | os.PathLike,
*args: str,
input: bytes | None = None, # noqa: A002 (subprocess's name)
env: Mapping[str, str] | None = None,
) -> bytes:
"""Run ``git -C repo args`` (no shell) and return its standard output as bytes.

Output stays binary, so that file names and file contents come back unchanged (use
``-z`` with listing commands). Raise :class:`CommandError` if git fails.
"""
full_env = {**os.environ, **env} if env else None
proc = subprocess.run( # noqa: S603
['git', '-C', os.fspath(repo), *args],
input=input,
capture_output=True,
env=full_env,
check=False,
)
if proc.returncode != 0:
output = proc.stderr.decode(errors='replace').strip()
raise CommandError(f'`git {" ".join(args[:1])}` failed: {output}')
return proc.stdout
17 changes: 17 additions & 0 deletions tfmanager/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
from __future__ import annotations

import json
import os

import pytest

from tfmanager.io import run_git
from tfmanager.tables import dump_json
from tfmanager.tree import MappingTree

Expand Down Expand Up @@ -93,3 +95,18 @@ def tree() -> MappingTree:

def with_description(**changes) -> MappingTree:
return make_tree(**{'template_description.json': json.dumps(description(**changes))})


@pytest.fixture
def git(monkeypatch):
"""Run git in a repository, isolated from the user's and the system's configuration."""
monkeypatch.setenv('GIT_CONFIG_GLOBAL', os.devnull)
monkeypatch.setenv('GIT_CONFIG_NOSYSTEM', '1')
for role in ('AUTHOR', 'COMMITTER'):
monkeypatch.setenv(f'GIT_{role}_NAME', 'TemplateFlow tests')
monkeypatch.setenv(f'GIT_{role}_EMAIL', 'tests@templateflow.invalid')

def run(repo, *args: str) -> str:
return run_git(repo, *args).decode()

return run
40 changes: 40 additions & 0 deletions tfmanager/tests/test_archive.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,43 @@ def test_renames_header(tmp_path):
root = _archive(tmp_path)
(root / 'renames.tsv').write_text('old_path\tnew_path\tdate\n')
assert any('header' in i.message for i in check_archive(root) if i.code == 'TF804')


def test_collect_archive():
from tfmanager.generate import collect_archive
from tfmanager.tree import MappingTree

index = collect_archive(
[
MappingTree(
'tpl-A',
{
'template_description.json': '{"Name": "A"}',
'tpl-A_res-1_atlas-Z_dseg.nii.gz': None,
'tpl-A_res-1_atlas-B_dseg.nii.gz': None,
'tpl-A_atlas-Z_dseg.tsv': 'index\tname\n',
'tpl-A_from-B+1_mode-image_xfm.h5': None,
'.hidden/tpl-A_atlas-H_dseg.tsv': '',
},
),
MappingTree(
'tpl-B', {'template_description.json': 'not JSON', 'tpl-B_atlas-Q_dseg.tsv': ''}
),
MappingTree('tpl-C', {'tpl-C_atlas-Q_dseg.tsv': ''}),
]
)
assert index.descriptions == {'A': {'Name': 'A'}}
assert index.atlases == {'A': ['Z', 'B']}
assert index.targets == [('tpl-A/tpl-A_from-B+1_mode-image_xfm.h5', 'B+1')]


def test_renames_problems():
from tfmanager.validate.archive import renames_problems

text = 'old_path\tnew_path\ntpl-A/x\ttpl-A/y\n'
assert renames_problems(text, lambda path: path == 'tpl-A/x') == [
'row 2: tpl-A/x still exists.',
'row 2: tpl-A/y does not exist.',
]
assert renames_problems(text, lambda path: True, installed=lambda template: False) == []
assert renames_problems('', lambda path: True) == ['The header must be old_path<TAB>new_path.']
130 changes: 129 additions & 1 deletion tfmanager/tests/test_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
import os
import zipfile

from tfmanager.tree import DirectoryTree, ZipTree
import pytest

from tfmanager import tree as tree_module
from tfmanager.io import CommandError, run_git
from tfmanager.tree import DirectoryTree, GitTree, ZipTree


def test_symlinks_are_not_followed(tmp_path):
Expand Down Expand Up @@ -40,3 +44,127 @@ def test_zip_tree(tmp_path):
assert trees[0].is_annexed('tpl-X_res-1_T1w.nii.gz')
assert not trees[0].is_annexed('template_description.json')
assert trees[0].read_text('template_description.json') == '{"Identifier": "X"}'


KEY = 'MD5E-s1--9dd4e461268c8034f5c8564e155c67a6.nii.gz'


def _repo(tmp_path, git):
"""A template repository: text, an executable, annexed files (locked and unlocked), a
symlink that is not annexed and a submodule."""
tpl = tmp_path / 'tpl-X'
(tpl / 'scripts').mkdir(parents=True)
git(tpl, 'init', '-q')
(tpl / '.gitattributes').write_text('* annex.largefiles=nothing\n')
(tpl / 'template_description.json').write_text('{"Identifier": "X"}')
(tpl / 'scripts' / 'run.sh').write_text('#!/bin/sh\n')
(tpl / 'scripts' / 'run.sh').chmod(0o755)
os.symlink(f'.git/annex/objects/Xx/Yy/{KEY}/{KEY}', tpl / 'tpl-X_res-1_T1w.nii.gz')
(tpl / 'tpl-X_res-2_T1w.nii.gz').write_text(f'/annex/objects/{KEY}\n')
os.symlink('template_description.json', tpl / 'tpl-X_res-1_T1w.json')
git(tpl, 'add', '-A')
git(tpl, 'commit', '-q', '-m', 'first')
head = git(tpl, 'rev-parse', 'HEAD').strip()
git(tpl, 'update-index', '--add', '--cacheinfo', f'160000,{head},sub')
git(tpl, 'commit', '-q', '-m', 'submodule')
return tpl


def test_git_tree(tmp_path, git):
tpl = _repo(tmp_path, git)
tree = GitTree(tpl)
assert tree.name == 'tpl-X'
assert list(tree.files()) == [
'.gitattributes',
'scripts/run.sh',
'template_description.json',
'tpl-X_res-1_T1w.nii.gz',
'tpl-X_res-2_T1w.nii.gz',
]
assert not tree.exists('tpl-X_res-1_T1w.json')
assert not tree.exists('sub')
assert tree.is_annexed('tpl-X_res-1_T1w.nii.gz')
assert tree.is_annexed('tpl-X_res-2_T1w.nii.gz')
assert not tree.is_annexed('template_description.json')
assert tree.read_bytes('tpl-X_res-1_T1w.nii.gz') is None
assert tree.read_text('template_description.json') == '{"Identifier": "X"}'
assert tree.read_bytes('missing') is None


def test_git_tree_matches_checkout(tmp_path, git):
tpl = _repo(tmp_path, git)
checkout, tree = DirectoryTree(tpl), GitTree(tpl)
(tpl / 'sub').mkdir()
assert list(checkout.files()) == list(tree.files())
for path in tree.files():
assert checkout.is_annexed(path) == tree.is_annexed(path), path
assert checkout.read_bytes(path) == tree.read_bytes(path), path


def test_git_tree_reads_commits(tmp_path, git, monkeypatch):
tpl = _repo(tmp_path, git)
(tpl / 'template_description.json').write_text('{"Identifier": "X", "Name": "X"}')
git(tpl, 'commit', '-q', '-am', 'second')
(tpl / 'template_description.json').write_text('not committed')
assert GitTree(tpl, 'HEAD~1').read_text('template_description.json') == '{"Identifier": "X"}'
assert GitTree(tpl, 'HEAD', name='tpl-Y').name == 'tpl-Y'
monkeypatch.setattr(tree_module, 'MAX_TEXT_BYTES', 20)
assert GitTree(tpl).read_bytes('template_description.json') is None


def test_git_tree_memory(tmp_path, git, monkeypatch):
"""Small files are read ahead up to MAX_CACHE_BYTES; others are read and not kept."""
tpl = tmp_path / 'tpl-X'
tpl.mkdir()
git(tpl, 'init', '-q')
sizes = {'a.json': 10, 'b.json': 20, 'c.json': 30, 'big.tsv': 80, 'bigger.tsv': 90}
(tpl / 'huge.txt').write_text('h' * 95) # over MAX_TEXT_BYTES (90 below): never read
for name, size in sizes.items():
(tpl / name).write_text(name[0] * size)
(tpl / 'pointer.nii.gz').write_text('/annex/objects/' + 'x' * 5000) # too long
git(tpl, 'add', '-A')
# A link whose target is too long to be an annex link
target = run_git(
tpl, 'hash-object', '-w', '--stdin', input=b'.git/annex/objects/' + b'x' * 5000
)
git(tpl, 'update-index', '--add', '--cacheinfo', f'120000,{target.decode().strip()},long')
git(tpl, 'commit', '-q', '-m', 'files')

calls = []

def counted(repo, *args, **kwargs):
calls.append(args[0])
return run_git(repo, *args, **kwargs)

monkeypatch.setattr(tree_module, 'run_git', counted)
monkeypatch.setattr(tree_module, 'MAX_TEXT_BYTES', 90)
tree = GitTree(tpl)
assert not tree.exists('long')
assert not tree.is_annexed('pointer.nii.gz')

# Everything fits: one read of git for every file
calls.clear()
assert {name: len(tree.read_bytes(name)) for name in sizes} == sizes
assert calls == ['cat-file']
assert tree.read_bytes('huge.txt') is None
assert sum(map(len, tree._blobs.values())) == sum(sizes.values())

monkeypatch.setattr(tree_module, 'MAX_CACHE_BYTES', 100)
tree = GitTree(tpl)
assert tree.read_text('bigger.tsv') == 'b' * 90 # kept, with a.json: 100 bytes
assert sum(map(len, tree._blobs.values())) == 100
calls.clear()
assert tree.read_text('a.json') == 'a' * 10
assert calls == []
for name, size in sizes.items():
assert tree.read_text(name) == name[0] * size
assert sum(map(len, tree._blobs.values())) == 100


def test_run_git(tmp_path, git):
tpl = _repo(tmp_path, git)
assert (
run_git(tpl, 'cat-file', '-p', 'HEAD:template_description.json') == b'{"Identifier": "X"}'
)
with pytest.raises(CommandError, match='git rev-parse'):
run_git(tmp_path, 'rev-parse', 'HEAD')
Loading