Skip to content

Commit 94dada4

Browse files
committed
STY: Various manual fixes
1 parent 66734bd commit 94dada4

File tree

12 files changed

+46
-37
lines changed

12 files changed

+46
-37
lines changed

fmriprep/cli/parser.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -116,8 +116,8 @@ def _bids_filter(value, parser):
116116
if Path(value).exists():
117117
try:
118118
return loads(Path(value).read_text(), object_hook=_filter_pybids_none_any)
119-
except JSONDecodeError:
120-
raise parser.error(f'JSON syntax error in: <{value}>.')
119+
except JSONDecodeError as e:
120+
raise parser.error(f'JSON syntax error in: <{value}>.') from e
121121
else:
122122
raise parser.error(f'Path does not exist: <{value}>.')
123123

@@ -130,8 +130,8 @@ def _slice_time_ref(value, parser):
130130
value = float(value)
131131
except ValueError:
132132
raise parser.error(
133-
"Slice time reference must be number, 'start', or 'middle'. " f'Received {value}.'
134-
)
133+
f"Slice time reference must be number, 'start', or 'middle'. Received {value}."
134+
) from None
135135
if not 0 <= value <= 1:
136136
raise parser.error(f'Slice time reference must be in range 0-1. Received {value}.')
137137
return value
@@ -784,7 +784,7 @@ def parse_args(args=None, namespace=None):
784784
import yaml
785785

786786
with open(opts.use_plugin) as f:
787-
plugin_settings = yaml.load(f, Loader=yaml.FullLoader)
787+
plugin_settings = yaml.safe_load(f)
788788
_plugin = plugin_settings.get('plugin')
789789
if _plugin:
790790
config.nipype.plugin = _plugin

fmriprep/cli/tests/test_parser.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ def test_bids_filter_file(tmp_path, capsys):
183183
_reset_config()
184184

185185

186-
@pytest.mark.parametrize('st_ref', (None, '0', '1', '0.5', 'start', 'middle'))
186+
@pytest.mark.parametrize('st_ref', (None, '0', '1', '0.5', 'start', 'middle')) # noqa: PT007
187187
def test_slice_time_ref(tmp_path, st_ref):
188188
bids_path = tmp_path / 'data'
189189
out_path = tmp_path / 'out'
@@ -200,13 +200,13 @@ def test_slice_time_ref(tmp_path, st_ref):
200200

201201
@pytest.mark.parametrize(
202202
('args', 'expectation'),
203-
(
203+
[
204204
([], False),
205205
(['--use-syn-sdc'], 'error'),
206206
(['--use-syn-sdc', 'error'], 'error'),
207207
(['--use-syn-sdc', 'warn'], 'warn'),
208208
(['--use-syn-sdc', 'other'], (SystemExit, ArgumentError)),
209-
),
209+
],
210210
)
211211
def test_use_syn_sdc(tmp_path, args, expectation):
212212
bids_path = tmp_path / 'data'

fmriprep/cli/tests/test_version.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
# https://www.nipreps.org/community/licensing/
2222
#
2323
"""Test version checks."""
24-
from datetime import datetime
24+
from datetime import datetime, timezone
2525
from os import getenv, geteuid
2626
from pathlib import Path
2727

@@ -71,7 +71,7 @@ def mock_get(*args, **kwargs):
7171
assert v == Version('1.1.0')
7272
assert cachefile.read_text().split('|') == [
7373
str(v),
74-
datetime.now().strftime(DATE_FMT),
74+
datetime.now(tz=timezone.utc).strftime(DATE_FMT),
7575
]
7676

7777
# Second check - test the cache file is read
@@ -139,7 +139,7 @@ def mock_get(*args, **kwargs):
139139
[
140140
'3laj#r???d|3akajdf#',
141141
'2.0.0|3akajdf#',
142-
'|'.join(('2.0.0', datetime.now().strftime(DATE_FMT), '')),
142+
'|'.join(('2.0.0', datetime.now(tz=timezone.utc).strftime(DATE_FMT), '')),
143143
'',
144144
],
145145
)
@@ -210,7 +210,7 @@ def test_readonly(tmp_path, monkeypatch):
210210
cachedir.mkdir(mode=0o555, exist_ok=True)
211211

212212
# Make sure creating the folder will raise the exception.
213-
with pytest.raises(OSError):
213+
with pytest.raises(OSError, match=r'Read-only file system|Permission denied'):
214214
(cachedir / 'fmriprep').mkdir(parents=True)
215215

216216
# Should not raise

fmriprep/cli/version.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222
#
2323
"""Version CLI helpers."""
2424

25-
from datetime import datetime
25+
from contextlib import suppress
26+
from datetime import datetime, timezone
2627
from pathlib import Path
2728

2829
import requests
@@ -40,6 +41,7 @@ def check_latest():
4041
latest = None
4142
date = None
4243
outdated = None
44+
now = datetime.now(tz=timezone.utc)
4345
cachefile = Path.home() / '.cache' / 'fmriprep' / 'latest'
4446
try:
4547
cachefile.parent.mkdir(parents=True, exist_ok=True)
@@ -49,23 +51,22 @@ def check_latest():
4951
if cachefile and cachefile.exists():
5052
try:
5153
latest, date = cachefile.read_text().split('|')
52-
except Exception:
54+
except Exception: # noqa: S110, BLE001
5355
pass
5456
else:
5557
try:
5658
latest = Version(latest)
57-
date = datetime.strptime(date, DATE_FMT)
59+
date = datetime.strptime(date, DATE_FMT).astimezone(timezone.utc)
5860
except (InvalidVersion, ValueError):
5961
latest = None
6062
else:
61-
if abs((datetime.now() - date).days) > RELEASE_EXPIRY_DAYS:
63+
if abs((now - date).days) > RELEASE_EXPIRY_DAYS:
6264
outdated = True
6365

6466
if latest is None or outdated is True:
65-
try:
67+
response = None
68+
with suppress(Exception):
6669
response = requests.get(url='https://pypi.org/pypi/fmriprep/json', timeout=1.0)
67-
except Exception:
68-
response = None
6970

7071
if response and response.status_code == 200:
7172
versions = [Version(rel) for rel in response.json()['releases'].keys()]
@@ -76,10 +77,8 @@ def check_latest():
7677
latest = None
7778

7879
if cachefile is not None and latest is not None:
79-
try:
80-
cachefile.write_text('|'.join(('%s' % latest, datetime.now().strftime(DATE_FMT))))
81-
except Exception:
82-
pass
80+
with suppress(OSError):
81+
cachefile.write_text(f'{latest}|{now.strftime(DATE_FMT)}')
8382

8483
return latest
8584

@@ -88,14 +87,13 @@ def is_flagged():
8887
"""Check whether current version is flagged."""
8988
# https://raw.githubusercontent.com/nipreps/fmriprep/master/.versions.json
9089
flagged = ()
91-
try:
90+
response = None
91+
with suppress(Exception):
9292
response = requests.get(
9393
url="""\
9494
https://raw.githubusercontent.com/nipreps/fmriprep/master/.versions.json""",
9595
timeout=1.0,
9696
)
97-
except Exception:
98-
response = None
9997

10098
if response and response.status_code == 200:
10199
flagged = response.json().get('flagged', {}) or {}

fmriprep/cli/workflow.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ def build_boilerplate(config_file, workflow):
215215

216216
config.loggers.cli.info('Generating an HTML version of the citation boilerplate...')
217217
try:
218-
check_call(cmd, timeout=10)
218+
check_call(cmd, timeout=10) # noqa: S603
219219
except (FileNotFoundError, CalledProcessError, TimeoutExpired):
220220
config.loggers.cli.warning('Could not generate CITATION.html file:\n%s', ' '.join(cmd))
221221

@@ -232,6 +232,6 @@ def build_boilerplate(config_file, workflow):
232232
]
233233
config.loggers.cli.info('Generating a LaTeX version of the citation boilerplate...')
234234
try:
235-
check_call(cmd, timeout=10)
235+
check_call(cmd, timeout=10) # noqa: S603
236236
except (FileNotFoundError, CalledProcessError, TimeoutExpired):
237237
config.loggers.cli.warning('Could not generate CITATION.tex file:\n%s', ' '.join(cmd))

fmriprep/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@
179179
from psutil import virtual_memory
180180

181181
_free_mem_at_start = round(virtual_memory().available / 1024**3, 1)
182-
except Exception:
182+
except ImportError:
183183
_free_mem_at_start = None
184184

185185
_oc_limit = 'n/a'
@@ -197,7 +197,7 @@
197197
_oc_limit = _proc_oc_kbytes.read_text().strip()
198198
if _oc_limit in ('0', 'n/a') and Path('/proc/sys/vm/overcommit_ratio').exists():
199199
_oc_limit = '{}%'.format(Path('/proc/sys/vm/overcommit_ratio').read_text().strip())
200-
except Exception:
200+
except Exception: # noqa: S110, BLE001
201201
pass
202202

203203

fmriprep/conftest.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,12 @@ def copytree_or_skip(source, target):
2222

2323
try:
2424
copytree(data_dir, target / data_dir.name)
25-
except Exception:
25+
except Exception: # noqa: BLE001
2626
pytest.skip(f'Cannot copy {data_dir!r} into {target / data_dir.name}. Probably in a zip.')
2727

2828

2929
@pytest.fixture(autouse=True)
30-
def populate_namespace(doctest_namespace, tmp_path):
30+
def _populate_namespace(doctest_namespace, tmp_path):
3131
doctest_namespace['copytree_or_skip'] = copytree_or_skip
3232
doctest_namespace['testdir'] = tmp_path
3333

fmriprep/data/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ def as_path(self, *segments) -> AbstractContextManager[Path]:
163163
"""
164164
return as_file(self.files.joinpath(*segments))
165165

166-
@cache
166+
@cache # noqa: B019
167167
def cached(self, *segments) -> Path:
168168
"""Ensure data is available as a :class:`~pathlib.Path`.
169169

fmriprep/utils/bids.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ def validate_input_dir(exec_env, bids_dir, participant_label, need_T1w=True):
233233
temp.write(json.dumps(validator_config_dict))
234234
temp.flush()
235235
try:
236-
subprocess.check_call(['bids-validator', str(bids_dir), '-c', temp.name])
236+
subprocess.check_call(['bids-validator', str(bids_dir), '-c', temp.name]) # noqa: S603, S607
237237
except FileNotFoundError:
238238
print('bids-validator does not appear to be installed', file=sys.stderr)
239239

@@ -263,10 +263,14 @@ def check_pipeline_version(pipeline_name, cvers, data_desc):
263263
Examples
264264
--------
265265
>>> check_pipeline_version('fMRIPrep', '23.2.0.dev0', 'sample_dataset_description.json')
266-
>>> check_pipeline_version('fMRIPrep', '23.2.0.dev0+gb2e14d98', 'sample_dataset_description.json')
266+
>>> check_pipeline_version(
267+
... 'fMRIPrep', '23.2.0.dev0+gb2e14d98', 'sample_dataset_description.json'
268+
... )
267269
>>> check_pipeline_version('fMRIPrep', '24.0.0', 'sample_dataset_description.json')
268270
'Previous output generated by version 23.2.0.dev0 found.'
269-
>>> check_pipeline_version('fMRIPrep', '24.0.0', 'legacy_dataset_description.json') # doctest: +ELLIPSIS
271+
>>> check_pipeline_version(
272+
... 'fMRIPrep', '24.0.0', 'legacy_dataset_description.json'
273+
... ) # doctest: +ELLIPSIS
270274
'Previous output generated by version 1.1.1rc5 found.'
271275
272276
Returns

fmriprep/workflows/base.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,7 @@ def init_single_subject_wf(subject_id: str):
237237
"Future versions of fMRIPrep will use alternative conventions. "
238238
"Please refer to the documentation before upgrading.",
239239
FutureWarning,
240+
stacklevel=1,
240241
)
241242

242243
spaces = config.workflow.spaces

0 commit comments

Comments
 (0)