Skip to content

Commit ac44a3a

Browse files
authored
Merge pull request #2857 from mgxd/sty/pre-commit
MAINT: Add `pre-commit`, dev installation for consistent styling
2 parents 469384e + fd941ff commit ac44a3a

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+1694
-1204
lines changed

.git-blame-ignore-revs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# 2022-09-22 - [email protected] - STY: black/isort the docker wrapper
2+
9976458388f369cba4b7d81359acc40b52f6621c
3+
# 2022-09-22 - [email protected] - STY: Apply black/isort to codebase
4+
7eedab8b29497cee1d8dd540c2266e740f484a86
15
# 2021-11-05 - [email protected] - STY: Update black config
26
d2ad20301306f283d504ec7b5a1bd73ce58c2b11
37
# 2021-09-22 - [email protected] - sty: run black

.github/workflows/contrib.yml

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,20 @@ jobs:
2323
python-version: [3.9]
2424

2525
steps:
26-
- uses: actions/checkout@v2
27-
with:
28-
submodules: recursive
29-
fetch-depth: 0
26+
- uses: actions/checkout@v3
3027
- name: Set up Python ${{ matrix.python-version }}
31-
uses: actions/setup-python@v2
28+
uses: actions/setup-python@v4
3229
with:
3330
python-version: ${{ matrix.python-version }}
3431
- name: Display Python version
3532
run: python -c "import sys; print(sys.version)"
36-
- name: Install flake8
37-
run: python -m pip install flake8
33+
- name: Install black/isort
34+
run: python -m pip install black isort
3835
- name: Check fMRIPrep
39-
run: python -m flake8 fmriprep
36+
run: |
37+
python -m black --check fmriprep
38+
python -m isort --check fmriprep
4039
- name: Check wrapper
41-
run: python -m flake8 wrapper
40+
run: |
41+
python -m black --check wrapper
42+
python -m isort --check wrapper

.pre-commit-config.yaml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
repos:
2+
- repo: https://github.com/pre-commit/pre-commit-hooks
3+
rev: v2.4.0
4+
hooks:
5+
- id: trailing-whitespace
6+
- id: end-of-file-fixer
7+
- id: check-yaml
8+
- id: check-added-large-files
9+
- repo: https://github.com/psf/black
10+
rev: 22.3.0
11+
hooks:
12+
- id: black
13+
files: ^fmriprep/
14+
- repo: https://github.com/pycqa/isort
15+
rev: 5.10.1
16+
hooks:
17+
- id: isort
18+
files: ^fmriprep/

fmriprep/__about__.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,18 @@
2222
#
2323
"""Base module variables."""
2424
from ._version import get_versions
25+
2526
__version__ = get_versions()['version']
2627
del get_versions
2728

2829
__packagename__ = 'fmriprep'
2930
__copyright__ = 'Copyright 2022, The NiPreps Developers'
30-
__credits__ = ('Contributors: please check the ``.zenodo.json`` file at the top-level folder'
31-
'of the repository')
31+
__credits__ = (
32+
'Contributors: please check the ``.zenodo.json`` file at the top-level folder'
33+
'of the repository'
34+
)
3235
__url__ = 'https://github.com/nipreps/fmriprep'
3336

34-
DOWNLOAD_URL = (
35-
'https://github.com/nipreps/{name}/archive/{ver}.tar.gz'.format(
36-
name=__packagename__, ver=__version__))
37+
DOWNLOAD_URL = 'https://github.com/nipreps/{name}/archive/{ver}.tar.gz'.format(
38+
name=__packagename__, ver=__version__
39+
)

fmriprep/__init__.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,7 @@
22
# vi: set ft=python sts=4 ts=4 sw=4 et:
33
"""Top-module metadata."""
44

5-
from .__about__ import (
6-
__copyright__,
7-
__credits__,
8-
__packagename__,
9-
__version__,
10-
)
5+
from .__about__ import __copyright__, __credits__, __packagename__, __version__
116

127
__all__ = [
138
'__copyright__',
@@ -19,8 +14,9 @@
1914
# Silence PyBIDS warning for extension entity behavior
2015
# Can be removed once minimum PyBIDS dependency hits 0.14
2116
try:
22-
from packaging.version import Version
2317
import bids
18+
from packaging.version import Version
19+
2420
if Version(bids.__version__) < Version('0.14'):
2521
bids.config.set_option('extension_initial_dot', True)
2622
except (ImportError, ValueError):

fmriprep/__main__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@
2424

2525
if __name__ == '__main__':
2626
import sys
27+
2728
from . import __name__ as module
29+
2830
# `python -m <module>` typically displays the command as __main__.py
2931
if '__main__.py' in sys.argv[0]:
3032
sys.argv[0] = '%s -m %s' % (sys.executable, module)

fmriprep/_warnings.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
# https://www.nipreps.org/community/licensing/
2222
#
2323
"""Manipulate Python warnings."""
24-
import warnings
2524
import logging
25+
import warnings
2626

2727
_wlog = logging.getLogger("py.warnings")
2828
_wlog.addHandler(logging.NullHandler())
@@ -34,9 +34,7 @@ def _warn(message, category=None, stacklevel=1, source=None):
3434
category = type(category).__name__
3535
category = category.replace("type", "WARNING")
3636

37-
logging.getLogger("py.warnings").warning(
38-
f"{category or 'WARNING'}: {message}"
39-
)
37+
logging.getLogger("py.warnings").warning(f"{category or 'WARNING'}: {message}")
4038

4139

4240
def _showwarning(message, category, filename, lineno, file=None, line=None):

fmriprep/cli/parser.py

Lines changed: 31 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#
2323
"""Parser."""
2424
import sys
25+
2526
from .. import config
2627

2728

@@ -30,15 +31,14 @@ def _build_parser(**kwargs):
3031
3132
``kwargs`` are passed to ``argparse.ArgumentParser`` (mainly useful for debugging).
3233
"""
34+
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
3335
from functools import partial
3436
from pathlib import Path
35-
from argparse import (
36-
ArgumentParser,
37-
ArgumentDefaultsHelpFormatter,
38-
)
37+
38+
from niworkflows.utils.spaces import OutputReferencesAction, Reference
3939
from packaging.version import Version
40+
4041
from .version import check_latest, is_flagged
41-
from niworkflows.utils.spaces import Reference, OutputReferencesAction
4242

4343
def _path_exists(path, parser):
4444
"""Ensure a given path exists."""
@@ -61,25 +61,24 @@ def _min_one(value, parser):
6161
return value
6262

6363
def _to_gb(value):
64-
scale = {"G": 1, "T": 10 ** 3, "M": 1e-3, "K": 1e-6, "B": 1e-9}
64+
scale = {"G": 1, "T": 10**3, "M": 1e-3, "K": 1e-6, "B": 1e-9}
6565
digits = "".join([c for c in value if c.isdigit()])
66-
units = value[len(digits):] or "M"
66+
units = value[len(digits) :] or "M"
6767
return int(digits) * scale[units[0]]
6868

6969
def _drop_sub(value):
7070
return value[4:] if value.startswith("sub-") else value
7171

7272
def _filter_pybids_none_any(dct):
7373
import bids
74+
7475
return {
75-
k: bids.layout.Query.NONE
76-
if v is None
77-
else (bids.layout.Query.ANY if v == "*" else v)
76+
k: bids.layout.Query.NONE if v is None else (bids.layout.Query.ANY if v == "*" else v)
7877
for k, v in dct.items()
7978
}
8079

8180
def _bids_filter(value, parser):
82-
from json import loads, JSONDecodeError
81+
from json import JSONDecodeError, loads
8382

8483
if value:
8584
if Path(value).exists():
@@ -98,17 +97,16 @@ def _slice_time_ref(value, parser):
9897
try:
9998
value = float(value)
10099
except ValueError:
101-
raise parser.error("Slice time reference must be number, 'start', or 'middle'. "
102-
f"Received {value}.")
100+
raise parser.error(
101+
"Slice time reference must be number, 'start', or 'middle'. " f"Received {value}."
102+
)
103103
if not 0 <= value <= 1:
104104
raise parser.error(f"Slice time reference must be in range 0-1. Received {value}.")
105105
return value
106106

107107
verstr = f"fMRIPrep v{config.environment.version}"
108108
currentv = Version(config.environment.version)
109-
is_release = not any(
110-
(currentv.is_devrelease, currentv.is_prerelease, currentv.is_postrelease)
111-
)
109+
is_release = not any((currentv.is_devrelease, currentv.is_prerelease, currentv.is_postrelease))
112110

113111
parser = ArgumentParser(
114112
description="fMRIPrep: fMRI PREProcessing workflows v{}".format(
@@ -206,7 +204,7 @@ def _slice_time_ref(value, parser):
206204
metavar="PATH",
207205
type=Path,
208206
help="Path to a PyBIDS database folder, for faster indexing (especially "
209-
"useful for large datasets). Will be created if not present."
207+
"useful for large datasets). Will be created if not present.",
210208
)
211209

212210
g_perfm = parser.add_argument_group("Options to handle performance")
@@ -239,8 +237,7 @@ def _slice_time_ref(value, parser):
239237
g_perfm.add_argument(
240238
"--low-mem",
241239
action="store_true",
242-
help="attempt to reduce memory usage (will increase disk usage "
243-
"in working directory)",
240+
help="attempt to reduce memory usage (will increase disk usage " "in working directory)",
244241
)
245242
g_perfm.add_argument(
246243
"--use-plugin",
@@ -250,9 +247,7 @@ def _slice_time_ref(value, parser):
250247
type=IsFile,
251248
help="nipype plugin configuration file",
252249
)
253-
g_perfm.add_argument(
254-
"--anat-only", action="store_true", help="run anatomical workflows only"
255-
)
250+
g_perfm.add_argument("--anat-only", action="store_true", help="run anatomical workflows only")
256251
g_perfm.add_argument(
257252
"--boilerplate_only",
258253
action="store_true",
@@ -321,7 +316,7 @@ def _slice_time_ref(value, parser):
321316
default=False,
322317
help="""\
323318
Output individual echo time series with slice, motion and susceptibility correction. \
324-
Useful for further Tedana processing post-fMRIPrep."""
319+
Useful for further Tedana processing post-fMRIPrep.""",
325320
)
326321

327322
g_conf.add_argument(
@@ -370,9 +365,9 @@ def _slice_time_ref(value, parser):
370365
default=None,
371366
type=SliceTimeRef,
372367
help="The time of the reference slice to correct BOLD values to, as a fraction "
373-
"acquisition time. 0 indicates the start, 0.5 the midpoint, and 1 the end "
374-
"of acquisition. The alias `start` corresponds to 0, and `middle` to 0.5. "
375-
"The default value is 0.5.",
368+
"acquisition time. 0 indicates the start, 0.5 the midpoint, and 1 the end "
369+
"of acquisition. The alias `start` corresponds to 0, and `middle` to 0.5. "
370+
"The default value is 0.5.",
376371
)
377372
g_conf.add_argument(
378373
"--dummy-scans",
@@ -438,8 +433,7 @@ def _slice_time_ref(value, parser):
438433
action="store",
439434
default=1.5,
440435
type=float,
441-
help="Threshold for flagging a frame as an outlier on the basis of standardised "
442-
"DVARS",
436+
help="Threshold for flagging a frame as an outlier on the basis of standardised " "DVARS",
443437
)
444438

445439
# ANTs options
@@ -499,7 +493,7 @@ def _slice_time_ref(value, parser):
499493
const="error",
500494
default=False,
501495
help="EXPERIMENTAL: Use fieldmap-free distortion correction; "
502-
"if unable, error (default) or warn based on optional argument.",
496+
"if unable, error (default) or warn based on optional argument.",
503497
)
504498
g_syn.add_argument(
505499
"--force-syn",
@@ -562,7 +556,7 @@ def _slice_time_ref(value, parser):
562556
help="Organization of outputs. bids (default) places fMRIPrep derivatives "
563557
"directly in the output directory, and defaults to placing FreeSurfer "
564558
"derivatives in <output-dir>/sourcedata/freesurfer. legacy creates "
565-
"derivative datasets as subdirectories of outputs."
559+
"derivative datasets as subdirectories of outputs.",
566560
)
567561
g_other.add_argument(
568562
"-w",
@@ -597,7 +591,8 @@ def _slice_time_ref(value, parser):
597591
action="store",
598592
metavar="FILE",
599593
help="Use pre-generated configuration file. Values in file will be overridden "
600-
"by command-line arguments.")
594+
"by command-line arguments.",
595+
)
601596
g_other.add_argument(
602597
"--write-graph",
603598
action="store_true",
@@ -608,8 +603,7 @@ def _slice_time_ref(value, parser):
608603
"--stop-on-first-crash",
609604
action="store_true",
610605
default=False,
611-
help="Force stopping on first crash, even if a work directory"
612-
" was specified.",
606+
help="Force stopping on first crash, even if a work directory" " was specified.",
613607
)
614608
g_other.add_argument(
615609
"--notrack",
@@ -665,6 +659,7 @@ def _slice_time_ref(value, parser):
665659
def parse_args(args=None, namespace=None):
666660
"""Parse args and run further checks on the command line."""
667661
import logging
662+
668663
from niworkflows.utils.spaces import Reference, SpatialReferences
669664

670665
parser = _build_parser()
@@ -680,6 +675,7 @@ def parse_args(args=None, namespace=None):
680675

681676
if not config.execution.notrack:
682677
import pkgutil
678+
683679
if pkgutil.find_loader("sentry_sdk") is None:
684680
config.execution.notrack = True
685681
config.loggers.cli.warning("Telemetry disabled because sentry_sdk is not installed.")
@@ -759,9 +755,7 @@ def parse_args(args=None, namespace=None):
759755

760756
build_log.info(f"Clearing previous fMRIPrep working directory: {work_dir}")
761757
if not clean_directory(work_dir):
762-
build_log.warning(
763-
f"Could not clear all contents of working directory: {work_dir}"
764-
)
758+
build_log.warning(f"Could not clear all contents of working directory: {work_dir}")
765759

766760
# Update the config with an empty dict to trigger initialization of all config
767761
# sections (we used `init=False` above).
@@ -793,9 +787,7 @@ def parse_args(args=None, namespace=None):
793787
"Making sure the input data is BIDS compliant (warnings can be ignored in most "
794788
"cases)."
795789
)
796-
validate_input_dir(
797-
config.environment.exec_env, opts.bids_dir, opts.participant_label
798-
)
790+
validate_input_dir(config.environment.exec_env, opts.bids_dir, opts.participant_label)
799791

800792
# Setup directories
801793
config.execution.log_dir = config.execution.fmriprep_dir / "logs"

0 commit comments

Comments
 (0)