Skip to content

Commit 7e5ac76

Browse files
authored
Merge pull request #2 from HackUCF/chore/ruff-python313-typehints
Adopt Ruff, target Python 3.13, add type hints
2 parents 6d79a2d + d21e980 commit 7e5ac76

15 files changed

Lines changed: 1000 additions & 1974 deletions

File tree

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ name: Code Formatting
22

33
on:
44
push:
5-
branches-ignore:
5+
branches-ignore:
66
- main
77
pull_request:
8-
types:
8+
types:
99
- opened
1010
- ready_for_review
1111
- reopened
@@ -17,18 +17,15 @@ jobs:
1717

1818
steps:
1919
- name: Checkout repo
20-
uses: actions/checkout@v3
21-
22-
- name: Install python
23-
uses: actions/setup-python@v3
24-
with:
25-
python-version: '3.9'
20+
uses: actions/checkout@v4
2621

27-
- name: Format the code
28-
uses: psf/black@stable
29-
with:
30-
options: "--check --diff"
31-
src: "."
22+
- name: Install uv
23+
uses: astral-sh/setup-uv@v6
24+
25+
- name: Lint and format with Ruff
26+
run: |
27+
uvx ruff check --fix .
28+
uvx ruff format .
3229
3330
- name: Check-in updated code
3431
uses: EndBug/add-and-commit@v9

‎.pre-commit-config.yaml‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,14 @@
11
repos:
22

3-
- repo: https://github.com/psf/black
4-
rev: 20.8b1
3+
- repo: https://github.com/astral-sh/ruff-pre-commit
4+
rev: v0.14.0
55
hooks:
6-
- id: black
7-
8-
- repo: https://github.com/pre-commit/mirrors-isort
9-
rev: v5.7.0
10-
hooks:
11-
- id: isort
12-
args: ["--profile", "black", "--filter-files"]
6+
- id: ruff
7+
args: [--fix]
8+
- id: ruff-format
139

1410
- repo: https://github.com/pre-commit/pre-commit-hooks
1511
rev: v3.4.0
1612
hooks:
1713
- id: check-added-large-files
18-
args: ['--maxkb=1500']
14+
args: ['--maxkb=1500']

‎app.py‎

Lines changed: 63 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
11
import atexit
2-
from operator import truediv
3-
import os
4-
import time
52
import json
6-
import github3
7-
from distutils.util import strtobool
8-
import threading
3+
import os
94
import sys
5+
import threading
6+
import time
107
import traceback
118
from concurrent.futures import ThreadPoolExecutor
9+
from typing import Any
1210

11+
import github3
1312
from apscheduler.schedulers.background import BackgroundScheduler
1413
from apscheduler.triggers.cron import CronTrigger
1514
from flask import Flask
1615

1716
from githubapp import (
18-
GitHubApp,
19-
DirectoryClient,
20-
CRON_INTERVAL,
21-
TEST_MODE,
2217
ADD_MEMBER,
18+
CRON_INTERVAL,
2319
REMOVE_ORG_MEMBERS_WITHOUT_TEAM,
24-
USER_SYNC_ATTRIBUTE,
2520
SYNCMAP_ONLY,
21+
TEST_MODE,
22+
USER_SYNC_ATTRIBUTE,
23+
DirectoryClient,
24+
GitHubApp,
2625
)
26+
from githubapp.util import strtobool
2727

2828
app = Flask(__name__)
2929
github_app = GitHubApp(app)
@@ -35,7 +35,7 @@
3535

3636

3737
@github_app.on("team.created")
38-
def sync_new_team():
38+
def sync_new_team() -> None:
3939
"""
4040
Sync a new team when it is created
4141
:return:
@@ -51,7 +51,12 @@ def sync_new_team():
5151
sync_team(client=client, owner=owner, team_id=team_id, slug=slug)
5252

5353

54-
def sync_team(client=None, owner=None, team_id=None, slug=None):
54+
def sync_team(
55+
client: Any = None,
56+
owner: str | None = None,
57+
team_id: int | None = None,
58+
slug: str | None = None,
59+
) -> None:
5560
"""
5661
Prepare the team sync
5762
:param client:
@@ -76,7 +81,7 @@ def sync_team(client=None, owner=None, team_id=None, slug=None):
7681
print(f"skipping team {team.slug} - not in group prefix")
7782
return
7883
directory_members = directory_group_members(group=directory_group)
79-
except Exception as e:
84+
except Exception:
8085
directory_members = []
8186
traceback.print_exc(file=sys.stderr)
8287

@@ -99,14 +104,14 @@ def sync_team(client=None, owner=None, team_id=None, slug=None):
99104
except (AssertionError, ValueError) as e:
100105
if strtobool(os.environ["OPEN_ISSUE_ON_FAILURE"]):
101106
open_issue(client=client, slug=slug, message=e)
102-
raise Exception(f"Team {team.slug} sync failed: {e}")
107+
raise Exception(f"Team {team.slug} sync failed: {e}") from e
103108
print(f"Processing Team Successful: {team.slug}")
104109
except Exception:
105110
traceback.print_exc(file=sys.stderr)
106111
raise
107112

108113

109-
def directory_group_members(group=None):
114+
def directory_group_members(group: str | None = None) -> list[dict[str, str | None]]:
110115
"""
111116
Look up members of a group in your user directory
112117
:param group: The name of the group to query in your directory server
@@ -118,13 +123,15 @@ def directory_group_members(group=None):
118123
directory = DirectoryClient()
119124
members = directory.get_group_members(group_name=group)
120125
group_members = [member for member in members]
121-
except Exception as e:
126+
except Exception:
122127
group_members = []
123128
traceback.print_exc(file=sys.stderr)
124129
return group_members
125130

126131

127-
def github_team_info(client=None, owner=None, team_id=None):
132+
def github_team_info(
133+
client: Any = None, owner: str | None = None, team_id: int | None = None
134+
) -> Any:
128135
"""
129136
Look up team info in GitHub
130137
:param client:
@@ -137,8 +144,12 @@ def github_team_info(client=None, owner=None, team_id=None):
137144

138145

139146
def github_team_members(
140-
client=None, owner=None, team_id=None, attribute="username", ignore_users=[]
141-
):
147+
client: Any = None,
148+
owner: str | None = None,
149+
team_id: int | None = None,
150+
attribute: str = "username",
151+
ignore_users: list[str] | None = None,
152+
) -> list[dict[str, str]]:
142153
"""
143154
Look up members of a given team in GitHub
144155
:param client:
@@ -151,6 +162,7 @@ def github_team_members(
151162
:return: team_members
152163
:rtype: list
153164
"""
165+
ignore_users = ignore_users or []
154166
team_members = []
155167
team = github_team_info(client=client, owner=owner, team_id=team_id)
156168
if attribute == "email":
@@ -168,9 +180,14 @@ def github_team_members(
168180
return [m for m in team_members if m["username"] not in ignore_users]
169181

170182

171-
def compare_members(group, team, attribute="username"):
183+
def compare_members(
184+
group: list[dict[str, str | None]],
185+
team: list[dict[str, str | None]],
186+
attribute: str = "username",
187+
) -> dict[str, Any]:
172188
"""
173-
Compare users in GitHub and the User Directory to see which users need to be added or removed
189+
Compare users in GitHub and the User Directory to see which users need to
190+
be added or removed
174191
:param group:
175192
:param team:
176193
:param attribute:
@@ -189,7 +206,7 @@ def compare_members(group, team, attribute="username"):
189206
return sync_state
190207

191208

192-
def execute_sync(org, team, slug, state):
209+
def execute_sync(org: Any, team: Any, slug: str, state: dict[str, Any]) -> None:
193210
"""
194211
Perform the synchronization
195212
:param org:
@@ -199,15 +216,19 @@ def execute_sync(org, team, slug, state):
199216
:return:
200217
"""
201218
total_changes = len(state["action"]["remove"]) + len(state["action"]["add"])
219+
threshold = int(os.environ.get("CHANGE_THRESHOLD", 25))
202220
if len(state["directory"]) == 0:
203-
message = f"{os.environ.get('USER_DIRECTORY', 'LDAP').upper()} group returned empty: {slug}"
221+
directory = os.environ.get("USER_DIRECTORY", "LDAP").upper()
222+
message = f"{directory} group returned empty: {slug}"
204223
raise ValueError(message)
205-
elif int(total_changes) > int(os.environ.get("CHANGE_THRESHOLD", 25)):
206-
message = "Skipping sync for {}.<br>".format(slug)
207-
message += "Total number of changes ({}) would exceed the change threshold ({}).".format(
208-
str(total_changes), str(os.environ.get("CHANGE_THRESHOLD", 25))
224+
elif int(total_changes) > threshold:
225+
message = (
226+
f"Skipping sync for {slug}.<br>"
227+
f"Total number of changes ({total_changes}) would exceed the "
228+
f"change threshold ({threshold})."
229+
"<br>Please investigate this change and increase your threshold "
230+
"if this is accurate."
209231
)
210-
message += "<br>Please investigate this change and increase your threshold if this is accurate."
211232
raise AssertionError(message)
212233
else:
213234
for user in state["action"]["add"]:
@@ -227,7 +248,7 @@ def execute_sync(org, team, slug, state):
227248
team.revoke_membership(user)
228249

229250

230-
def open_issue(client, slug, message):
251+
def open_issue(client: Any, slug: str, message: Exception | str) -> None:
231252
"""
232253
Open an issue with the failed sync details
233254
:param client: Our installation client
@@ -243,12 +264,14 @@ def open_issue(client, slug, message):
243264
owner=owner,
244265
repository=repository,
245266
assignee=assignee,
246-
title="Team sync failed for @{}/{}".format(owner, slug),
267+
title=f"Team sync failed for @{owner}/{slug}",
247268
body=str(message),
248269
)
249270

250271

251-
def load_custom_map(file="syncmap.yml"):
272+
def load_custom_map(
273+
file: str = "syncmap.yml",
274+
) -> tuple[dict, list[str], list[str]]:
252275
"""
253276
Custom team synchronization
254277
:param file:
@@ -258,9 +281,9 @@ def load_custom_map(file="syncmap.yml"):
258281
ignore_users = []
259282
group_prefix = []
260283
if os.path.isfile(file):
261-
from yaml import load, Loader
284+
from yaml import Loader, load
262285

263-
with open(file, "r") as f:
286+
with open(file) as f:
264287
data = load(f, Loader=Loader)
265288
if "mapping" in data:
266289
for d in data["mapping"]:
@@ -276,7 +299,7 @@ def load_custom_map(file="syncmap.yml"):
276299
return (syncmap, group_prefix, ignore_users)
277300

278301

279-
def get_app_installations():
302+
def get_app_installations() -> Any:
280303
"""
281304
Get a list of installations for this app
282305
:return:
@@ -294,7 +317,7 @@ def get_app_installations():
294317
@scheduler.scheduled_job(
295318
trigger=CronTrigger.from_crontab(CRON_INTERVAL), id="sync_all_teams"
296319
)
297-
def sync_all_teams():
320+
def sync_all_teams() -> None:
298321
"""
299322
Lookup teams in a GitHub org and synchronize all teams with your user directory
300323
:return:
@@ -334,7 +357,7 @@ def sync_all_teams():
334357
print(f"Syncing all teams successful: {time.strftime('%A, %d. %B %Y %I:%M:%S %p')}")
335358

336359

337-
def remove_org_members_without_team(installations):
360+
def remove_org_members_without_team(installations: Any) -> None:
338361
for i in installations():
339362
with app.app_context() as ctx:
340363
try:
@@ -356,7 +379,7 @@ def remove_org_members_without_team(installations):
356379
ctx.pop()
357380

358381

359-
def sync_team_helper(team, custom_map, client, org):
382+
def sync_team_helper(team: Any, custom_map: dict, client: Any, org: Any) -> None:
360383
print(f"Organization: {org.login}")
361384
try:
362385
if SYNCMAP_ONLY and not is_team_in_map(team.slug, custom_map, org):
@@ -374,7 +397,7 @@ def sync_team_helper(team, custom_map, client, org):
374397
print(f"DEBUG: {e}")
375398

376399

377-
def is_team_in_map(slug, custom_map, org):
400+
def is_team_in_map(slug: str, custom_map: dict, org: Any) -> bool:
378401
key_with_org = (org.login, slug)
379402
key_without_org = slug
380403
if key_with_org in custom_map or key_without_org in custom_map:
@@ -383,7 +406,7 @@ def is_team_in_map(slug, custom_map, org):
383406
return False
384407

385408

386-
def get_directory_from_slug(slug, custom_map, org):
409+
def get_directory_from_slug(slug: str, custom_map: dict, org: Any) -> str | None:
387410
if not is_team_in_map(slug, custom_map, org):
388411
return slug
389412
elif (org.login, slug) in custom_map:

‎githubapp/__init__.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import os
2-
from distutils.util import strtobool
32

43
from .core import GitHubApp
4+
from .util import strtobool
55

66
if os.environ.get("USER_DIRECTORY", "LDAP").upper() == "LDAP":
77
from .ldap import LDAPClient as DirectoryClient
@@ -17,7 +17,7 @@
1717
from .keycloak import Keycloak as DirectoryClient
1818
from .version import __version__
1919

20-
__all__ = ["GitHubApp", "DirectoryClient"]
20+
__all__ = ["GitHubApp", "DirectoryClient", "__version__"]
2121

2222
# Set default logging handler to avoid "No handler found" warnings.
2323
import logging

0 commit comments

Comments
 (0)