forked from templateflow/python-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
151 lines (119 loc) · 4.48 KB
/
cli.py
File metadata and controls
151 lines (119 loc) · 4.48 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
# 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 click.decorators import FC, Option, _param_memo
from templateflow import __package__, api
from acres import Loader as _Loader
from templateflow.conf import TF_AUTOUPDATE, TF_HOME, TF_USE_DATALAD
load_data = _Loader(__package__)
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'}
TEMPLATE_LIST = api.get_templates()
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={TF_HOME}
TEMPLATEFLOW_USE_DATALAD={'on' if TF_USE_DATALAD else 'off'}
TEMPLATEFLOW_AUTOUPDATE={'on' if TF_AUTOUPDATE else 'off'}
""")
@main.command()
def wipe():
"""Wipe out a local S3 (direct-download) TemplateFlow Archive."""
click.echo(f'This will wipe out all data downloaded into {TF_HOME}.')
if click.confirm('Do you want to continue?'):
value = click.prompt(
f'Please write the path of your local archive ({TF_HOME})',
default='(abort)',
show_default=False,
)
if value.strip() == str(TF_HOME):
from templateflow.conf import wipe
wipe()
click.echo(f'{TF_HOME} was wiped out.')
return
click.echo(f'Aborted! {TF_HOME} WAS NOT wiped out.')
@main.command()
@click.option('--local', is_flag=True)
@click.option('--overwrite/--no-overwrite', default=True)
def update(local, overwrite):
"""Update the local TemplateFlow Archive."""
from templateflow.conf import update as _update
click.echo(
f'Successfully updated local TemplateFlow Archive: {TF_HOME}.'
if _update(local=local, overwrite=overwrite)
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 api.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 = api.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()