Skip to content

Commit ab3b202

Browse files
committed
Lint repo with new ruff rules
1 parent 77125de commit ab3b202

7 files changed

Lines changed: 37 additions & 33 deletions

File tree

.github/workflows/lint.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ jobs:
1919

2020
- name: Run pre-commit hooks
2121
run: SKIP=ruff pre-commit run --all-files
22-
22+
2323
# Run `ruff` using github formatting to enable automatic inline annotations.
2424
- name: Run ruff
2525
run: "ruff check --format=github ."

docs/Gemfile

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,3 @@ platforms :mingw, :x64_mingw, :mswin, :jruby do
88
end
99

1010
gem "wdm", "~> 0.1.1", :platforms => [:mingw, :x64_mingw, :mswin]
11-

olli/alert.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""This module contains the logic for grepping logs and generating Discord alerts."""
1+
"""The logic for grepping logs and generating Discord alerts."""
22
import httpx
33
from loguru import logger
44

@@ -43,19 +43,19 @@ def get_match(token: TokenConfig) -> TokenMatch:
4343

4444
def send_alerts(matches: list[TokenMatch]) -> None:
4545
"""Take the found matches and relay them to Discord."""
46-
# TODO: batch into 10 to avoid embed limits
46+
# TODO: batch into 10 to avoid embed limits # noqa: TD002,TD003,FIX002
4747
logger.info("Sending webhook payload to Discord")
4848
webhook.send_token_matches(matches)
4949

5050

5151
def run() -> None:
5252
"""Entrypoint for Olli's search process."""
5353
logger.info("Running Olli search")
54-
matches = []
55-
56-
for token in SERVICE_CONFIG.tokens:
57-
if match := get_match(token):
58-
matches.append(match)
54+
matches = [
55+
match
56+
for token in SERVICE_CONFIG.tokens
57+
if (match := get_match(token))
58+
]
5959

6060
send_alerts(matches)
6161
logger.info("Olli search complete.")

olli/api.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""This module contains API logic for interacting with Loki."""
1+
"""The API logic for interacting with Loki."""
22
import datetime
33
from typing import Any
44

@@ -17,18 +17,18 @@ def route(path: str) -> str:
1717

1818
def get_token_logs(self, token: TokenConfig) -> dict[str, Any]:
1919
"""
20-
Fetch the logs from configured services for a matchign token.
20+
Fetch the logs from configured services for a matching token.
2121
2222
The term is searched case-insensitively in the logs for the interval
2323
configured in the config.toml file.
2424
"""
2525
td = datetime.timedelta(minutes=SERVICE_CONFIG.interval_minutes)
26-
start_time = datetime.datetime.now() - td
26+
start_time = datetime.datetime.now(tz=datetime.UTC) - td
2727
start_ts = start_time.timestamp() * 1_000_000_000
2828

2929
job_regex = "|".join(LOKI_CONFIG.jobs)
3030

31-
case_filter = '(?i)' if not token.case_sensitive else ''
31+
case_filter = "(?i)" if not token.case_sensitive else ""
3232

3333
resp = httpx.get(self.route("query_range"), params={
3434
"query": f'{{job=~"({job_regex})"}} |~ "{case_filter}{token.token}"',

olli/config.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
"""Configuration loading and validation."""
22

3-
from typing import Optional
43

54
from loguru import logger
6-
from pydantic import BaseModel
5+
from pydantic import BaseModel, field_validator
76
from pydantic_settings import BaseSettings
87

98

@@ -22,7 +21,7 @@ class _LokiConfig(EnvConfig, env_prefix="loki_"):
2221

2322
api_url: str
2423
jobs: list[str]
25-
max_logs: Optional[int] = 5_000
24+
max_logs: int | None = 5_000
2625

2726

2827
LOKI_CONFIG = _LokiConfig()
@@ -31,7 +30,7 @@ class _LokiConfig(EnvConfig, env_prefix="loki_"):
3130
class _DiscordConfig(EnvConfig, env_prefix="discord_"):
3231
"""Configuration for Discord alerting."""
3332

34-
webhook_url: Optional[str]
33+
webhook_url: str | None
3534

3635

3736
DISCORD_CONFIG = _DiscordConfig()
@@ -41,8 +40,8 @@ class TokenConfig(BaseModel):
4140
"""Class representing a token config entry."""
4241

4342
token: str
44-
color: Optional[str] = "#7289DA"
45-
case_sensitive: Optional[bool] = False
43+
color: str | None = "#7289DA"
44+
case_sensitive: bool | None = False
4645

4746

4847
class _ServiceConfig(EnvConfig, env_prefix="service_"):
@@ -51,15 +50,18 @@ class _ServiceConfig(EnvConfig, env_prefix="service_"):
5150
interval_minutes: int
5251
tokens: list[TokenConfig]
5352

54-
@validator("interval_minutes")
53+
@field_validator("interval_minutes")
54+
@classmethod
5555
def must_be_above_zero(cls, value: int) -> int:
5656
"""Validate that the interval minutes is 1 or greater."""
5757
if value < 1:
58-
raise ValueError("Interval must be above zero minutes.")
58+
msg = "Interval must be above zero minutes."
59+
raise ValueError(msg)
5960

6061
return value
6162

62-
@validator("tokens")
63+
@field_validator("tokens")
64+
@classmethod
6365
def warn_above_ten(cls, value: list[TokenConfig]) -> list[TokenConfig]:
6466
"""
6567
Warn a user if they have more than 10 tokens.

olli/webhook.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
"""This module contains the logic for sending webhooks to Discord."""
2-
from datetime import datetime
1+
"""The logic for sending webhooks to Discord."""
2+
from datetime import UTC, datetime
33
from typing import Any
44

55
import httpx
@@ -16,7 +16,7 @@ def send_with_backoff(url: str, json: dict[str, Any], n: int = 5) -> None:
1616
try:
1717
httpx.post(url, json=json).raise_for_status()
1818
break
19-
except Exception:
19+
except httpx.HTTPStatusError:
2020
i += 1
2121
if i == n:
2222
logger.exception(f"Could not POST to URL {url}")
@@ -31,13 +31,14 @@ def send_olli_error(error: str) -> None:
3131
"title": "Olli Error",
3232
"color": 0xff5f5f,
3333
"description": f"Olli encountered an error: {error}",
34-
"timestamp": datetime.utcnow().isoformat(),
35-
}]
34+
"timestamp": datetime.now(tz=UTC).isoformat(),
35+
}],
3636
})
3737

3838

3939
def send_token_matches(matches: list[TokenMatch]) -> None:
40-
"""Send the found token matches to Discord.
40+
"""
41+
Send the found token matches to Discord.
4142
4243
The method checks that each token has at least 1 match and then merges
4344
together up to 10 embeds into one webhook payload.
@@ -53,28 +54,28 @@ def send_token_matches(matches: list[TokenMatch]) -> None:
5354
"description": f"`{sum(match.services.values())}` events matching",
5455
"color": int(match.token.color[1:], 16),
5556
"author": {
56-
"name": "Olli"
57+
"name": "Olli",
5758
},
5859
"footer": {
5960
"text": f"Last {SERVICE_CONFIG.interval_minutes} minutes",
6061
},
61-
"timestamp": datetime.utcnow().isoformat(),
62-
"fields": []
62+
"timestamp": datetime.now(tz=UTC).isoformat(),
63+
"fields": [],
6364
}
6465

6566
for service, count in match.services.items():
6667
embed["fields"].append({
6768
"name": service,
6869
"value": f"`{count:,}` logs",
69-
"inline": True
70+
"inline": True,
7071
})
7172

7273
embeds.append(embed)
7374

7475
if len(embeds) > 0:
7576
logger.info("Sending alerts payload to Discord")
7677
send_with_backoff(DISCORD_CONFIG.webhook_url, {
77-
"embeds": embeds
78+
"embeds": embeds,
7879
})
7980
else:
8081
logger.info("No alerts to send to Discord")

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ ignore = [
5050
"ARG003",
5151
"C901",
5252
"D100", "D104", "D105", "D107", "D203", "D212", "D214", "D215", "D416",
53+
"EM101",
54+
"TRY003"
5355
]
5456
line-length = 120
5557
select = ["ALL"]

0 commit comments

Comments
 (0)