-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Sc 19672 create a tool to generate teams from GitHub part3 #3
Merged
k-shlomi
merged 30 commits into
main
from
sc-19672-create-a-tool-to-generate-teams-from-github-part3
Aug 23, 2023
Merged
Changes from 28 commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
5fb06a2
rename team objects
k-shlomi 9ef86e4
modify the code to not use cli argument --input, but to apss filename…
k-shlomi 57001e0
initial tests for create_teams.py
k-shlomi b15fd8a
fix test test_parse_input_file
k-shlomi bea14b5
implement test_parse_input_file_with_invalid_json
k-shlomi 1f52698
cleanup
k-shlomi 9946ff4
cleanup
k-shlomi 3e75d23
Merge branch 'sc-19672-create-a-tool-to-generate-teams-from-github-pa…
k-shlomi 0e5b4d5
format the logger
k-shlomi 911d937
log fix
k-shlomi 77e8a77
log fix
k-shlomi 2ef55f9
Merge branch 'main' into sc-19672-create-a-tool-to-generate-teams-fro…
k-shlomi f9e1c71
cr fix
k-shlomi 18c48bd
use load_dotenv() only in main entrypoint file
k-shlomi 6ab4eb7
readme update
k-shlomi 5cf21f4
prepare for adding team exclusion
k-shlomi 272b420
implemented get_desired_teams that gets a refined team list with excl…
k-shlomi 759b207
first polyfactory for models
k-shlomi a853af0
initial factories for other models
k-shlomi 76bfe06
doc
k-shlomi 16c9364
fix factories
k-shlomi 444adac
add test_process_teams
k-shlomi e38c456
add tests
k-shlomi a15c816
add ability to exclude topic wildcards
k-shlomi 515fb68
fix test
k-shlomi 1aa8ee4
lint
k-shlomi 3f19c26
update README
k-shlomi 5ea73d7
cleanup
k-shlomi 4b337c2
cr fixes
k-shlomi 920b844
cr fixes
k-shlomi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,4 +2,5 @@ | |
pytest==7.4.0 | ||
pytest-mock==3.11.1 | ||
pytest-cov==4.0.0 | ||
polyfactory==2.7.2 | ||
flake8>=3.9.2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,15 +7,18 @@ | |
from dotenv import load_dotenv | ||
from loguru import logger | ||
from pydantic import ValidationError | ||
|
||
from src.shared.clients.jit import get_existing_teams, create_teams, list_assets, add_teams_to_asset, delete_teams, \ | ||
get_jit_jwt_token | ||
from src.shared.diff_tools import get_different_items_in_lists | ||
from src.shared.models import Asset, TeamObject, Organization, TeamTemplate | ||
from src.shared.models import Asset, TeamAttributes, Organization, TeamStructure | ||
|
||
# Load environment variables from .env file. | ||
load_dotenv() | ||
|
||
logger.remove() # Remove default handler | ||
logger_format = "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | {message}" | ||
logger.add(sys.stderr, format=logger_format) | ||
|
||
|
||
def parse_input_file() -> Organization: | ||
""" | ||
|
@@ -27,39 +30,34 @@ | |
# Create the argument parser | ||
parser = argparse.ArgumentParser(description="Retrieve teams and assets") | ||
|
||
# Add the --input argument | ||
parser.add_argument("--input", help="Path to a JSON file") | ||
# Add the file argument | ||
parser.add_argument("file", help="Path to a JSON file") | ||
|
||
# Parse the command line arguments | ||
args = parser.parse_args() | ||
|
||
# Check if the --input argument is provided | ||
if args.input: | ||
# Check if the file exists and is a JSON file | ||
if not os.path.isfile(args.input): | ||
logger.error("Error: File does not exist.") | ||
sys.exit(1) | ||
if not args.input.endswith(".json"): | ||
logger.error("Error: File is not a JSON file.") | ||
sys.exit(1) | ||
|
||
# Read the JSON file | ||
with open(args.input, "r") as file: | ||
json_data = file.read() | ||
|
||
# Parse the JSON data | ||
try: | ||
data = json.loads(json_data) | ||
return Organization(teams=[TeamTemplate(**team) for team in data["teams"]]) | ||
except ValidationError as e: | ||
logger.error(f"Failed to validate input file: {e}") | ||
sys.exit(1) | ||
else: | ||
logger.error("No input file provided.") | ||
# Check if the file exists and is a JSON file | ||
if not os.path.isfile(args.file): | ||
logger.error("Error: File does not exist.") | ||
sys.exit(1) | ||
if not args.file.endswith(".json"): | ||
logger.error("Error: File is not a JSON file.") | ||
sys.exit(1) | ||
|
||
# Read the JSON file | ||
with open(args.file, "r") as file: | ||
json_data = file.read() | ||
|
||
# Parse the JSON data | ||
try: | ||
data = json.loads(json_data) | ||
return Organization(teams=[TeamStructure(**team) for team in data["teams"]]) | ||
except (ValidationError, KeyError) as e: | ||
logger.error(f"Failed to validate input file: {e}") | ||
sys.exit(1) | ||
|
||
def update_assets(token, organization): | ||
|
||
def update_assets(token, assets: List[Asset], organization): | ||
""" | ||
Update the assets with the teams specified in the organization. | ||
|
||
|
@@ -71,13 +69,22 @@ | |
None | ||
""" | ||
logger.info("Updating assets.") | ||
assets: List[Asset] = list_assets(token) | ||
|
||
asset_to_team_map = get_teams_for_assets(organization) | ||
existing_teams: List[str] = [t.name for t in get_existing_teams(token)] | ||
for asset in assets: | ||
teams_to_update = asset_to_team_map.get(asset.asset_name, []) | ||
if teams_to_update: | ||
logger.info(f"Adding teams {teams_to_update} to asset {asset.asset_name}") | ||
excluded_teams = get_different_items_in_lists(teams_to_update, existing_teams) | ||
if excluded_teams: | ||
logger.info(f"Excluding team(s) {excluded_teams} for asset '{asset.asset_name}'") | ||
teams_to_update = list(set(teams_to_update) - set(excluded_teams)) | ||
logger.info(f"Syncing team(s) {teams_to_update} to asset '{asset.asset_name}'") | ||
add_teams_to_asset(token, asset, teams_to_update) | ||
else: | ||
if asset.tags and "team" in [t.name for t in asset.tags]: | ||
logger.info(f"Removing all teams from asset '{asset.asset_name}'") | ||
add_teams_to_asset(token, asset, teams_to_update) | ||
|
||
|
||
def get_teams_to_create(topic_names: List[str], existing_team_names: List[str]) -> List[str]: | ||
|
@@ -108,7 +115,43 @@ | |
return get_different_items_in_lists(existing_team_names, topic_names) | ||
|
||
|
||
def process_teams(token, organization): | ||
def get_desired_teams(assets: List[Asset], organization: Organization) -> List[str]: | ||
""" | ||
Get the desired teams based on the assets and organization. | ||
Also filter out teams that match the TEAM_WILDCARD_TO_EXCLUDE environment variable. | ||
|
||
Args: | ||
assets (List[Asset]): The list of assets. | ||
organization (Organization): The organization object. | ||
|
||
Returns: | ||
List[str]: The names of the desired teams. | ||
""" | ||
desired_teams = [] | ||
for team in organization.teams: | ||
team_resources = [] | ||
for resource in team.resources: | ||
if resource.type == "github_repo" and resource.name in [asset.asset_name for asset in assets]: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please move There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ok |
||
team_resources.append(resource.name) | ||
if team_resources: | ||
desired_teams.append(team.name) | ||
|
||
wildcards_to_exclude = os.getenv("TEAM_WILDCARD_TO_EXCLUDE", "").split(",") | ||
final_desired_teams = [] | ||
for team_name in desired_teams: | ||
exclude_team = False | ||
for wildcard in wildcards_to_exclude: | ||
wildcard = wildcard.strip().strip("*") | ||
if wildcard and wildcard in team_name: | ||
exclude_team = True | ||
break | ||
if not exclude_team: | ||
final_desired_teams.append(team_name) | ||
|
||
return final_desired_teams | ||
|
||
|
||
def process_teams(token, organization, assets: List[Asset]) -> List[str]: | ||
""" | ||
Process the teams in the organization and create or delete teams as necessary. | ||
We will delete the teams at a later stage to avoid possible synchronization issues. | ||
|
@@ -121,13 +164,14 @@ | |
List[str]: The names of the teams to delete. | ||
""" | ||
logger.info("Determining required changes in teams.") | ||
desired_teams = [t.name for t in organization.teams] | ||
existing_teams: List[TeamObject] = get_existing_teams(token) | ||
|
||
desired_teams = get_desired_teams(assets, organization) | ||
existing_teams: List[TeamAttributes] = get_existing_teams(token) | ||
existing_team_names = [team.name for team in existing_teams] | ||
teams_to_create = get_teams_to_create(desired_teams, existing_team_names) | ||
teams_to_delete = get_teams_to_delete(desired_teams, existing_team_names) | ||
if teams_to_create: | ||
logger.info(f"Creating {len(teams_to_create)} teams: {teams_to_create}") | ||
logger.info(f"Creating {len(teams_to_create)} team(s): {teams_to_create}") | ||
create_teams(token, teams_to_create) | ||
return teams_to_delete | ||
|
||
|
@@ -166,15 +210,17 @@ | |
logger.error("Failed to parse input file. Exiting...") | ||
return | ||
|
||
teams_to_delete = process_teams(jit_token, organization) | ||
assets: List[Asset] = list_assets(jit_token) | ||
|
||
teams_to_delete = process_teams(jit_token, organization, assets) | ||
|
||
update_assets(jit_token, organization) | ||
update_assets(jit_token, assets, organization) | ||
|
||
if teams_to_delete: | ||
logger.info(f"Deleting {len(teams_to_delete)} teams: {teams_to_delete}") | ||
logger.info(f"Deleting {len(teams_to_delete)} team(s): {teams_to_delete}") | ||
delete_teams(jit_token, teams_to_delete) | ||
logger.info("Successfully completed teams sync.") | ||
|
||
|
||
if __name__ == '__main__': | ||
logger.add("app.log", rotation="5 MB", level="INFO") | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.