Skip to content

Commit 8dd6c2b

Browse files
authored
Merge pull request #119 from templateflow/sty/run-ruff
MAINT: Run ruff and address some issues
2 parents 435037d + d004f3b commit 8dd6c2b

File tree

11 files changed

+216
-181
lines changed

11 files changed

+216
-181
lines changed

templateflow/__init__.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
11
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
22
# vi: set ft=python sts=4 ts=4 sw=4 et:
33
"""TemplateFlow is the Zone of Templates."""
4-
__packagename__ = "templateflow"
5-
__copyright__ = "2020, The TemplateFlow developers"
4+
__packagename__ = 'templateflow'
5+
__copyright__ = '2020, The TemplateFlow developers'
66
try:
77
from ._version import __version__
88
except ModuleNotFoundError:
9-
from importlib.metadata import version, PackageNotFoundError
9+
from importlib.metadata import PackageNotFoundError, version
1010
try:
1111
__version__ = version(__packagename__)
1212
except PackageNotFoundError:
13-
__version__ = "0+unknown"
13+
__version__ = '0+unknown'
1414
del version
1515
del PackageNotFoundError
1616

1717
import os
18-
from . import api
19-
from .conf import update, TF_USE_DATALAD
2018

19+
from . import api
20+
from .conf import TF_USE_DATALAD, update
2121

22-
if not TF_USE_DATALAD and os.getenv("TEMPLATEFLOW_AUTOUPDATE", "1") not in (
23-
"false",
24-
"off",
25-
"0",
26-
"no",
27-
"n",
22+
if not TF_USE_DATALAD and os.getenv('TEMPLATEFLOW_AUTOUPDATE', '1') not in (
23+
'false',
24+
'off',
25+
'0',
26+
'no',
27+
'n',
2828
):
2929
# trigger skeleton autoupdate
3030
update(local=True, overwrite=False, silent=True)
3131

3232
__all__ = [
33-
"__copyright__",
34-
"__packagename__",
35-
"__version__",
36-
"api",
37-
"update",
33+
'__copyright__',
34+
'__packagename__',
35+
'__version__',
36+
'api',
37+
'update',
3838
]

templateflow/_loader.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
except ImportError: # pragma: no cover
2828
from importlib_resources.abc import Traversable
2929

30-
__all__ = ["Loader"]
30+
__all__ = ['Loader']
3131

3232

3333
class Loader:
@@ -119,19 +119,19 @@ def _doc(self):
119119
directory.
120120
"""
121121
top_level = sorted(
122-
os.path.relpath(p, self.files) + "/"[: p.is_dir()]
122+
os.path.relpath(p, self.files) + '/'[: p.is_dir()]
123123
for p in self.files.iterdir()
124-
if p.name[0] not in (".", "_") and p.name != "tests"
124+
if p.name[0] not in ('.', '_') and p.name != 'tests'
125125
)
126126
doclines = [
127-
f"Load package files relative to ``{self._anchor}``.",
128-
"",
129-
"This package contains the following (top-level) files/directories:",
130-
"",
131-
*(f"* ``{path}``" for path in top_level),
127+
f'Load package files relative to ``{self._anchor}``.',
128+
'',
129+
'This package contains the following (top-level) files/directories:',
130+
'',
131+
*(f'* ``{path}``' for path in top_level),
132132
]
133133

134-
return "\n".join(doclines)
134+
return '\n'.join(doclines)
135135

136136
def readable(self, *segments) -> Traversable:
137137
"""Provide read access to a resource through a Path-like interface.

templateflow/api.py

Lines changed: 35 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,19 @@
22
import sys
33
from json import loads
44
from pathlib import Path
5+
56
from bids.layout import Query
67

7-
from .conf import TF_LAYOUT, TF_S3_ROOT, TF_USE_DATALAD, requires_layout
8+
from templateflow.conf import (
9+
TF_GET_TIMEOUT,
10+
TF_LAYOUT,
11+
TF_S3_ROOT,
12+
TF_USE_DATALAD,
13+
requires_layout,
14+
)
815

916
_layout_dir = tuple(
10-
item for item in dir(TF_LAYOUT) if item.startswith("get_")
17+
item for item in dir(TF_LAYOUT) if item.startswith('get_')
1118
)
1219

1320

@@ -59,13 +66,13 @@ def ls(template, **kwargs):
5966
6067
"""
6168
# Normalize extensions to always have leading dot
62-
if "extension" in kwargs:
63-
kwargs["extension"] = _normalize_ext(kwargs["extension"])
69+
if 'extension' in kwargs:
70+
kwargs['extension'] = _normalize_ext(kwargs['extension'])
6471

6572
return [
6673
Path(p) for p in TF_LAYOUT.get(
6774
template=Query.ANY if template is None else template,
68-
return_type="file",
75+
return_type='file',
6976
**kwargs
7077
)
7178
]
@@ -130,7 +137,7 @@ def get(template, raise_empty=False, **kwargs):
130137
out_file = ls(template, **kwargs)
131138

132139
if raise_empty and not out_file:
133-
raise Exception("No results found")
140+
raise Exception('No results found')
134141

135142
# Try DataLad first
136143
dl_missing = [p for p in out_file if not p.is_file()]
@@ -147,7 +154,7 @@ def get(template, raise_empty=False, **kwargs):
147154
not_fetched = [str(p) for p in out_file if not p.is_file() or p.stat().st_size == 0]
148155

149156
if not_fetched:
150-
msg = "Could not fetch template files: %s." % ", ".join(not_fetched)
157+
msg = 'Could not fetch template files: %s.' % ', '.join(not_fetched)
151158
if dl_missing and not TF_USE_DATALAD:
152159
msg += (
153160
"""\
@@ -222,7 +229,7 @@ def get_metadata(template):
222229
223230
"""
224231
tf_home = Path(TF_LAYOUT.root)
225-
filepath = tf_home / ("tpl-%s" % template) / "template_description.json"
232+
filepath = tf_home / ('tpl-%s' % template) / 'template_description.json'
226233

227234
# Ensure that template is installed and file is available
228235
if not filepath.is_file():
@@ -243,9 +250,9 @@ def get_citations(template, bibtex=False):
243250
244251
"""
245252
data = get_metadata(template)
246-
refs = data.get("ReferencesAndLinks", [])
253+
refs = data.get('ReferencesAndLinks', [])
247254
if isinstance(refs, dict):
248-
refs = [x for x in refs.values()]
255+
refs = list(refs.values())
249256

250257
if not bibtex:
251258
return refs
@@ -255,10 +262,10 @@ def get_citations(template, bibtex=False):
255262

256263
@requires_layout
257264
def __getattr__(key: str):
258-
key = key.replace("ls_", "get_")
265+
key = key.replace('ls_', 'get_')
259266
if (
260-
key.startswith("get_")
261-
and key not in ("get_metadata", "get_citations")
267+
key.startswith('get_')
268+
and key not in ('get_metadata', 'get_citations')
262269
and key not in _layout_dir
263270
):
264271
return TF_LAYOUT.__getattr__(key)
@@ -277,7 +284,7 @@ def _datalad_get(filepath):
277284
try:
278285
api.get(filepath, dataset=str(TF_LAYOUT.root))
279286
except IncompleteResultsError as exc:
280-
if exc.failed[0]["message"] == "path not associated with any dataset":
287+
if exc.failed[0]['message'] == 'path not associated with any dataset':
281288
from .conf import TF_GITHUB_SOURCE
282289

283290
api.install(path=TF_LAYOUT.root, source=TF_GITHUB_SOURCE, recursive=True)
@@ -288,47 +295,50 @@ def _datalad_get(filepath):
288295

289296
def _s3_get(filepath):
290297
from sys import stderr
291-
from tqdm import tqdm
298+
292299
import requests
300+
from tqdm import tqdm
293301

294302
path = filepath.relative_to(TF_LAYOUT.root).as_posix()
295-
url = f"{TF_S3_ROOT}/{path}"
303+
url = f'{TF_S3_ROOT}/{path}'
296304

297-
print("Downloading %s" % url, file=stderr)
305+
print('Downloading %s' % url, file=stderr)
298306
# Streaming, so we can iterate over the response.
299-
r = requests.get(url, stream=True)
307+
r = requests.get(url, stream=True, timeout=TF_GET_TIMEOUT)
300308

301309
# Total size in bytes.
302-
total_size = int(r.headers.get("content-length", 0))
310+
total_size = int(r.headers.get('content-length', 0))
303311
block_size = 1024
304312
wrote = 0
305313
if not filepath.is_file():
306314
filepath.unlink()
307315

308-
with filepath.open("wb") as f:
309-
with tqdm(total=total_size, unit="B", unit_scale=True) as t:
316+
with filepath.open('wb') as f:
317+
with tqdm(total=total_size, unit='B', unit_scale=True) as t:
310318
for data in r.iter_content(block_size):
311319
wrote = wrote + len(data)
312320
f.write(data)
313321
t.update(len(data))
314322

315323
if total_size != 0 and wrote != total_size:
316-
raise RuntimeError("ERROR, something went wrong")
324+
raise RuntimeError('ERROR, something went wrong')
317325

318326

319327
def _to_bibtex(doi, template, idx):
320-
if "doi.org" not in doi:
328+
if 'doi.org' not in doi:
321329
return doi
322330

323331
# Is a DOI URL
324332
import requests
325333

326334
response = requests.post(
327-
doi, headers={"Accept": "application/x-bibtex; charset=utf-8"}
335+
doi,
336+
headers={'Accept': 'application/x-bibtex; charset=utf-8'},
337+
timeout=TF_GET_TIMEOUT,
328338
)
329339
if not response.ok:
330340
print(
331-
f"Failed to convert DOI <{doi}> to bibtex, returning URL.",
341+
f'Failed to convert DOI <{doi}> to bibtex, returning URL.',
332342
file=sys.stderr,
333343
)
334344
return doi

templateflow/conf/__init__.py

Lines changed: 34 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,28 @@
11
"""Configuration and settings."""
2-
from os import getenv
32
import re
4-
from warnings import warn
5-
from pathlib import Path
63
from contextlib import suppress
74
from functools import wraps
5+
from os import getenv
6+
from pathlib import Path
7+
from warnings import warn
8+
89
from .._loader import Loader
910

1011
load_data = Loader(__package__)
1112

12-
TF_DEFAULT_HOME = Path.home() / ".cache" / "templateflow"
13-
TF_HOME = Path(getenv("TEMPLATEFLOW_HOME", str(TF_DEFAULT_HOME)))
14-
TF_GITHUB_SOURCE = "https://github.com/templateflow/templateflow.git"
15-
TF_S3_ROOT = "https://templateflow.s3.amazonaws.com"
16-
TF_USE_DATALAD = getenv("TEMPLATEFLOW_USE_DATALAD", "false").lower() in (
17-
"true",
18-
"on",
19-
"1",
20-
"yes",
21-
"y",
13+
TF_DEFAULT_HOME = Path.home() / '.cache' / 'templateflow'
14+
TF_HOME = Path(getenv('TEMPLATEFLOW_HOME', str(TF_DEFAULT_HOME)))
15+
TF_GITHUB_SOURCE = 'https://github.com/templateflow/templateflow.git'
16+
TF_S3_ROOT = 'https://templateflow.s3.amazonaws.com'
17+
TF_USE_DATALAD = getenv('TEMPLATEFLOW_USE_DATALAD', 'false').lower() in (
18+
'true',
19+
'on',
20+
'1',
21+
'yes',
22+
'y',
2223
)
2324
TF_CACHED = True
25+
TF_GET_TIMEOUT = 10
2426

2527

2628
def _init_cache():
@@ -34,6 +36,7 @@ def _init_cache():
3436
If the path reported above is not the desired location for TemplateFlow, \
3537
please set the TEMPLATEFLOW_HOME environment variable.""",
3638
ResourceWarning,
39+
stacklevel=2,
3740
)
3841
if TF_USE_DATALAD:
3942
try:
@@ -64,7 +67,7 @@ def wrapper(*args, **kwargs):
6467
from bids import __version__
6568

6669
raise RuntimeError(
67-
f"A layout with PyBIDS <{__version__}> could not be initiated"
70+
f'A layout with PyBIDS <{__version__}> could not be initiated'
6871
)
6972
return func(*args, **kwargs)
7073

@@ -85,6 +88,7 @@ def update(local=False, overwrite=True, silent=False):
8588
init_layout()
8689
# ensure the api uses the updated layout
8790
import importlib
91+
8892
from .. import api
8993

9094
importlib.reload(api)
@@ -96,19 +100,20 @@ def wipe():
96100
global TF_USE_DATALAD, TF_HOME
97101

98102
if TF_USE_DATALAD:
99-
print("TemplateFlow is configured in DataLad mode, wipe() has no effect")
103+
print('TemplateFlow is configured in DataLad mode, wipe() has no effect')
100104
return
101105

102106
import importlib
103107
from shutil import rmtree
108+
104109
from templateflow import api
105110

106111
def _onerror(func, path, excinfo):
107112
from pathlib import Path
108113

109114
if Path(path).exists():
110115
print(
111-
f"Warning: could not delete <{path}>, please clear the cache manually."
116+
f'Warning: could not delete <{path}>, please clear the cache manually.'
112117
)
113118

114119
rmtree(TF_HOME, onerror=_onerror)
@@ -132,32 +137,37 @@ def setup_home(force=False):
132137
def _update_datalad():
133138
from datalad.api import update
134139

135-
print("Updating TEMPLATEFLOW_HOME using DataLad ...")
140+
print('Updating TEMPLATEFLOW_HOME using DataLad ...')
136141
try:
137142
update(dataset=str(TF_HOME), recursive=True, merge=True)
138-
except Exception as e:
139-
warn(f"Error updating TemplateFlow's home directory (using DataLad): {e}")
143+
except Exception as e: # noqa: BLE001
144+
warn(
145+
f"Error updating TemplateFlow's home directory (using DataLad): {e}",
146+
stacklevel=2,
147+
)
148+
return False
140149
return True
141150

142151

143152
TF_LAYOUT = None
144153

145154

146155
def init_layout():
147-
from templateflow.conf.bids import Layout
148156
from bids.layout.index import BIDSLayoutIndexer
149157

158+
from templateflow.conf.bids import Layout
159+
150160
global TF_LAYOUT
151161
TF_LAYOUT = Layout(
152162
TF_HOME,
153163
validate=False,
154-
config="templateflow",
164+
config='templateflow',
155165
indexer=BIDSLayoutIndexer(
156166
validate=False,
157167
ignore=(
158-
re.compile(r"scripts/"),
159-
re.compile(r"/\."),
160-
re.compile(r"^\."),
168+
re.compile(r'scripts/'),
169+
re.compile(r'/\.'),
170+
re.compile(r'^\.'),
161171
),
162172
),
163173
)

0 commit comments

Comments
 (0)