Skip to content

Commit

Permalink
STY: Mass ruff-ication
Browse files Browse the repository at this point in the history
  • Loading branch information
mgxd committed Jul 31, 2024
1 parent edbd316 commit c4205c6
Show file tree
Hide file tree
Showing 18 changed files with 417 additions and 415 deletions.
16 changes: 8 additions & 8 deletions nibabies/__about__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
try:
from ._version import __version__
except ImportError:
__version__ = "0+unknown"
__version__ = '0+unknown'

__org__ = "nipreps"
__packagename__ = "nibabies"
__copyright__ = "Copyright 2023, Center for Reproducible Neuroscience, Stanford University"
__org__ = 'nipreps'
__packagename__ = 'nibabies'
__copyright__ = 'Copyright 2023, Center for Reproducible Neuroscience, Stanford University'
__credits__ = (
"Contributors: please check the ``.zenodo.json`` file at the top-level folder"
"of the repository"
'Contributors: please check the ``.zenodo.json`` file at the top-level folder'
'of the repository'
)
__url__ = f"https://github.com/{__org__}/{__packagename__}"
__url__ = f'https://github.com/{__org__}/{__packagename__}'

DOWNLOAD_URL = f"https://github.com/{__org__}/{__packagename__}/archive/{__version__}.tar.gz"
DOWNLOAD_URL = f'https://github.com/{__org__}/{__packagename__}/archive/{__version__}.tar.gz'
2 changes: 1 addition & 1 deletion nibabies/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .__about__ import __version__
from .__about__ import __version__ # noqa: F401
6 changes: 3 additions & 3 deletions nibabies/_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@
import logging
import warnings

_wlog = logging.getLogger("py.warnings")
_wlog = logging.getLogger('py.warnings')
_wlog.addHandler(logging.NullHandler())


def _warn(message, category=None, stacklevel=1, source=None):
"""Redefine the warning function."""
if category is not None:
category = type(category).__name__
category = category.replace("type", "WARNING")
category = category.replace('type', 'WARNING')

logging.getLogger("py.warnings").warning(f"{category or 'WARNING'}: {message}")
logging.getLogger('py.warnings').warning(f"{category or 'WARNING'}: {message}")


def _showwarning(message, category, filename, lineno, file=None, line=None):
Expand Down
2 changes: 1 addition & 1 deletion nibabies/cli/mcribs.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@


def _parser():
parser = ArgumentParser(description="Test script for MCRIBS surfaces")
parser = ArgumentParser(description='Test script for MCRIBS surfaces')
parser.add_argument('subject', help='Subject ID')
parser.add_argument('t2w', type=os.path.abspath, help='Input T2w (radioisotropic)')
parser.add_argument(
Expand Down
40 changes: 19 additions & 21 deletions nibabies/cli/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Version CLI helpers."""

from datetime import datetime
from contextlib import suppress
from datetime import datetime, timezone
from pathlib import Path

import requests

from .. import __version__

RELEASE_EXPIRY_DAYS = 14
DATE_FMT = "%Y%m%d"
DATE_FMT = '%Y%m%d'


def check_latest():
Expand All @@ -20,65 +21,62 @@ def check_latest():
latest = None
date = None
outdated = None
cachefile = Path.home() / ".cache" / "nibabies" / "latest"
now = datetime.now(tz=timezone.utc)
cachefile = Path.home() / '.cache' / 'nibabies' / 'latest'
try:
cachefile.parent.mkdir(parents=True, exist_ok=True)
except OSError:
cachefile = None

if cachefile and cachefile.exists():
try:
latest, date = cachefile.read_text().split("|")
except Exception:
latest, date = cachefile.read_text().split('|')
except Exception: # noqa: S110, BLE001
pass
else:
try:
latest = Version(latest)
date = datetime.strptime(date, DATE_FMT)
date = datetime.strptime(date, DATE_FMT).astimezone(timezone.utc)
except (InvalidVersion, ValueError):
latest = None
else:
if abs((datetime.now() - date).days) > RELEASE_EXPIRY_DAYS:
if abs((now - date).days) > RELEASE_EXPIRY_DAYS:
outdated = True

if latest is None or outdated is True:
try:
response = requests.get(url="https://pypi.org/pypi/nibabies/json", timeout=1.0)
except Exception:
response = None
response = None
with suppress(Exception):
response = requests.get(url='https://pypi.org/pypi/nibabies/json', timeout=1.0)

if response and response.status_code == 200:
versions = [Version(rel) for rel in response.json()["releases"].keys()]
versions = [Version(rel) for rel in response.json()['releases'].keys()]
versions = [rel for rel in versions if not rel.is_prerelease]
if versions:
latest = sorted(versions)[-1]
else:
latest = None

if cachefile is not None and latest is not None:
try:
cachefile.write_text("|".join(("%s" % latest, datetime.now().strftime(DATE_FMT))))
except Exception:
pass
with suppress(OSError):
cachefile.write_text(f'{latest}|{now.strftime(DATE_FMT)}')

return latest


def is_flagged():
"""Check whether current version is flagged."""
# https://raw.githubusercontent.com/nipreps/fmriprep/master/.versions.json
flagged = tuple()
try:
flagged = ()
response = None
with suppress(Exception):
response = requests.get(
url="""\
https://raw.githubusercontent.com/nipreps/nibabies/master/.versions.json""",
timeout=1.0,
)
except Exception:
response = None

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

if __version__ in flagged:
return True, flagged[__version__]
Expand Down
34 changes: 17 additions & 17 deletions nibabies/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,22 @@
from nibabies.data import load as load_data

FILES = (
"functional.nii",
"anatomical.nii",
"func.dlabel.nii",
"func.dtseries.nii",
"epi.nii",
"T1w.nii",
"func_to_struct.mat",
"atlas.nii",
"label_list.txt",
"sub-01_run-01_echo-1_bold.nii.gz",
"sub-01_run-01_echo-2_bold.nii.gz",
"sub-01_run-01_echo-3_bold.nii.gz",
'functional.nii',
'anatomical.nii',
'func.dlabel.nii',
'func.dtseries.nii',
'epi.nii',
'T1w.nii',
'func_to_struct.mat',
'atlas.nii',
'label_list.txt',
'sub-01_run-01_echo-1_bold.nii.gz',
'sub-01_run-01_echo-2_bold.nii.gz',
'sub-01_run-01_echo-3_bold.nii.gz',
)


@pytest.fixture(scope="package")
@pytest.fixture(scope='package')
def data_dir():
with TemporaryDirectory() as tmpdir:
tmp_path = Path(tmpdir)
Expand All @@ -33,7 +33,7 @@ def data_dir():


@pytest.fixture(autouse=True)
def set_namespace(doctest_namespace, data_dir):
doctest_namespace["data_dir"] = data_dir
doctest_namespace["test_data"] = load_data.cached('../tests/data')
doctest_namespace["Path"] = Path
def _populate_namespace(doctest_namespace, data_dir):
doctest_namespace['data_dir'] = data_dir
doctest_namespace['test_data'] = load_data.cached('../tests/data')
doctest_namespace['Path'] = Path
20 changes: 10 additions & 10 deletions nibabies/data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
except ImportError:
from importlib_resources.abc import Traversable

__all__ = ["load"]
__all__ = ['load']


class Loader:
Expand Down Expand Up @@ -111,7 +111,7 @@ class Loader:
.. automethod:: cached
"""

def __init__(self, anchor: Union[str, ModuleType]):
def __init__(self, anchor: str | ModuleType):
self._anchor = anchor
self.files = files(anchor)
self.exit_stack = ExitStack()
Expand All @@ -128,19 +128,19 @@ def _doc(self):
directory.
"""
top_level = sorted(
os.path.relpath(p, self.files) + "/"[: p.is_dir()]
os.path.relpath(p, self.files) + '/'[: p.is_dir()]
for p in self.files.iterdir()
if p.name[0] not in (".", "_") and p.name != "tests"
if p.name[0] not in ('.', '_') and p.name != 'tests'
)
doclines = [
f"Load package files relative to ``{self._anchor}``.",
"",
"This package contains the following (top-level) files/directories:",
"",
*(f"* ``{path}``" for path in top_level),
f'Load package files relative to ``{self._anchor}``.',
'',
'This package contains the following (top-level) files/directories:',
'',
*(f'* ``{path}``' for path in top_level),
]

return "\n".join(doclines)
return '\n'.join(doclines)

def readable(self, *segments) -> Traversable:
"""Provide read access to a resource through a Path-like interface.
Expand Down
2 changes: 1 addition & 1 deletion nibabies/interfaces/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@

# TODO: Set default as default in niworkflows
class DerivativesDataSink(_DDS):
out_path_base = ""
out_path_base = ''
Loading

0 comments on commit c4205c6

Please sign in to comment.