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
19 changes: 19 additions & 0 deletions .github/workflows/pythonapp.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,25 @@ jobs:
- name: Test
run: python -m pytest -o addopts="" --doctest-modules tfmanager

annex:
# tfmgr migrate apply on a real git-annex repository (skipped in the test job)
runs-on: ubuntu-26.04
steps:
- uses: actions/checkout@v7
- name: Set up Python 3.13
uses: actions/setup-python@v7
with:
python-version: '3.13'
- name: Install git-annex
run: |
sudo apt-get update
sudo apt-get install -y git-annex
git annex version
- name: Install with test dependencies
run: python -m pip install ".[test]"
- name: Test with git-annex
run: python -m pytest -o addopts="" -m annex -rs tfmanager

build:

runs-on: ubuntu-26.04
Expand Down
24 changes: 24 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,30 @@ Unreleased
config ``edits`` may create a sidecar (``create: true``): the migration describes the
``desc`` and ``atlas`` values that renames drop, corrects authors, broken links and the
ages of the dhcp surface templates (postmenstrual weeks).
* New commands ``tfmgr migrate plan``, ``apply`` and ``verify`` move templates to
TemplateFlow 2.0. ``plan (-t tpl-<label> | --all) --source ZIP|DIR -o OUT`` writes, for
each template, ``plan.json`` (what ``apply`` reads: fingerprints and manifests of the
base and the result, the renames with their rules, the text and git blob of each file
written, the findings, the validation it predicts and the two commit messages),
``plan.md`` (the complete plan, with diffs, for review), ``pr.md`` (the body of the
template's pull request, within GitHub's limit) and ``renames.tsv``, and exits with 1
when a plan is blocked. ``--headers`` and ``--labels`` add facts read later,
``--authored DIR`` adds files written by hand (``DIR/tpl-<label>/<path>``), and
``--config`` replaces the shipped config. ``apply PLAN DIR`` builds two commits with git
plumbing, the file names and then the metadata (a commit that would change nothing is
left out: a template planned again once its README is written gets one), checks them
(fingerprints, annex keys, only planned paths changed, the validation predicted) and
only then creates and checks out the branch ``migrate/2.0.0``. It refuses a blocked
plan, a checkout that is not the plan's base (listing what differs), changes in the
worktree, an existing branch, an ``adjusted/`` branch and unlocked annexed files; it
rolls back on failure and never pushes. ``--dry-run`` builds the commits in a temporary
object store. ``verify PLAN DIR [--ref REF]`` checks a commit, such as a rebased pull
request, against the plan. A CI job runs these tests with git-annex.
* A plan simulates the legacy skeleton the superdataset builds (M301, blocking): every
name that released clients know must stay, with the rule of
templateflow/templateflow#219 for files merged into another. ``--legacy-skeleton ZIP``
gives the exact names; without it, the gate checks every name the skeleton may list (the
template's files and the old paths of its rows).
* 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
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ norecursedirs =
.github
addopts = -svx --doctest-modules
doctest_optionflags = ALLOW_UNICODE NORMALIZE_WHITESPACE
markers =
annex: needs git-annex (skipped without it)
env =
PYTHONHASHSEED=0
filterwarnings =
Expand Down
234 changes: 234 additions & 0 deletions tfmanager/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,240 @@ def labels(archive, templates, needs, output):
click.echo(f'{len(found)} files read, {len(tables)} GIFTI label tables.', err=True)


@migrate.command('plan')
@click.option(
'-t', '--template', 'templates', multiple=True, help='Plan this template (tpl-<label>).'
)
@click.option('--all', 'everything', is_flag=True, help='Plan every template of the source.')
@click.option(
'--source',
required=True,
type=click.Path(exists=True),
help='A v2 skeleton zip, a template checkout, or an Archive checkout.',
)
@click.option(
'-o',
'--output',
required=True,
type=click.Path(file_okay=False, writable=True),
help='Write OUTPUT/tpl-<label>/{plan.json,plan.md,pr.md,renames.tsv} (and summary.md).',
)
@click.option('--date', help='Date of the CHANGES entry, YYYY-MM-DD (default: today).')
@click.option(
'--config',
'config_file',
type=click.Path(exists=True, dir_okay=False),
help='A config file instead of the one shipped with tfmanager.',
)
@click.option(
'--authored',
type=click.Path(exists=True, file_okay=False),
help='Files written by hand, as AUTHORED/tpl-<label>/<path> (README.md, docs/...).',
)
@click.option(
'--headers',
'headers_file',
type=click.Path(exists=True, dir_okay=False),
help='Header facts read later (tfmgr migrate headers), added to those shipped.',
)
@click.option(
'--labels',
'labels_dir',
type=click.Path(exists=True, file_okay=False),
help='Label facts read later (tfmgr migrate labels -o DIR), added to those shipped.',
)
@click.option(
'--legacy-skeleton',
type=click.Path(exists=True, dir_okay=False),
help="The legacy skeleton zip, for the exact names of M301's check.",
)
def plan(
templates,
everything,
source,
output,
date,
config_file,
authored,
headers_file,
labels_dir,
legacy_skeleton,
):
"""Plan the migration of templates to TemplateFlow 2.0 (nothing is changed).

For each template, writes plan.json (what `tfmgr migrate apply` reads), plan.md (the
complete plan, for review), pr.md (the body of its pull request) and renames.tsv (its
rows); with --all, also summary.md.

Exits with 0 when every plan is ready, with 1 when a plan is blocked (plan.md lists
the findings that need a decision), and with 2 on errors.
"""
import datetime
import hashlib
from importlib.resources import files

from . import __version__
from .migrate.config import ConfigError, load_config
from .migrate.engine import plan_template
from .migrate.headers import BUNDLED as HEADERS
from .migrate.headers import HeaderIndex
from .migrate.labels import BUNDLED as LABELS
from .migrate.labels import LabelIndex
from .migrate.legacy import load_legacy_zip
from .migrate.report import document, summary_md, write_plan
from .migrate.snapshot import load_source

if bool(templates) == everything:
raise click.UsageError('Give -t tpl-<label> (one or more) or --all.')

def sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()

data = files('tfmanager.migrate').joinpath('data')
try:
date = date or datetime.date.today().isoformat()
datetime.date.fromisoformat(date)
config = load_config(config_file)
snapshots = load_source(source, None if everything else templates)
headers = HeaderIndex.bundled()
inputs = {
'source': {'name': Path(source).name},
'config': {'version': config.version, 'digest': config.digest},
'headers': {'bundled': sha256(data.joinpath(HEADERS).read_bytes())},
'labels': {'bundled': [sha256(data.joinpath(name).read_bytes()) for name in LABELS]},
}
if config_file:
inputs['config']['file'] = Path(config_file).name
if headers_file:
extra = HeaderIndex.from_file(headers_file)
headers = HeaderIndex({**headers.headers, **extra.headers})
inputs['headers']['file'] = sha256(Path(headers_file).read_bytes())
labels = LabelIndex.bundled()
if labels_dir:
extra = LabelIndex.from_files(*(Path(labels_dir) / name for name in LABELS))
labels = LabelIndex(
{**labels.labels, **extra.labels}, {**labels.tables, **extra.tables}
)
inputs['labels']['files'] = [
sha256((Path(labels_dir) / name).read_bytes()) for name in LABELS
]
legacy = None
if legacy_skeleton:
legacy = load_legacy_zip(legacy_skeleton)
inputs['legacy_skeleton'] = {
'name': Path(legacy_skeleton).name,
'sha256': sha256(Path(legacy_skeleton).read_bytes()),
}
except (ConfigError, ValueError, OSError) as exc:
click.echo(f'tfmgr migrate plan failed: {exc}', err=True)
raise SystemExit(2) from exc

out, docs = Path(output), {}
for name, snapshot in snapshots.items():
written = {}
if authored and (Path(authored) / name).is_dir():
root = Path(authored) / name
written = {
p.relative_to(root).as_posix(): p.read_bytes()
for p in sorted(root.rglob('*'))
if p.is_file()
}
try:
result = plan_template(
snapshot,
config,
headers,
date=date,
authored=written,
labels=labels,
legacy=None if legacy is None else legacy.get(name, set()),
)
except ValueError as exc:
click.echo(f'{name}: planning failed: {exc}', err=True)
raise SystemExit(2) from exc
info = {
**inputs,
'source': {**inputs['source'], **snapshot.origin},
'authored': {p: sha256(d) for p, d in written.items()},
}
doc = document(result, snapshot, config, version=__version__, date=date, inputs=info)
write_plan(out / name, doc, snapshot)
docs[name] = doc
blocking = sum(f['blocking'] for f in doc['findings'])
state = f'blocked ({blocking} findings)' if blocking else 'ready'
click.echo(f'{name}: {state}', err=True)
if everything:
(out / 'summary.md').write_text(summary_md(docs))
if any(d['status'] != 'ready' for d in docs.values()):
raise SystemExit(1)


@migrate.command('apply')
@click.argument('plan_file', type=click.Path(exists=True, dir_okay=False))
@click.argument('checkout', type=click.Path(exists=True, file_okay=False))
@click.option('--branch', help="The branch to create (default: the plan's, migrate/2.0.0).")
@click.option('--dry-run', is_flag=True, help='Build and check the commits, and keep nothing.')
def apply_(plan_file, checkout, branch, dry_run):
"""Apply a plan to a checkout of its template: commits on a new branch.

The first commit renames files (annexed files keep their keys), the second writes the
metadata; a commit that would change nothing is left out. They are built and checked
before any branch is created; the branch is then checked out. Nothing is pushed.

Exits with 1 when the plan does not apply (nothing was changed), and with 2 on errors.
"""
from .io import CommandError
from .migrate.apply import LABELS, ApplyError, apply_plan, load_plan

try:
doc, digest = load_plan(plan_file)
done = apply_plan(doc, checkout, plan_sha=digest, branch=branch, dry_run=dry_run)
except ApplyError as exc:
click.echo(f'tfmgr migrate apply: {exc}', err=True)
raise SystemExit(1) from exc
except (CommandError, OSError, ValueError) as exc:
click.echo(f'tfmgr migrate apply failed: {exc}', err=True)
raise SystemExit(2) from exc
for check in done.checks:
click.echo(f'ok: {check}')
for part, commit in done.commits:
click.echo(f'{LABELS[part]}: {commit}')
if done.dry_run:
click.echo('Dry run: nothing was kept, and the repository is unchanged.')
return
pr = Path(plan_file).with_name('pr.md')
click.echo(
f'{done.branch} is checked out. Next: push it (git push origin {done.branch}), '
f'open the pull request with {pr} as its body, and replay its rows through the '
'compatibility tests of the Python client.'
)


@migrate.command('verify')
@click.argument('plan_file', type=click.Path(exists=True, dir_okay=False))
@click.argument('checkout', type=click.Path(exists=True, file_okay=False))
@click.option('--ref', default='HEAD', show_default=True, help='The commit to check.')
def verify(plan_file, checkout, ref):
"""Check that a commit (e.g. a rebased pull request) is the result of a plan.

Exits with 1 when it is not (the differences are listed), and with 2 on errors.
"""
from .io import CommandError
from .migrate.apply import ApplyError, load_plan, verify_plan

try:
doc, _ = load_plan(plan_file)
problems = verify_plan(doc, checkout, ref)
except (ApplyError, CommandError, OSError, ValueError) as exc:
click.echo(f'tfmgr migrate verify failed: {exc}', err=True)
raise SystemExit(2) from exc
for problem in problems:
click.echo(problem, err=True)
if problems:
raise SystemExit(1)
click.echo(f'{ref} is the result of the plan.')


@cli.command()
@click.argument(
'template_dir', type=click.Path(exists=True, file_okay=False), default='.', required=False
Expand Down
Loading