Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
176 lines (140 loc) · 5.32 KB
/
Copy pathcli.py
File metadata and controls
176 lines (140 loc) · 5.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2024 The NiPreps Developers <nipreps@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# We support and encourage derived works from this project, please read
# about our expectations at
#
# https://www.nipreps.org/community/licensing/
#
"""The TemplateFlow Python Client command-line interface (CLI)."""
from __future__ import annotations
import json
from pathlib import Path
import click
from acres import Loader as _Loader
from click.decorators import FC, Option, _param_memo
from templateflow.client import TemplateFlowClient
from templateflow.conf import _cache
load_data = _Loader(__spec__.parent)
ENTITY_SHORTHANDS = {
# 'template': ('--tpl', '-t'),
'resolution': ('--res',),
'density': ('--den',),
'atlas': ('-a',),
'suffix': ('-s',),
'desc': ('-d', '--description'),
'extension': ('--ext', '-x'),
'label': ('-l',),
'segmentation': ('--seg',),
}
ENTITY_EXCLUDE = {'template', 'description'}
CLIENT = TemplateFlowClient(cache=_cache)
CACHE = CLIENT.cache
CONFIG = CACHE.config
CACHE.ensure()
TEMPLATE_LIST = [d.name[4:] for d in CONFIG.root.iterdir() if d.name.startswith('tpl-')]
def _nulls(s):
return None if s == 'null' else s
def entity_opts():
"""Attaches all entities as options to the command."""
entities = json.loads(load_data('conf/config.json').read_text())['entities']
args = [
(f'--{e["name"]}', *ENTITY_SHORTHANDS.get(e['name'], ()))
for e in entities
if e['name'] not in ENTITY_EXCLUDE
]
def decorator(f: FC) -> FC:
for arg in reversed(args):
_param_memo(f, Option(arg, type=str, default=[], multiple=True))
return f
return decorator
@click.group()
@click.version_option(message='TemplateFlow Python Client %(version)s')
def main():
"""The TemplateFlow Python Client command-line interface (CLI)."""
pass
@main.command()
def config():
"""Print-out configuration."""
click.echo(f"""Current TemplateFlow settings:
TEMPLATEFLOW_HOME={CONFIG.root}
TEMPLATEFLOW_USE_DATALAD={'on' if CONFIG.use_datalad else 'off'}
TEMPLATEFLOW_AUTOUPDATE={'on' if CONFIG.autoupdate else 'off'}
Home layout: {CACHE.generation}
""")
@main.command()
def wipe():
"""Wipe out a local S3 (direct-download) TemplateFlow Archive."""
from templateflow.conf import wipe as _wipe
if CONFIG.use_datalad:
_wipe() # DataLad homes are never wiped out: this only says so
return
click.echo(f'This will wipe out all data downloaded into {CONFIG.root}.')
if click.confirm('Do you want to continue?'):
value = click.prompt(
f'Please write the path of your local archive ({CONFIG.root})',
default='(abort)',
show_default=False,
)
if value.strip() == str(CONFIG.root):
_wipe()
click.echo(f'{CONFIG.root} was wiped out.')
return
click.echo(f'Aborted! {CONFIG.root} WAS NOT wiped out.')
@main.command()
@click.option('--local', is_flag=True, help='Use the skeleton bundled with the client.')
@click.option('--overwrite/--no-overwrite', default=True)
@click.option(
'--migrate',
is_flag=True,
help=(
'Move a home created by templateflow 25.x or older to the TemplateFlow 2.0 names: '
'stubs of old names are removed, and downloaded files move to their new names. '
'Older clients sharing the home lose the old names until they update it.'
),
)
def update(local, overwrite, migrate):
"""Update the local TemplateFlow Archive."""
from templateflow.conf import update as _update
try:
updated = _update(local=local, overwrite=overwrite, migrate=migrate)
except RuntimeError as exc:
raise click.ClickException(str(exc)) from exc
click.echo(
f'Successfully updated local TemplateFlow Archive: {CONFIG.root}.'
if updated
else 'TemplateFlow Archive not updated.'
)
@main.command()
@entity_opts()
@click.argument('template', type=click.Choice(TEMPLATE_LIST))
def ls(template, **kwargs):
"""List the assets corresponding to template and optional filters."""
entities = {k: _nulls(v) for k, v in kwargs.items() if v != ''}
click.echo('\n'.join(f'{match}' for match in CLIENT.ls(template, **entities)))
@main.command()
@entity_opts()
@click.argument('template', type=click.Choice(TEMPLATE_LIST))
def get(template, **kwargs):
"""Fetch the assets corresponding to template and optional filters."""
entities = {k: _nulls(v) for k, v in kwargs.items() if v != ''}
paths = CLIENT.get(template, **entities)
filenames = [str(paths)] if isinstance(paths, Path) else [str(file) for file in paths]
click.echo('\n'.join(filenames))
if __name__ == '__main__':
""" Install entry-point """
main()