Skip to content

Commit

Permalink
chore: format with ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
GabDug committed Mar 2, 2024
1 parent 4c9ea8a commit 23954f2
Show file tree
Hide file tree
Showing 39 changed files with 281 additions and 287 deletions.
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ _cd-lint-pylint = {composite= ["_copy_env", "lint-pylint-strict"], help="Run pyl
lint-pylint = {cmd="pylint --django-settings-module=firefighter.firefighter.settings src", help="Run pylint"}
lint-pylint-strict = {shell="pylint --django-settings-module=firefighter.settings src --fail-under=0.99", help="Run pylint, fail if score is under 9.99"}
lint-mypy = {shell= "mypy", help="Run mypy type checker", env={"ENABLE_PAGERDUTY"="True", "ENABLE_CONFLUENCE"="True"}}
lint-ruff = {cmd="ruff .", help="Run ruff linter"}
lint-ruff = {cmd="ruff check .", help="Run ruff linter"}
lint = {composite= ["lint-ruff", "lint-pylint", "lint-mypy"], help="Run all linters (ruff, pylint, mypy)."}
# Format
fmt-black = {cmd="ruff format .", help="Run black-like ruff formatter"}
Expand Down Expand Up @@ -545,6 +545,7 @@ external = [
"**/main.py" = ["INP"]
"**/gunicorn.conf.py" = ["INP"]
"scripts/*" = ["INP"]
"*.pyi" = ["E301", "E302", "E305"]

[tool.ruff.lint.mccabe]
max-complexity = 15
Expand Down
24 changes: 19 additions & 5 deletions src/firefighter/api/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ class APITokenAdmin(TokenAdmin):
Add supports for custom permissions.
"""

def formfield_for_foreignkey(self, db_field: ForeignKey[Any, Any], request: HttpRequest, **kwargs: Any) -> ModelChoiceField: # type: ignore[override]
def formfield_for_foreignkey(
self, db_field: ForeignKey[Any, Any], request: HttpRequest, **kwargs: Any
) -> ModelChoiceField: # type: ignore[override]
"""Show all or only current user depending on permissions."""
if db_field.name == "user":
if request.user.has_perm("api.can_add_any") or request.user.has_perm(
Expand All @@ -40,7 +42,13 @@ def formfield_for_foreignkey(self, db_field: ForeignKey[Any, Any], request: Http
kwargs["queryset"] = User.objects.filter(id=request.user.id)
return super().formfield_for_foreignkey(db_field, request, **kwargs)

def get_form(self, request: HttpRequest, obj: APITokenProxy | None = None, change: bool = False, **kwargs: Any) -> type[ModelForm[APITokenProxy]]: # type: ignore[override] # noqa: FBT001, FBT002
def get_form(
self,
request: HttpRequest,
obj: APITokenProxy | None = None,
change: bool = False, # noqa: FBT001, FBT002
**kwargs: Any,
) -> type[ModelForm[APITokenProxy]]: # type: ignore[override]
"""Prefill the form with the current user."""
form: type[ModelForm[APITokenProxy]] = super().get_form(
request, obj, change, **kwargs
Expand All @@ -65,7 +73,9 @@ def get_sortable_by(self, request: HttpRequest): # type: ignore[no-untyped-def,
)
return super().get_sortable_by(request)

def has_view_permission(self, request: HttpRequest, obj: APITokenProxy | None = None) -> bool: # type: ignore[override]
def has_view_permission(
self, request: HttpRequest, obj: APITokenProxy | None = None
) -> bool: # type: ignore[override]
if obj is None:
return request.user.has_perm("api.can_view_any") or request.user.has_perm(
"api.can_view_own"
Expand All @@ -81,7 +91,9 @@ def has_add_permission(self, request: HttpRequest) -> bool: # type: ignore[over
"api.can_add_own"
)

def has_delete_permission(self, request: HttpRequest, obj: APITokenProxy | None = None) -> bool: # type: ignore[override]
def has_delete_permission(
self, request: HttpRequest, obj: APITokenProxy | None = None
) -> bool: # type: ignore[override]
if obj is None:
return request.user.has_perm("api.can_delete_any") or request.user.has_perm(
"api.can_delete_own"
Expand All @@ -92,7 +104,9 @@ def has_delete_permission(self, request: HttpRequest, obj: APITokenProxy | None
return bool(obj.user == request.user)
return False

def has_change_permission(self, request: HttpRequest, obj: APITokenProxy | None = None) -> bool: # type: ignore[override]
def has_change_permission(
self, request: HttpRequest, obj: APITokenProxy | None = None
) -> bool: # type: ignore[override]
if obj is None:
return request.user.has_perm("api.can_edit_any")
if request.user.has_perm("api.can_edit_any"):
Expand Down
4 changes: 3 additions & 1 deletion src/firefighter/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ def map_serializer(
return {"type": "object", "additionalProperties": child_schema_ref}

def get_name(
self, auto_schema: AutoSchema, direction: Direction # noqa: ARG002
self,
auto_schema: AutoSchema, # noqa: ARG002
direction: Direction, # noqa: ARG002
) -> str:
return f"GroupedModelSerializer_{self.target.child_serializer.__name__}"

Expand Down
32 changes: 13 additions & 19 deletions src/firefighter/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,26 +54,20 @@
path("", include(router.urls)),
path(
"incidents",
views.incidents.CreateIncidentViewSet.as_view(
{"post": "create"}
), # pyright: ignore[reportGeneralTypeIssues]
views.incidents.CreateIncidentViewSet.as_view({"post": "create"}), # pyright: ignore[reportGeneralTypeIssues]
name="incidents",
),
]
if settings.FF_EXPOSE_API_DOCS:
urlpatterns.extend(
(
path(
"schema",
SpectacularAPIView.as_view(), # pyright: ignore[reportGeneralTypeIssues]
name="schema",
),
path(
"schema/swagger-ui",
SpectacularSwaggerView.as_view(
url_name="api:schema"
), # pyright: ignore[reportGeneralTypeIssues]
name="swagger-ui",
),
)
)
urlpatterns.extend((
path(
"schema",
SpectacularAPIView.as_view(), # pyright: ignore[reportGeneralTypeIssues]
name="schema",
),
path(
"schema/swagger-ui",
SpectacularSwaggerView.as_view(url_name="api:schema"), # pyright: ignore[reportGeneralTypeIssues]
name="swagger-ui",
),
))
4 changes: 2 additions & 2 deletions src/firefighter/confluence/tasks/sync_runbooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,11 @@ def sync_runbooks() -> None:
return
if len(missing_runbooks) > 4:
logger.warning(
f"Too many runbooks not found. FireFighter will not delete them automatically, as it might be an API or implementation error. List: {[f'{x.page_id }/ {x.name}' for x in missing_runbooks]}"
f"Too many runbooks not found. FireFighter will not delete them automatically, as it might be an API or implementation error. List: {[f'{x.page_id}/ {x.name}' for x in missing_runbooks]}"
)
return
logger.warning(
f"Missing runbooks that will be deleted: {[f'{x.page_id }/ {x.name}' for x in missing_runbooks]}"
f"Missing runbooks that will be deleted: {[f'{x.page_id}/ {x.name}' for x in missing_runbooks]}"
)
# Delete all runbooks that are not in the folders anymore
missing_runbooks.delete()
Expand Down
10 changes: 4 additions & 6 deletions src/firefighter/firefighter/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,10 @@ def __init__(self, client_kwargs: dict[str, Any] | None = None) -> None:
self._client = httpx.Client(**(client_kwargs or {}))
self._client.timeout = httpx.Timeout(15, read=20)
if FF_HTTP_CLIENT_ADDITIONAL_HEADERS:
self._client.headers = httpx.Headers(
{
**self._client.headers,
**FF_HTTP_CLIENT_ADDITIONAL_HEADERS,
}
)
self._client.headers = httpx.Headers({
**self._client.headers,
**FF_HTTP_CLIENT_ADDITIONAL_HEADERS,
})

def call(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
res: httpx.Response = getattr(self._client, method)(url, **kwargs)
Expand Down
2 changes: 1 addition & 1 deletion src/firefighter/firefighter/management/commands/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@ def handle(self, *args: Any, **options: Any) -> None:
self.stdout.write(self.style.SUCCESS(f"Successfully ran task {task_name}"))
else:
sep = "\n - "
err_msg = f'Task "{task_name}" does not exist. Available tasks are:\n - { sep.join(sorted(tasks))}'
err_msg = f'Task "{task_name}" does not exist. Available tasks are:\n - {sep.join(sorted(tasks))}'
raise CommandError(err_msg)
14 changes: 6 additions & 8 deletions src/firefighter/firefighter/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,12 @@
)

if settings.FF_DEBUG_ERROR_PAGES:
firefighter_urlpatterns[0].extend(
(
path("err/403/", views.permission_denied_view),
path("err/404/", views.not_found_view),
path("err/400/", views.bad_request_view),
path("err/500/", views.server_error_view),
)
)
firefighter_urlpatterns[0].extend((
path("err/403/", views.permission_denied_view),
path("err/404/", views.not_found_view),
path("err/400/", views.bad_request_view),
path("err/500/", views.server_error_view),
))

if apps.is_installed("firefighter.slack") and (
"runserver" in sys.argv
Expand Down
30 changes: 16 additions & 14 deletions src/firefighter/incidents/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,9 @@ class IncidentMembershipInline(admin.StackedInline[IncidentMembership, Incident]
verbose_name = _("Incident Member")

def has_change_permission(
self, request: HttpRequest, obj: Any | None = None # noqa: ARG002
self,
request: HttpRequest, # noqa: ARG002
obj: Any | None = None, # noqa: ARG002
) -> bool:
return False

Expand Down Expand Up @@ -579,21 +581,21 @@ def incidents_opened_count(obj: User) -> int:
return obj.incidents_created_by.count()

def get_fieldsets(
self, request: HttpRequest, obj: User | None = None # type: ignore[override]
self,
request: HttpRequest,
obj: User | None = None, # type: ignore[override]
) -> _FieldsetSpec:
fieldsets = list(super().get_fieldsets(request, obj)) # type: ignore[arg-type]
fieldsets.append(
(
_("User statistics"),
{
"fields": (
"commander_count",
"communication_lead_count",
"incidents_opened_count",
)
},
)
)
fieldsets.append((
_("User statistics"),
{
"fields": (
"commander_count",
"communication_lead_count",
"incidents_opened_count",
)
},
))
return fieldsets


Expand Down
2 changes: 1 addition & 1 deletion src/firefighter/incidents/forms/update_key_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def generate_fields_dynamically(self) -> None:
self.initial[field_name] = key_event.data.event_ts
except IndexError:
self.initial[field_name] = ""
logger.debug(f"Initial {field_name} was set to { self.initial[field_name]}")
logger.debug(f"Initial {field_name} was set to {self.initial[field_name]}")

def clean(self) -> dict[str, Any] | None:
if self.user is None:
Expand Down
2 changes: 1 addition & 1 deletion src/firefighter/incidents/forms/update_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def generate_fields_dynamically(self) -> None:
)

logger.debug(
f"Initial {field_name} was set to { self.initial.get(field_name)}"
f"Initial {field_name} was set to {self.initial.get(field_name)}"
)

def clean(self) -> dict[str, Any] | None:
Expand Down
7 changes: 4 additions & 3 deletions src/firefighter/incidents/menus.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@ def user_details_url(request: AuthenticatedHttpRequest) -> str | None:

def log_out_url(_request: HttpRequest) -> str:
url = reverse("oidc_logout")
return "?".join(
[url, urlencode({"next": "/admin/login/", "fail": "/admin/login/"})]
)
return "?".join([
url,
urlencode({"next": "/admin/login/", "fail": "/admin/login/"}),
])


def setup_navbar_menu() -> None:
Expand Down
14 changes: 6 additions & 8 deletions src/firefighter/incidents/models/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,12 @@ def queryset_with_mtbf(
incidents_downtime=F("metric_subquery"),
incident_uptime=Value(date_interval) - F("incidents_downtime"),
)
.annotate(
**{
field_name: Cast(
F("incident_uptime") / F("incident_count"),
output_field=DurationField(),
)
}
)
.annotate(**{
field_name: Cast(
F("incident_uptime") / F("incident_count"),
output_field=DurationField(),
)
})
)

@staticmethod
Expand Down
32 changes: 13 additions & 19 deletions src/firefighter/incidents/models/incident.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ def slack_channel_url(self) -> str | None:
@property
def status_page_url(self) -> str:
"""Similar with `get_absolute_url` but with full domain, to be used out of the website."""
return f"{ settings.BASE_URL }{self.get_absolute_url()}"
return f"{settings.BASE_URL}{self.get_absolute_url()}"

@property
def needs_postmortem(self) -> bool:
Expand All @@ -335,27 +335,21 @@ def can_be_closed(self) -> tuple[bool, list[tuple[str, str]]]:
return True, []
if self.needs_postmortem:
if self.status.value != IncidentStatus.POST_MORTEM:
cant_closed_reasons.append(
(
"STATUS_NOT_POST_MORTEM",
f"Incident is not in PostMortem status, and needs one because of its priority and environment ({self.priority.name}/{self.environment.value}).",
)
)
cant_closed_reasons.append((
"STATUS_NOT_POST_MORTEM",
f"Incident is not in PostMortem status, and needs one because of its priority and environment ({self.priority.name}/{self.environment.value}).",
))
elif self.status.value < IncidentStatus.FIXED:
cant_closed_reasons.append(
(
"STATUS_NOT_MITIGATED",
f"Incident is not in {IncidentStatus.FIXED.label} status (currently {self.status.label}).",
)
)
cant_closed_reasons.append((
"STATUS_NOT_MITIGATED",
f"Incident is not in {IncidentStatus.FIXED.label} status (currently {self.status.label}).",
))
missing_milestones = self.missing_milestones()
if len(missing_milestones) > 0:
cant_closed_reasons.append(
(
"MISSING_REQUIRED_KEY_EVENTS",
f"Missing key events: {', '.join(missing_milestones)}",
)
)
cant_closed_reasons.append((
"MISSING_REQUIRED_KEY_EVENTS",
f"Missing key events: {', '.join(missing_milestones)}",
))

if len(cant_closed_reasons) > 0:
return False, cant_closed_reasons
Expand Down
4 changes: 3 additions & 1 deletion src/firefighter/incidents/models/incident_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ class IncidentUpdate(models.Model):

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
event_ts: datetime.datetime = models.DateTimeField(auto_now_add=False, editable=True) # type: ignore
event_ts: datetime.datetime = models.DateTimeField(
auto_now_add=False, editable=True
) # type: ignore
event_type = models.CharField(null=True, blank=True, max_length=64)

class Meta(TypedModelMeta):
Expand Down
4 changes: 1 addition & 3 deletions src/firefighter/incidents/tasks/updateoncall.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ def update_oncall_views(*_args: Any, **_kwargs: Any) -> bool:
logger.error("Can't update on-call users without PagerDuty enabled.")
return False

oncall_users_grouped_per_ep = (
PagerDutyOncall.objects.get_current_oncalls_per_escalation_policy_name_first_responder()
)
oncall_users_grouped_per_ep = PagerDutyOncall.objects.get_current_oncalls_per_escalation_policy_name_first_responder()

# Check that we have Slack ID and handle for these users, if needed
if settings.ENABLE_SLACK:
Expand Down
3 changes: 2 additions & 1 deletion src/firefighter/incidents/views/docs/role_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ class RoleTypeDetailView(CustomDetailView[IncidentRoleType]):
class RoleTypeRedirectView(View):
@staticmethod
def get(
request: HttpRequest, slug: str | None = None # noqa: ARG004
request: HttpRequest, # noqa: ARG004
slug: str | None = None,
) -> HttpResponseRedirect:
incident_role_type = get_object_or_404(IncidentRoleType, slug=slug)
return redirect(incident_role_type)
Loading

0 comments on commit 23954f2

Please sign in to comment.