Skip to content

Commit 4c87da8

Browse files
committed
linting
1 parent 50032d3 commit 4c87da8

File tree

7 files changed

+134
-146
lines changed

7 files changed

+134
-146
lines changed

.github/workflows/pylint.yml

Lines changed: 17 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,24 @@
1-
name: Tests and Linting
1+
name: Pylint
22

3-
on:
4-
push:
5-
branches: [main, develop]
6-
pull_request:
7-
branches: [main, develop]
3+
on: [push]
84

95
jobs:
10-
test-and-lint:
6+
build:
117
runs-on: ubuntu-latest
128
strategy:
139
matrix:
14-
python-version: ["3.9", "3.10", "3.11"]
15-
10+
python-version: ["3.9"]
1611
steps:
17-
- uses: actions/checkout@v3
18-
19-
- name: Set up Python ${{ matrix.python-version }}
20-
uses: actions/setup-python@v4
21-
with:
22-
python-version: ${{ matrix.python-version }}
23-
24-
- name: Install dependencies
25-
run: |
26-
python -m pip install --upgrade pip
27-
pip install -r requirements.txt
28-
29-
- name: Lint with pylint
30-
run: |
31-
pylint common.py premier_division.py first_division.py fai_cup.py live_updater.py rate_limiter.py
32-
33-
- name: Run all tests with coverage
34-
run: |
35-
python -m pytest tests/ -v --tb=short --cov=. --cov-report=xml --cov-report=term
36-
37-
- name: Upload coverage to Codecov
38-
uses: codecov/codecov-action@v3
39-
with:
40-
files: ./coverage.xml
41-
flags: unittests
42-
name: codecov-umbrella
43-
if: matrix.python-version == '3.11'
12+
- uses: actions/checkout@v3
13+
- name: Set up Python ${{ matrix.python-version }}
14+
uses: actions/setup-python@v3
15+
with:
16+
python-version: ${{ matrix.python-version }}
17+
- name: Install dependencies
18+
run: |
19+
python -m pip install --upgrade pip
20+
pip install pylint
21+
pip install -r requirements.txt
22+
- name: Analysing the code with pylint
23+
run: |
24+
pylint $(git ls-files '*.py') --exit-zero

common.py

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import json
66
import os
7-
from datetime import datetime
7+
from datetime import datetime, timedelta
88
from zoneinfo import ZoneInfo
99
from typing import Dict, List, Tuple, Any
1010

@@ -308,3 +308,42 @@ def format_scorer_list(scorer_list: List[Dict[str, Any]]) -> List[str]:
308308
return parts[0]
309309

310310
return ""
311+
312+
313+
def filter_weekly_matches(all_matches, today_date):
314+
"""Filter matches to next 7 days.
315+
316+
Args:
317+
all_matches: List of match fixtures from API
318+
today_date: Today's date (datetime.date object)
319+
320+
Returns:
321+
List of matches within the next 7 days
322+
"""
323+
week_end = today_date + timedelta(days=7)
324+
return [
325+
m for m in all_matches
326+
if (today_date <=
327+
parse_match_datetime(m["fixture"]["date"]).date() <=
328+
week_end)
329+
]
330+
331+
332+
def get_match_date_range(matches):
333+
"""Get first and last match dates from list.
334+
335+
Args:
336+
matches: List of match fixtures
337+
338+
Returns:
339+
Tuple of (first_match_date, last_match_date)
340+
"""
341+
first_date = min(
342+
parse_match_datetime(m["fixture"]["date"]).date()
343+
for m in matches
344+
)
345+
last_date = max(
346+
parse_match_datetime(m["fixture"]["date"]).date()
347+
for m in matches
348+
)
349+
return first_date, last_date

first_division.py

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Used for the League of Ireland subreddit
44
"""
55

6-
from datetime import datetime, timedelta
6+
from datetime import datetime
77
from zoneinfo import ZoneInfo
88
from tabulate import tabulate
99
import praw
@@ -19,6 +19,8 @@
1919
format_live_fixture,
2020
load_cache,
2121
save_cache,
22+
filter_weekly_matches,
23+
get_match_date_range,
2224
)
2325

2426
LEAGUE_ID = 358
@@ -184,29 +186,15 @@ def main():
184186
gw_num = int(gw.split()[-1])
185187
all_matches = get_matches_for_gameweek(gw)
186188

187-
# Filter to next 7 days only
188-
week_end = today + timedelta(days=7)
189-
weekly_matches = [
190-
m for m in all_matches
191-
if (today <=
192-
parse_match_datetime(m["fixture"]["date"]).date() <=
193-
week_end)
194-
]
189+
weekly_matches = filter_weekly_matches(all_matches, today)
195190

196191
if not weekly_matches:
197192
print(
198193
f"No matches in next 7 days for round {gw_num}, exiting."
199194
)
200195
return
201196

202-
first_match_date = min(
203-
parse_match_datetime(m["fixture"]["date"]).date()
204-
for m in weekly_matches
205-
)
206-
last_match_date = max(
207-
parse_match_datetime(m["fixture"]["date"]).date()
208-
for m in weekly_matches
209-
)
197+
first_match_date, last_match_date = get_match_date_range(weekly_matches)
210198

211199
title = (
212200
f"LOI First Division - Match Thread / "

live_updater.py

Lines changed: 43 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def get_live_fixtures(league_ids, api_client=None):
7575
)
7676
return response.get("response", [])
7777
except requests.exceptions.RequestException as e:
78-
logger.error(f"Error fetching live fixtures: {e}")
78+
logger.error("Error fetching live fixtures: %s", e)
7979
return []
8080

8181
# Fallback to direct requests if no api_client provided
@@ -89,7 +89,7 @@ def get_live_fixtures(league_ids, api_client=None):
8989
response.raise_for_status()
9090
return response.json()["response"]
9191
except requests.exceptions.RequestException as e:
92-
logger.error(f"Error fetching live fixtures: {e}")
92+
logger.error("Error fetching live fixtures: %s", e)
9393
return []
9494

9595

@@ -112,8 +112,9 @@ def get_league_table(league_id: int) -> List[Dict[str, Any]]:
112112
cache_entry = _table_cache[league_id]
113113
if now < cache_entry["expires"]:
114114
logger.debug(
115-
f"Using cached table for league {league_id} "
116-
f"(expires in {int(cache_entry['expires'] - now)}s)"
115+
"Using cached table for league %s (expires in %ds)",
116+
league_id,
117+
int(cache_entry["expires"] - now)
117118
)
118119
return cache_entry["data"]
119120

@@ -136,19 +137,42 @@ def get_league_table(league_id: int) -> List[Dict[str, Any]]:
136137
"data": table_data,
137138
"expires": now + TABLE_CACHE_SECONDS,
138139
}
139-
logger.info(f"Fetched and cached table for league {league_id}")
140+
logger.info("Fetched and cached table for league %s", league_id)
140141
return table_data
141142

142143
except requests.exceptions.RequestException as e:
143-
logger.error(f"Error getting league table for {league_id}: {e}")
144+
logger.error("Error getting league table for %s: %s", league_id, e)
144145

145146
# Return stale cache if available, otherwise empty
146147
if league_id in _table_cache:
147-
logger.warning(f"Using stale cache for league {league_id}")
148+
logger.warning("Using stale cache for league %s", league_id)
148149
return _table_cache[league_id]["data"]
149150
return []
150151

151152

153+
def _format_match_date_section(date_str, matches_list):
154+
"""Format matches for a single date into a markdown section."""
155+
date_extracted = datetime.strptime(date_str, "%Y-%m-%d")
156+
date_header = date_extracted.strftime(
157+
f"%A, %B {ordinal_suffix(date_extracted.day)}"
158+
)
159+
section_header = f"## {date_header}\n\n"
160+
161+
matches = [format_live_fixture(match) for match in matches_list]
162+
match_table = tabulate(
163+
matches, headers=match_table_headers, tablefmt='pipe'
164+
)
165+
166+
section = f"{section_header}{match_table}\n"
167+
for match in matches_list:
168+
scorers = format_scorers_inline(match)
169+
if scorers:
170+
section += f"\n{scorers}\n"
171+
section += "\n"
172+
173+
return section
174+
175+
152176
def build_premier_body(matches_data, league_table, gameweek_number):
153177
"""Build the body text for Premier Division post."""
154178
matches_by_date = {}
@@ -159,25 +183,7 @@ def build_premier_body(matches_data, league_table, gameweek_number):
159183
body = "*Live scores will be updated during matches*\n\n"
160184

161185
for date, matches_list in sorted(matches_by_date.items()):
162-
date_extracted = datetime.strptime(date, "%Y-%m-%d")
163-
date_header = date_extracted.strftime(
164-
f"%A, %B {ordinal_suffix(date_extracted.day)}"
165-
)
166-
section_header = f"## {date_header}\n\n"
167-
168-
matches = [format_live_fixture(match) for match in matches_list]
169-
170-
match_table = tabulate(
171-
matches, headers=match_table_headers, tablefmt='pipe'
172-
)
173-
body += f"{section_header}{match_table}\n"
174-
175-
# Add scorers inline under table
176-
for match in matches_list:
177-
scorers = format_scorers_inline(match)
178-
if scorers:
179-
body += f"\n{scorers}\n"
180-
body += "\n"
186+
body += _format_match_date_section(date, matches_list)
181187

182188
table_data = [
183189
[
@@ -226,25 +232,7 @@ def build_first_body(matches_data, league_table, gameweek_number):
226232
body = "*Live scores will be updated during matches*\n\n"
227233

228234
for date, matches_list in sorted(matches_by_date.items()):
229-
date_extracted = datetime.strptime(date, "%Y-%m-%d")
230-
date_header = date_extracted.strftime(
231-
f"%A, %B {ordinal_suffix(date_extracted.day)}"
232-
)
233-
section_header = f"## {date_header}\n\n"
234-
235-
matches = [format_live_fixture(match) for match in matches_list]
236-
237-
match_table = tabulate(
238-
matches, headers=match_table_headers, tablefmt='pipe'
239-
)
240-
body += f"{section_header}{match_table}\n"
241-
242-
# Add scorers inline under table
243-
for match in matches_list:
244-
scorers = format_scorers_inline(match)
245-
if scorers:
246-
body += f"\n{scorers}\n"
247-
body += "\n"
235+
body += _format_match_date_section(date, matches_list)
248236

249237
table_data = [
250238
[
@@ -349,13 +337,13 @@ def update_reddit_post(post_id: str, new_body: str) -> bool:
349337

350338
post = reddit.submission(id=post_id)
351339
post.edit(new_body)
352-
logger.info(f"Updated post {post_id}")
340+
logger.info("Updated post %s", post_id)
353341
return True
354342
except (
355343
praw.exceptions.PRAWException,
356344
requests.exceptions.RequestException
357345
) as e:
358-
logger.error(f"Error updating post {post_id}: {e}")
346+
logger.error("Error updating post %s: %s", post_id, e)
359347
return False
360348

361349

@@ -374,7 +362,7 @@ def update_league_thread(
374362
league_id: League ID (357, 358, or 359)
375363
"""
376364
comp_display = competition_name.replace('_', ' ').title()
377-
logger.info(f"Updating {comp_display} thread...")
365+
logger.info("Updating %s thread...", comp_display)
378366

379367
post_id = cache_data["post_id"]
380368
current_round = cache_data["round"]
@@ -413,7 +401,7 @@ def main():
413401
break
414402

415403
if not has_matches_today:
416-
logger.info(f"No matches scheduled for {today.isoformat()}, exiting.")
404+
logger.info("No matches scheduled for %s, exiting.", today.isoformat())
417405
return
418406

419407
# Initialize API client with rate limiting
@@ -427,13 +415,15 @@ def main():
427415
logger.info("No live fixtures found.")
428416
return
429417

430-
logger.info(f"Found {len(live_fixtures)} live fixtures")
418+
logger.info("Found %d live fixtures", len(live_fixtures))
431419

432420
# Log rate limiting stats
433421
stats = rate_limiter.get_stats()
434422
logger.info(
435-
f"Rate limiting stats: {stats['daily_calls']}/{stats['daily_limit']} "
436-
f"calls today, polling interval: {stats['polling_interval']}s"
423+
"Rate limiting stats: %s/%s calls today, polling interval: %ss",
424+
stats['daily_calls'],
425+
stats['daily_limit'],
426+
stats['polling_interval']
437427
)
438428

439429
# Organize fixtures by league
@@ -472,10 +462,7 @@ def main():
472462
logger.info("All matches finished.")
473463
else:
474464
next_poll = rate_limiter.get_polling_interval()
475-
logger.info(
476-
f"Some matches still in progress. "
477-
f"Next poll in {next_poll}s."
478-
)
465+
logger.info("Some matches still in progress. Next poll in %ss.", next_poll)
479466

480467

481468
if __name__ == "__main__":

0 commit comments

Comments
 (0)