11import atexit
2- from operator import truediv
3- import os
4- import time
52import json
6- import github3
7- from distutils .util import strtobool
8- import threading
3+ import os
94import sys
5+ import threading
6+ import time
107import traceback
118from concurrent .futures import ThreadPoolExecutor
9+ from typing import Any
1210
11+ import github3
1312from apscheduler .schedulers .background import BackgroundScheduler
1413from apscheduler .triggers .cron import CronTrigger
1514from flask import Flask
1615
1716from 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
2828app = Flask (__name__ )
2929github_app = GitHubApp (app )
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
139146def 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 :
0 commit comments