Skip to content

Commit

Permalink
Fix remaining ruff issues.
Browse files Browse the repository at this point in the history
  • Loading branch information
tsalo committed Oct 31, 2024
1 parent ecc4901 commit 42c8602
Show file tree
Hide file tree
Showing 28 changed files with 122 additions and 357 deletions.
Empty file modified .circleci/get_data.py
100644 → 100755
Empty file.
35 changes: 22 additions & 13 deletions .maint/update_authors.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
"""Update and sort the creators list of the zenodo record."""

import json
import sys
from pathlib import Path
Expand Down Expand Up @@ -113,16 +114,17 @@ def get_git_lines(fname='line-contributors.txt'):
if not lines and git_line_summary_path:
print('Running git-line-summary on repo')
lines = sp.check_output([git_line_summary_path]).decode().splitlines()
lines = [l for l in lines if 'Not Committed Yet' not in l]
lines = [line for line in lines if 'Not Committed Yet' not in line]
contrib_file.write_text('\n'.join(lines))

if not lines:
raise RuntimeError(
"""\
Could not find line-contributors from git repository.%s"""
% """ \
Could not find line-contributors from git repository.{}""".format(
""" \
git-line-summary not found, please install git-extras. """
* (git_line_summary_path is None)
* (git_line_summary_path is None)
)
)
return [' '.join(line.strip().split()[1:-1]) for line in lines if '%' in line]

Expand Down Expand Up @@ -185,7 +187,7 @@ def zenodo(
misses = set(miss_creators).intersection(miss_contributors)
if misses:
print(
"Some people made commits, but are missing in .maint/ " f"files: {', '.join(misses)}",
f"Some people made commits, but are missing in .maint/ files: {', '.join(misses)}",
file=sys.stderr,
)

Expand All @@ -204,7 +206,7 @@ def zenodo(
if isinstance(creator['affiliation'], list):
creator['affiliation'] = creator['affiliation'][0]

Path(zenodo_file).write_text('%s\n' % json.dumps(zenodo, indent=2))
Path(zenodo_file).write_text(f'{json.dumps(zenodo, indent=2)}\n')


@cli.command()
Expand Down Expand Up @@ -242,7 +244,7 @@ def publication(
hits = [hit for hit in hits if hit['name'] not in pi_names] + pi_hits

def _aslist(value):
if isinstance(value, (list, tuple)):
if isinstance(value, list | tuple):
return value
return [value]

Expand All @@ -266,22 +268,29 @@ def _aslist(value):

if misses:
print(
"Some people made commits, but are missing in .maint/ " f"files: {', '.join(misses)}",
f"Some people made commits, but are missing in .maint/ files: {', '.join(misses)}",
file=sys.stderr,
)

print('Authors (%d):' % len(hits))
print(
'%s.'
% '; '.join(['%s \\ :sup:`%s`\\ ' % (i['name'], idx) for i, idx in zip(hits, aff_indexes, strict=False)])
'{}.'.format(
'; '.join(
[
rf'{i["name"]} \ :sup:`{idx}`\ '
for i, idx in zip(hits, aff_indexes, strict=False)
]
)
)
)

print(
'\n\nAffiliations:\n%s'
% '\n'.join([f'{i + 1: >2}. {a}' for i, a in enumerate(affiliations)])
'\n\nAffiliations:\n{}'.format(
'\n'.join([f'{i + 1: >2}. {a}' for i, a in enumerate(affiliations)])
)
)


if __name__ == '__main__':
"""Install entry-point"""
""" Install entry-point """
cli()
2 changes: 1 addition & 1 deletion aslprep/cli/aggregate_qc.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def main():
outputfile = os.getcwd() + '/' + str(opts.output_prefix) + '_allsubjects_qc.tsv'

qclist = []
for r, d, f in os.walk(allsubj_dir):
for r, _, f in os.walk(allsubj_dir):
for filex in f:
if filex.endswith('desc-qualitycontrol_cbf.tsv'):
qclist.append(r + '/' + filex)
Expand Down
6 changes: 3 additions & 3 deletions aslprep/cli/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ def _bids_filter(value, parser):
if Path(value).exists():
try:
return loads(Path(value).read_text(), object_hook=_filter_pybids_none_any)
except JSONDecodeError:
raise parser.error(f'JSON syntax error in: <{value}>.')
except JSONDecodeError as e:
raise parser.error(f'JSON syntax error in: <{value}>.') from e
else:
raise parser.error(f'Path does not exist: <{value}>.')

Expand Down Expand Up @@ -671,7 +671,7 @@ def parse_args(args=None, namespace=None):
import yaml

with open(opts.use_plugin) as f:
plugin_settings = yaml.load(f, Loader=yaml.FullLoader)
plugin_settings = yaml.safe_load(f)
_plugin = plugin_settings.get('plugin')
if _plugin:
config.nipype.plugin = _plugin
Expand Down
Empty file modified aslprep/cli/run.py
100644 → 100755
Empty file.
56 changes: 37 additions & 19 deletions aslprep/cli/version.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,34 @@
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright The NiPreps Developers <[email protected]>
#
# 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/
#
"""Version CLI helpers."""

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

import requests

from aslprep import __version__
from .. import __version__

RELEASE_EXPIRY_DAYS = 14
DATE_FMT = '%Y%m%d'
Expand All @@ -20,6 +41,7 @@ def check_latest():
latest = None
date = None
outdated = None
now = datetime.now(tz=timezone.utc)
cachefile = Path.home() / '.cache' / 'aslprep' / 'latest'
try:
cachefile.parent.mkdir(parents=True, exist_ok=True)
Expand All @@ -29,23 +51,22 @@ def check_latest():
if cachefile and cachefile.exists():
try:
latest, date = cachefile.read_text().split('|')
except Exception:
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/alprep/json', timeout=1.0)
except Exception:
response = None
response = None
with suppress(Exception):
response = requests.get(url='https://pypi.org/pypi/aslprep/json', timeout=1.0)

if response and response.status_code == 200:
versions = [Version(rel) for rel in response.json()['releases'].keys()]
Expand All @@ -56,26 +77,23 @@ def check_latest():
latest = None

if cachefile is not None and latest is not None:
try:
cachefile.write_text('|'.join((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/pennlinc/aslprep/master/.versions.json
flagged = tuple()
try:
# https://raw.githubusercontent.com/pennlinc/aslprep/main/.versions.json
flagged = ()
response = None
with suppress(Exception):
response = requests.get(
url="""\
https://raw.githubusercontent.com/pennlinc/aslprep/master/.versions.json""",
https://raw.githubusercontent.com/pennlinc/aslprep/main/.versions.json""",
timeout=1.0,
)
except Exception:
response = None

if response and response.status_code == 200:
flagged = response.json().get('flagged', {}) or {}
Expand Down
10 changes: 5 additions & 5 deletions aslprep/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@
from psutil import virtual_memory

_free_mem_at_start = round(virtual_memory().available / 1024**3, 1)
except Exception:
except Exception: # noqa: BLE001
_free_mem_at_start = None

_oc_limit = 'n/a'
Expand All @@ -197,7 +197,7 @@
_oc_limit = _proc_oc_kbytes.read_text().strip()
if _oc_limit in ('0', 'n/a') and Path('/proc/sys/vm/overcommit_ratio').exists():
_oc_limit = f"{Path('/proc/sys/vm/overcommit_ratio').read_text().strip()}%"
except Exception:
except Exception: # noqa: S110, BLE001
pass


Expand All @@ -209,7 +209,7 @@
class _Config:
"""An abstract class forbidding instantiation."""

_paths = tuple()
_paths = ()

def __init__(self):
"""Avert instantiation."""
Expand All @@ -223,7 +223,7 @@ def load(cls, settings, init=True, ignore=None):
if k in ignore or v is None:
continue
if k in cls._paths:
if isinstance(v, (list, tuple)):
if isinstance(v, list | tuple):
setattr(cls, k, [Path(val).absolute() for val in v])
else:
setattr(cls, k, Path(v).absolute())
Expand All @@ -248,7 +248,7 @@ def get(cls):
if callable(getattr(cls, k)):
continue
if k in cls._paths:
if isinstance(v, (list, tuple)):
if isinstance(v, list | tuple):
v = [str(val) for val in v]
else:
v = str(v)
Expand Down
Loading

0 comments on commit 42c8602

Please sign in to comment.