Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fully switches to ruff preview and cleans up config #1564

Merged
merged 1 commit into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 10 additions & 17 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -134,18 +134,13 @@ target-version = "py311"
select = [
"B0",
"B904",
"B909",
"C4",
"COM818",
"D2",
"D301",
"D4",
"E",
"E301",
"E302",
"E303",
"E304",
"E305",
"E306",
"F",
"FLY002",
"ISC",
Expand All @@ -157,11 +152,13 @@ select = [
"Q",
"RUF",
"SIM",
"SLOT",
"UP",
"W"
]
ignore = [
"B007",
"C420",
"D200",
"D201",
"D202",
Expand All @@ -173,6 +170,7 @@ ignore = [
"D400",
"D401",
"D412",
"E226",
"E402",
"E711",
"E712",
Expand All @@ -182,18 +180,19 @@ ignore = [
"PYI041",
"RUF012",
"RUF013",
# TODO: We would like to enable some of these eventually
# But there are a lot of violations
"RUF021",
"RUF022",
"RUF023",
"RUF031",
# TODO: We would like to enable SIM102, but it has a ton of
# violations, so it's a big job to clean it up
"SIM102",
"SIM103",
"SIM105",
"SIM108",
"SIM110",
"SIM113",
"SIM114",
"SIM118",
"SIM210",
"SIM211",
"SIM910",
"UP009",
"UP012",
Expand All @@ -204,19 +203,13 @@ ignore = [
unfixable = []
external = ["MS", "TC"]
allowed-confusables = ["×"]
# NOTE: Enable preview rules, but only the ones we select explicitly
preview = true
explicit-preview-rules = true

[tool.ruff.lint.extend-per-file-ignores]
"src/onegov/core/types.py" = ["B018"]
"reportlab_settings.py" = ["N"]
"*.pyi" = [
"D",
"E501",
# TODO: re-enable this one, I think it is smarter in Ruff
"F401",
"F403",
"N",
"Q",
# NOTE: We would prefer to set a different target version instead
Expand Down
4 changes: 1 addition & 3 deletions src/onegov/activity/collections/booking.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,9 +249,7 @@ def cancel_booking(
blocked = {b for b in bookings if b.state == 'blocked'}
unblocked = set()

if booking.period.all_inclusive:
limit = booking.period.booking_limit
elif booking.period.booking_limit:
if booking.period.all_inclusive or booking.period.booking_limit:
limit = booking.period.booking_limit
else:
limit = booking.attendee.limit
Expand Down
2 changes: 1 addition & 1 deletion src/onegov/activity/collections/invoice.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
self.period_id = period_id

if schema not in KNOWN_SCHEMAS:
raise RuntimeError('Unknown schema: {schema}')
raise RuntimeError(f'Unknown schema: {schema}')

Check warning on line 36 in src/onegov/activity/collections/invoice.py

View check run for this annotation

Codecov / codecov/patch

src/onegov/activity/collections/invoice.py#L36

Added line #L36 was not covered by tests

self.schema_name = schema
self.schema_config = (schema_config or {})
Expand Down
12 changes: 5 additions & 7 deletions src/onegov/agency/excel_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,16 +65,14 @@

write_out = extract_person_data(session)

row = 0
for entry in write_out:
row += 1
for col_ix, value in enumerate(entry.values()):
for row, entry in enumerate(write_out, start=1):
for column, value in enumerate(entry.values()):
if value is None:
worksheet.write_string(row, col_ix, '')
worksheet.write_string(row, column, '')
elif isinstance(value, str):
worksheet.write_string(row, col_ix, value)
worksheet.write_string(row, column, value)
elif isinstance(value, (int, Decimal)):
worksheet.write_number(row, col_ix, value)
worksheet.write_number(row, column, value)

Check warning on line 75 in src/onegov/agency/excel_export.py

View check run for this annotation

Codecov / codecov/patch

src/onegov/agency/excel_export.py#L75

Added line #L75 was not covered by tests
else:
raise NotImplementedError()

Expand Down
4 changes: 1 addition & 3 deletions src/onegov/agency/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,9 +379,7 @@ def get_ancestors(
) -> 'Iterator[Link]':

for ix, ancestor in enumerate(item.ancestors, 1):
if levels is None:
yield Link(ancestor.title, self.request.link(ancestor))
elif ix in levels:
if levels is None or ix in levels:
yield Link(ancestor.title, self.request.link(ancestor))

if with_item:
Expand Down
2 changes: 1 addition & 1 deletion src/onegov/core/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def bool_decode(s: str) -> bool: ...

def bool_decode(s: str) -> bool:
""" Decodes a boolean. """
return False if s == '0' or s == '' else True
return not (s == '0' or s == '')


@overload
Expand Down
2 changes: 1 addition & 1 deletion src/onegov/core/i18n/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def get_translations(
# it might be worth revisiting in the future if we can
# enable caching here again, or introduce our own
wtf = super().get_translations(form)
if wtf is None:
if wtf is None:
wtf = gettext.NullTranslations()
wtf.is_wtforms = True

Expand Down
2 changes: 1 addition & 1 deletion src/onegov/directory/archive.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
]

class SupportsReadAndSeek(SupportsRead[bytes], Protocol):
def seek(self, __offset: int) -> object: ...
def seek(self, offset: int, /) -> object: ...


class _Sentinel(Enum):
Expand Down
18 changes: 8 additions & 10 deletions src/onegov/directory/migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,16 +365,14 @@ def detect_renamed_fields(self) -> None:
def detect_changed_fields(self) -> None:
self.changed_fields = []

for old in self.old:
if old in self.renamed_fields:
new = self.renamed_fields[old]
elif old in self.new:
new = old
for old_id, old in self.old.items():
if old_id in self.renamed_fields:
new_id = self.renamed_fields[old_id]
elif old_id in self.new:
new_id = old_id
else:
continue

if self.old[old].required != self.new[new].required:
self.changed_fields.append(new)

elif self.old[old].type != self.new[new].type:
self.changed_fields.append(new)
new = self.new[new_id]
if old.required != new.required or old.type != new.type:
self.changed_fields.append(new_id)
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,7 @@ def import_election_wabstic_majorz(

# Check if the entity is counted
try:
entity['counted'] = False if validate_integer(
line, 'sperrung') == 0 else True
entity['counted'] = validate_integer(line, 'sperrung') != 0
except ValueError as e:
line_errors.append(e.args[0])

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ def import_election_wabstic_proporz(
# From wabstic export docs: Einheit ist grün-gesperrt
# (1442=14:42 Uhr von der Oberbehörde gesperrt), sonst leer
locking_time = validate_integer(line, 'sperrung', default=False)
entity['counted'] = False if not locking_time else True
entity['counted'] = locking_time != 0
except ValueError as e:
line_errors.append(e.args[0])

Expand Down
2 changes: 1 addition & 1 deletion src/onegov/election_day/formats/imports/vote/wabstic.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ def import_vote_wabstic(
# Check if the entity is counted
try:
counted_num = validate_integer(line, 'sperrung')
counted = False if counted_num == 0 else True
counted = counted_num != 0
except ValueError:
line_errors.append(_('Invalid values'))
else:
Expand Down
2 changes: 1 addition & 1 deletion src/onegov/election_day/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ def get_data_source_item(

@ElectionDayApp.path(
model=ArchivedResultCollection,
path='/archive/{date}'
path='/archive/{date}' # noqa: RUF027
)
def get_archive_by_year(
app: ElectionDayApp,
Expand Down
8 changes: 4 additions & 4 deletions src/onegov/election_day/views/subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def subscribe_email(
'message': message,
'cancel': layout.homepage_link,
'callout': callout,
'show_form': False if callout else True
'show_form': not callout
}


Expand Down Expand Up @@ -145,7 +145,7 @@ def unsubscribe_email(
'title': _('Stop email subscription'),
'cancel': layout.homepage_link,
'callout': callout,
'show_form': False if callout else True
'show_form': not callout
}


Expand Down Expand Up @@ -246,7 +246,7 @@ def subscribe_sms(
),
'cancel': layout.homepage_link,
'callout': callout,
'show_form': False if callout else True
'show_form': not callout
}


Expand Down Expand Up @@ -288,5 +288,5 @@ def unsubscribe_sms(
'title': _('Stop SMS subscription'),
'cancel': layout.homepage_link,
'callout': callout,
'show_form': False if callout else True
'show_form': not callout
}
14 changes: 6 additions & 8 deletions src/onegov/feriennet/views/booking.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,14 +300,12 @@ def actions_by_booking(
))

if period.active and period.confirmed and booking.state == 'accepted':
if layout.request.is_admin:
may_cancel = True
elif not booking.occasion.is_past_cancellation(layout.today()):
may_cancel = True
else:
may_cancel = False

if may_cancel:
if (
# admins can always cancel bookings
layout.request.is_admin
# other users can if it isn't past its cancellation deadline
or not booking.occasion.is_past_cancellation(layout.today())
):
actions.append(Link(
text=_('Cancel Booking'),
url=layout.csrf_protected_url(
Expand Down
8 changes: 4 additions & 4 deletions src/onegov/form/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -749,10 +749,10 @@ def add(
submission_window = submission_window

submission = SurveySubmission(
id = id or uuid4(),
name = name,
meta = meta or {},
submission_window = submission_window
id=id or uuid4(),
name=name,
meta=meta or {},
submission_window=submission_window
)

# extensions are inherited from definitions
Expand Down
2 changes: 1 addition & 1 deletion src/onegov/form/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ class UploadMultipleField(UploadMultipleBase, FileField):
if TYPE_CHECKING:
_separator: str

def _add_entry(self, __d: _MultiDictLikeWithGetlist) -> UploadField:
def _add_entry(self, d: _MultiDictLikeWithGetlist, /) -> UploadField:
...

upload_field_class: type[UploadField] = UploadField
Expand Down
2 changes: 1 addition & 1 deletion src/onegov/form/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from wtforms.form import BaseForm

class FieldCondition(Protocol[BaseFormT, FieldT]):
def __call__(self, __form: BaseFormT, __field: FieldT) -> bool: ...
def __call__(self, form: BaseFormT, field: FieldT, /) -> bool: ...

Widget: TypeAlias = _Widget
Filter: TypeAlias = _Filter
Expand Down
15 changes: 7 additions & 8 deletions src/onegov/form/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,13 @@
assert self.step != Decimal(0)

def __repr__(self) -> str:
if self.start <= self.stop and self.step == Decimal('1.0'):
return "decimal_range('{}', '{}')".format(self.start, self.stop)
elif self.start >= self.stop and self.step == Decimal('-1.0'):
return "decimal_range('{}', '{}')".format(self.start, self.stop)
else:
return "decimal_range('{}', '{}', '{}')".format(
self.start, self.stop, self.step
)
if (
(self.start <= self.stop and self.step == Decimal('1.0'))
or (self.start >= self.stop and self.step == Decimal('-1.0'))
):
return f"decimal_range('{self.start}', '{self.stop}')"

return f"decimal_range('{self.start}', '{self.stop}', '{self.step}')"

Check warning on line 104 in src/onegov/form/utils.py

View check run for this annotation

Codecov / codecov/patch

src/onegov/form/utils.py#L104

Added line #L104 was not covered by tests

def __eq__(self, other: object) -> bool:
if not isinstance(other, self.__class__):
Expand Down
2 changes: 1 addition & 1 deletion src/onegov/fsi/ims_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@


def parse_completed(val: str | None) -> bool:
return False if val == 'N' else True
return val != 'N'

Check warning on line 287 in src/onegov/fsi/ims_import.py

View check run for this annotation

Codecov / codecov/patch

src/onegov/fsi/ims_import.py#L287

Added line #L287 was not covered by tests


@with_open
Expand Down
4 changes: 2 additions & 2 deletions src/onegov/landsgemeinde/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def get_assemblies(app: LandsgemeindeApp) -> AssemblyCollection:

@LandsgemeindeApp.path(
model=Assembly,
path='/landsgemeinde/{date}',
path='/landsgemeinde/{date}', # noqa: RUF027
converters={'date': extended_date_converter}
)
def get_assembly(app: LandsgemeindeApp, date: 'date') -> Assembly | None:
Expand All @@ -36,7 +36,7 @@ def get_assembly(app: LandsgemeindeApp, date: 'date') -> Assembly | None:

@LandsgemeindeApp.path(
model=AgendaItemCollection,
path='/traktanden/{date}',
path='/traktanden/{date}', # noqa: RUF027
converters={'date': extended_date_converter}
)
def get_agenda_items(
Expand Down
2 changes: 1 addition & 1 deletion src/onegov/landsgemeinde/views/opendata_swiss.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def set_headers(response: 'Response') -> None:
url = request.link(item, 'json')
sub(dist, 'dcat:accessURL', {'rdf:resource': url})
sub(dist, 'dcat:downloadURL', {'rdf:resource': url})
sub( dist, 'dct:license', {
sub(dist, 'dct:license', {
'rdf:resource': 'http://dcat-ap.ch/vocabulary/licenses/terms_by'
})
sub(dist, 'dcat:mediaType', {
Expand Down
9 changes: 5 additions & 4 deletions src/onegov/org/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -599,9 +599,10 @@ def format_datetime_range(
with_year: bool = False
) -> str:

if start.date() == end.date():
show_single_day = True
elif (end - start) <= timedelta(hours=23) and end.time() < time(6, 0):
if start.date() == end.date() or (
(end - start) <= timedelta(hours=23)
and end.time() < time(6, 0)
):
show_single_day = True
else:
show_single_day = False
Expand Down Expand Up @@ -2324,7 +2325,7 @@ def format_recurrence(self, recurrence: str | None) -> str:
def event_deletable(self, event: 'Event') -> bool:
tickets = TicketCollection(self.request.session)
ticket = tickets.by_handler_id(event.id.hex)
return False if ticket else True
return not ticket


class OccurrencesLayout(DefaultLayout, EventLayoutMixin):
Expand Down
Loading