Skip to content

Commit 459130a

Browse files
committed
Enable many more Ruff linter rules
1 parent 92cc614 commit 459130a

File tree

335 files changed

+1256
-1207
lines changed

Some content is hidden

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

335 files changed

+1256
-1207
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
"PT006", # Enforces a consistent style for the type of the `argnames` parameter to
2+
# pytest.mark.parametrize. We have too many pre-existing violations of
3+
# this.
4+
"PT007", # Enforces a consistent style for the type of the `argvalues` parameter to
5+
# pytest.mark.parametrize. We have too many pre-existing violations of
6+
# this.

Diff for: bin/run_data_task.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
This is a general mechanism for running tasks defined in SQL, however it's
55
currently only used to perform the aggregations and mappings required for
66
reporting.
7-
"""
7+
""" # noqa: EXE002
88

99
from argparse import ArgumentParser
1010

@@ -60,18 +60,18 @@ def main():
6060
)
6161

6262
# Run the update in a transaction, so we roll back if it goes wrong
63-
with request.db.bind.connect() as connection:
63+
with request.db.bind.connect() as connection: # noqa: SIM117
6464
with connection.begin():
6565
for script in scripts:
6666
if args.no_python and isinstance(script, PythonScript):
67-
print(f"Skipping: {script}")
67+
print(f"Skipping: {script}") # noqa: T201
6868
continue
6969

7070
for step in script.execute(connection, dry_run=args.dry_run):
7171
if args.dry_run:
72-
print("Dry run!")
72+
print("Dry run!") # noqa: T201
7373

74-
print(step.dump(indent=" ") + "\n")
74+
print(step.dump(indent=" ") + "\n") # noqa: T201
7575

7676

7777
if __name__ == "__main__":

Diff for: h/_version.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -15,23 +15,24 @@
1515

1616

1717
def fetch_git_ref():
18-
return subprocess.check_output(
19-
["git", "rev-parse", "--short", "HEAD"], stderr=DEVNULL
18+
return subprocess.check_output( # noqa: S603
19+
["git", "rev-parse", "--short", "HEAD"], # noqa: S607
20+
stderr=DEVNULL,
2021
).strip()
2122

2223

2324
def fetch_git_date(ref):
24-
output = subprocess.check_output(["git", "show", "-s", "--format=%ct", ref])
25-
return datetime.datetime.fromtimestamp(int(output))
25+
output = subprocess.check_output(["git", "show", "-s", "--format=%ct", ref]) # noqa: S603, S607
26+
return datetime.datetime.fromtimestamp(int(output)) # noqa: DTZ006
2627

2728

2829
def fetch_git_dirty():
2930
# Ensure git index is up-to-date first. This usually isn't necessary, but
3031
# can be needed inside a docker container where the index is out of date.
31-
subprocess.call(["git", "update-index", "-q", "--refresh"])
32-
dirty_tree = bool(subprocess.call(["git", "diff-files", "--quiet"]))
32+
subprocess.call(["git", "update-index", "-q", "--refresh"]) # noqa: S603, S607
33+
dirty_tree = bool(subprocess.call(["git", "diff-files", "--quiet"])) # noqa: S603, S607
3334
dirty_index = bool(
34-
subprocess.call(["git", "diff-index", "--quiet", "--cached", "HEAD"])
35+
subprocess.call(["git", "diff-index", "--quiet", "--cached", "HEAD"]) # noqa: S603, S607
3536
)
3637
return dirty_tree or dirty_index
3738

@@ -45,11 +46,11 @@ def git_version():
4546

4647
def git_archive_version(): # pragma: no cover
4748
ref = VERSION_GIT_REF
48-
date = datetime.datetime.fromtimestamp(int(VERSION_GIT_DATE))
49+
date = datetime.datetime.fromtimestamp(int(VERSION_GIT_DATE)) # noqa: DTZ006
4950
return pep440_version(date, ref)
5051

5152

52-
def pep440_version(date, ref, dirty=False):
53+
def pep440_version(date, ref, dirty=False): # noqa: FBT002
5354
"""Build a PEP440-compliant version number from the passed information."""
5455
return f"{date.strftime('%Y%m%d')}+g{ref}{'.dirty' if dirty else ''}"
5556

Diff for: h/accounts/schemas.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import codecs
22
import logging
33
from datetime import datetime, timedelta
4-
from functools import lru_cache
4+
from functools import cache
55

66
import colander
77
import deform
@@ -24,18 +24,18 @@
2424
log = logging.getLogger(__name__)
2525

2626

27-
@lru_cache(maxsize=None)
27+
@cache
2828
def get_blacklist():
2929
# Try to load the blacklist file from disk. If, for whatever reason, we
3030
# can't load the file, then don't crash out, just log a warning about
3131
# the problem.
3232
try:
3333
with codecs.open("h/accounts/blacklist", encoding="utf-8") as handle:
3434
blacklist = handle.readlines()
35-
except (IOError, ValueError): # pragma: no cover
35+
except (IOError, ValueError): # pragma: no cover # noqa: UP024
3636
log.exception("unable to load blacklist")
3737
blacklist = []
38-
return set(line.strip().lower() for line in blacklist)
38+
return set(line.strip().lower() for line in blacklist) # noqa: C401
3939

4040

4141
def unique_email(node, value):
@@ -68,7 +68,7 @@ def unique_username(node, value):
6868
)
6969
# 31 days is an arbitrary time delta that should be more than enough
7070
# time for all the previous user's data to be expunged.
71-
.where(models.UserDeletion.requested_at > datetime.now() - timedelta(days=31))
71+
.where(models.UserDeletion.requested_at > datetime.now() - timedelta(days=31)) # noqa: DTZ005
7272
).first():
7373
raise exc
7474

Diff for: h/accounts/util.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@ def validate_url(url):
2323
parsed_url = urlparse("http://" + url)
2424

2525
if not re.match("https?", parsed_url.scheme):
26-
raise ValueError('Links must have an "http" or "https" prefix')
26+
raise ValueError('Links must have an "http" or "https" prefix') # noqa: EM101, TRY003
2727

2828
if not parsed_url.netloc:
29-
raise ValueError("Links must include a domain name")
29+
raise ValueError("Links must include a domain name") # noqa: EM101, TRY003
3030

3131
return parsed_url.geturl()
3232

@@ -44,10 +44,10 @@ def validate_orcid(orcid):
4444
orcid_regex = r"\A[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{3}[0-9X]\Z"
4545

4646
if not re.match(orcid_regex, orcid):
47-
raise ValueError(f"The format of this ORCID is incorrect: {orcid}")
47+
raise ValueError(f"The format of this ORCID is incorrect: {orcid}") # noqa: EM102, TRY003
4848

4949
if _orcid_checksum_digit(orcid[:-1]) != orcid[-1:]:
50-
raise ValueError(f"{orcid} is not a valid ORCID")
50+
raise ValueError(f"{orcid} is not a valid ORCID") # noqa: EM102, TRY003
5151

5252
return True
5353

Diff for: h/activity/bucketing.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ def next(self, annotation):
146146
if timeframe.within_cutoff(annotation):
147147
return timeframe
148148

149-
cutoff_time = datetime.datetime(
149+
cutoff_time = datetime.datetime( # noqa: DTZ001
150150
year=annotation.updated.year, month=annotation.updated.month, day=1
151151
)
152152
timeframe = Timeframe(annotation.updated.strftime("%b %Y"), cutoff_time)
@@ -179,4 +179,4 @@ def bucket(annotations):
179179

180180

181181
def utcnow(): # pragma: no cover
182-
return datetime.datetime.utcnow()
182+
return datetime.datetime.utcnow() # noqa: DTZ003

Diff for: h/activity/query.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from h.services.annotation_read import AnnotationReadService
1818

1919

20-
class ActivityResults(
20+
class ActivityResults( # noqa: SLOT002
2121
namedtuple("ActivityResults", ["total", "aggregations", "timeframes"]) # noqa: PYI024
2222
):
2323
pass

Diff for: h/app.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def includeme(config): # pragma: no cover
6363

6464
config.add_settings(
6565
{
66-
"tm.manager_hook": lambda request: transaction.TransactionManager(),
66+
"tm.manager_hook": lambda request: transaction.TransactionManager(), # noqa: ARG005
6767
"tm.annotate_user": False,
6868
}
6969
)

Diff for: h/cli/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
)
2323

2424

25-
def bootstrap(app_url, dev=False):
25+
def bootstrap(app_url, dev=False): # noqa: FBT002
2626
"""
2727
Bootstrap the application from the given arguments.
2828
@@ -34,7 +34,7 @@ def bootstrap(app_url, dev=False):
3434
if dev:
3535
app_url = "http://localhost:5000"
3636
else:
37-
raise click.ClickException("the app URL must be set in production mode!")
37+
raise click.ClickException("the app URL must be set in production mode!") # noqa: EM101, TRY003
3838

3939
config = "conf/development.ini" if dev else "conf/production.ini"
4040

Diff for: h/cli/commands/authclient.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def authclient():
3636
help="An allowable grant type",
3737
)
3838
@click.pass_context
39-
def add(ctx, name, authority, type_, redirect_uri, grant_type):
39+
def add(ctx, name, authority, type_, redirect_uri, grant_type): # noqa: PLR0913
4040
"""Create a new OAuth client."""
4141
request = ctx.obj["bootstrap"]()
4242

Diff for: h/cli/commands/create_annotations.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@ def create_annotations(ctx, number):
1515
tm = request.tm
1616

1717
for _ in range(number):
18-
created = updated = datetime.datetime(
19-
year=random.randint(2015, 2020),
20-
month=random.randint(1, 12),
21-
day=random.randint(1, 27),
22-
hour=random.randint(1, 12),
23-
minute=random.randint(0, 59),
24-
second=random.randint(0, 59),
18+
created = updated = datetime.datetime( # noqa: DTZ001
19+
year=random.randint(2015, 2020), # noqa: S311
20+
month=random.randint(1, 12), # noqa: S311
21+
day=random.randint(1, 27), # noqa: S311
22+
hour=random.randint(1, 12), # noqa: S311
23+
minute=random.randint(0, 59), # noqa: S311
24+
second=random.randint(0, 59), # noqa: S311
2525
)
2626
db.add(
2727
factories.Annotation.build(created=created, updated=updated, shared=True)

Diff for: h/cli/commands/devdata.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def create_all(self):
5555
elif type_ == "restricted_group":
5656
self.upsert_restricted_group(data_dict)
5757
else:
58-
raise RuntimeError(f"Unrecognized type: {type_}")
58+
raise RuntimeError(f"Unrecognized type: {type_}") # noqa: EM102, TRY003
5959

6060
self.tm.commit()
6161

@@ -113,7 +113,7 @@ def upsert_group(self, group_data, group_create_method):
113113
creator = models.User.get_by_username(
114114
self.db, group_data.pop("creator_username"), group_data["authority"]
115115
)
116-
assert creator
116+
assert creator # noqa: S101
117117

118118
organization = (
119119
self.db.query(models.Organization)
@@ -145,23 +145,24 @@ def setattrs(object_, attrs):
145145
def devdata(ctx):
146146
with tempfile.TemporaryDirectory() as tmpdirname:
147147
# The directory that we'll clone the devdata git repo into.
148-
git_dir = os.path.join(tmpdirname, "devdata")
148+
git_dir = os.path.join(tmpdirname, "devdata") # noqa: PTH118
149149

150150
# Clone the private devdata repo from GitHub.
151151
# This will fail if Git->GitHub HTTPS authentication isn't set up or if
152152
# your GitHub account doesn't have access to the private repo.
153-
subprocess.check_call(
154-
["git", "clone", "https://github.com/hypothesis/devdata.git", git_dir]
153+
subprocess.check_call( # noqa: S603
154+
["git", "clone", "https://github.com/hypothesis/devdata.git", git_dir] # noqa: S607
155155
)
156156

157157
# Copy environment variables file into place.
158158
shutil.copyfile(
159-
os.path.join(git_dir, "h", "devdata.env"),
160-
os.path.join(pathlib.Path(h.__file__).parent.parent, ".devdata.env"),
159+
os.path.join(git_dir, "h", "devdata.env"), # noqa: PTH118
160+
os.path.join(pathlib.Path(h.__file__).parent.parent, ".devdata.env"), # noqa: PTH118
161161
)
162162

163-
with open(
164-
os.path.join(git_dir, "h", "devdata.json"), "r", encoding="utf8"
163+
with open( # noqa: PTH123
164+
os.path.join(git_dir, "h", "devdata.json"), # noqa: PTH118
165+
encoding="utf8",
165166
) as handle:
166167
DevDataFactory(
167168
ctx.obj["bootstrap"](),

Diff for: h/cli/commands/move_uri.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def move_uri(ctx, old, new):
4040
)
4141
answer = click.prompt(prompt, default="n", show_default=False)
4242
if answer != "y":
43-
print("Aborted")
43+
print("Aborted") # noqa: T201
4444
return
4545

4646
for annotation in annotations:

Diff for: h/cli/commands/normalize_uris.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from h.util import uri
99

1010

11-
class Window(namedtuple("Window", ["start", "end"])): # noqa: PYI024
11+
class Window(namedtuple("Window", ["start", "end"])): # noqa: PYI024, SLOT002
1212
pass
1313

1414

Diff for: h/cli/commands/search.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,4 @@ def update_settings(ctx):
2323
try:
2424
config.update_index_settings(request.es)
2525
except RuntimeError as exc:
26-
raise click.ClickException(str(exc))
26+
raise click.ClickException(str(exc)) # noqa: B904

Diff for: h/cli/commands/user.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def add(ctx, username, email, password, authority):
3939
message = (
4040
f"could not create user due to integrity constraint.\n\n{upstream_error}"
4141
)
42-
raise click.ClickException(message)
42+
raise click.ClickException(message) # noqa: B904
4343

4444
click.echo(f"{username} created", err=True)
4545

@@ -92,8 +92,8 @@ def password(ctx, username, authority, password):
9292

9393
user = models.User.get_by_username(request.db, username, authority)
9494
if user is None:
95-
raise click.ClickException(
96-
f'no user with username "{username}" and authority "{authority}"'
95+
raise click.ClickException( # noqa: TRY003
96+
f'no user with username "{username}" and authority "{authority}"' # noqa: EM102
9797
)
9898

9999
password_service.update_password(user, password)

Diff for: h/config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
)
2424

2525

26-
def configure(environ=None, settings=None):
26+
def configure(environ=None, settings=None): # noqa: PLR0915
2727
if environ is None: # pragma: no cover
2828
environ = os.environ
2929
if settings is None: # pragma: no cover

Diff for: h/db/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from sqlalchemy import text
2121
from sqlalchemy.orm import declarative_base, sessionmaker
2222

23-
__all__ = ("Base", "Session", "pre_create", "post_create", "create_engine")
23+
__all__ = ("Base", "Session", "create_engine", "post_create", "pre_create")
2424

2525
log = logging.getLogger(__name__)
2626

0 commit comments

Comments
 (0)