Skip to content

Commit ac5081d

Browse files
DEVOPS-50 new files
1 parent c0a71c5 commit ac5081d

File tree

3 files changed

+189
-0
lines changed

3 files changed

+189
-0
lines changed

add_a_repo_to_github_app.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import requests
2+
import json
3+
import os
4+
import argparse
5+
from dotenv import load_dotenv
6+
from list_repos_in_org import list_repos_in_github_org
7+
from list_github_app_matching_name import list_github_apps_in_organization_matching_name
8+
9+
def add_repository_to_github_app(organization:str,matching_repos: list[dict], app_short_list: list[dict] ):
10+
"""
11+
add repos to github app using rest api
12+
:return:
13+
https://docs.github.com/en/rest/apps/installations?apiVersion=2022-11-28#add-a-repository-to-an-app-installation
14+
"""
15+
# Assuming that the Github app name doesnot contain any special cgharacters and github app name is same as app_slug.
16+
print(f'Matching repos are: {matching_repos}')
17+
print(f'GitHub App details are: {app_short_list}')
18+
add_repo_to_github_app_endpoint = f'https://api.github.com/user/installations/{id}/repositories/REPOSITORY_ID
19+
'
20+
headers = {
21+
"Accept": "application/vnd.github+json",
22+
"Authorization": f"Bearer {os.getenv('GH_TOKEN')}",
23+
"X-GitHub-Api-Version": "2022-11-28"
24+
}
25+
26+
27+
def main():
28+
""" to test the script"""
29+
load_dotenv()
30+
organization = os.getenv('ORGANIZATION')
31+
parser = argparse.ArgumentParser(description="Add specific repos matching a string in repo names to a github teams")
32+
parser.add_argument("--search_string", required=True, type=str, help="github repo name search string")
33+
parser.add_argument("--github_app_name", required=True, type=str, help="github repo name search string")
34+
args = parser.parse_args()
35+
search_string = args.search_string
36+
github_app_name = args.github_app_name
37+
# Function call for repo list
38+
matching_repos = list_repos_in_github_org(organization, search_string)
39+
# Function call for github app details
40+
app_short_list = list_github_apps_in_organization_matching_name(organization, github_app_name)
41+
# Fucntion call for adding repo to github app
42+
add_repository_to_github_app(organization, matching_repos, app_short_list)
43+
44+
45+
if __name__ == "__main__":
46+
main()

list_github_app_matching_name.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# reference: https://docs.github.com/en/rest/orgs/orgs?apiVersion=2022-11-28#list-app-installations-for-an-organization
2+
import requests
3+
import json
4+
import argparse
5+
import os
6+
from dotenv import load_dotenv
7+
8+
def list_github_apps_in_organization_matching_name(organization: str, github_app_name: str):
9+
"""
10+
list GitHub apps in the orgaization
11+
:param organization:
12+
:return:
13+
reference: https://docs.github.com/en/rest/orgs/orgs?apiVersion=2022-11-28#list-app-installations-for-an-organization
14+
"""
15+
16+
list_github_app_endpoint = f'https://api.github.com/orgs/{organization}/installations'
17+
headers = {
18+
"Accept": "application/vnd.github+json",
19+
"Authorization": f"Bearer {os.getenv('GH_TOKEN')}",
20+
"X-GitHub-Api-Version": "2022-11-28"
21+
}
22+
23+
response = requests.get(list_github_app_endpoint, headers=headers)
24+
response_json = response.json()
25+
response_code = response.status_code
26+
27+
if response_code == 200:
28+
print(f'Listing GitHub Apps in {organization} organization successful')
29+
else:
30+
print(f'Listing GitHub Apps in {organization} failed')
31+
32+
total_num_of_github_app_installations = response_json['total_count']
33+
print(f'Found {total_num_of_github_app_installations} GitHub App in {organization} organization')
34+
35+
# Extract the list of dictionaries
36+
list_of_installations = response_json["installations"]
37+
38+
# Convert list of dictionaries to JSON string
39+
json_data = json.dumps(list_of_installations, indent=4)
40+
41+
# Write JSON string to a file
42+
with open("list_of_github_installations.json", "w") as file:
43+
file.write(json_data)
44+
45+
app_short_list = []
46+
for app in list_of_installations:
47+
app_dict = {}
48+
if app['app_slug'] == github_app_name:
49+
app_dict['id'] = app['id']
50+
app_dict['app_id'] = app['app_id']
51+
app_dict['app_slug'] = app['app_slug']
52+
app_short_list.append(app_dict)
53+
54+
return app_short_list
55+
56+
def main():
57+
""" To test the code """
58+
load_dotenv()
59+
GH_TOKEN = os.getenv('gh_token')
60+
organization = os.getenv('ORGANIZATION')
61+
# organization = 'devwithkrishna'
62+
parser = argparse.ArgumentParser(description="Get the App installation id from name")
63+
parser.add_argument("--github_app_name", required=True, type=str, help="github repo name search string")
64+
args = parser.parse_args()
65+
github_app_name = args.github_app_name
66+
# Function call
67+
app_short_list = list_github_apps_in_organization_matching_name(organization, github_app_name)
68+
69+
70+
if __name__ == '__main__':
71+
main()
72+
73+
74+

list_repos_in_org.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import requests
2+
import os
3+
import argparse
4+
from dotenv import load_dotenv
5+
6+
def list_repos_in_github_org(orgaization: str, search_string: str):
7+
""" get the repo id of repos natching the search string """
8+
9+
# GitHub endpoint for listing repos under an organization
10+
repo_url = f"https://api.github.com/orgs/{orgaization}/repos"
11+
# print(f"github api endpoint url {repo_url}")
12+
13+
headers = {
14+
"Accept": "application/vnd.github+json",
15+
"Authorization": f"Bearer {os.getenv('GH_TOKEN')}",
16+
"X-GitHub-Api-Version": "2022-11-28"
17+
}
18+
19+
# Define pagination parameters
20+
per_page = 100 # Number of records per page
21+
page = 1 # Initial page number
22+
list_of_repo_names = []
23+
24+
while True:
25+
# Add pagination parameters to the URL
26+
params = {'per_page': per_page, 'page': page}
27+
response = requests.get(repo_url, headers=headers, params=params)
28+
response_json = response.json() ## Github repo details
29+
30+
# Checking the API status code
31+
if response.status_code == 200:
32+
print(f"API request successful on {repo_url}")
33+
# print(response_json)
34+
else:
35+
print(f"API request failed with status code {response.status_code}:")
36+
# print(response_json)
37+
break
38+
39+
# Get the repo names from the list of dictionaries and add to another list
40+
for repo in response_json:
41+
repo_dict = {}
42+
repo_dict['name'] = repo['full_name']
43+
repo_dict['id'] = repo['id']
44+
list_of_repo_names.append(repo_dict)
45+
46+
page += 1 # Move to the next page
47+
48+
49+
# Finding repos starting with search string
50+
matching_repos = [repo for repo in list_of_repo_names if repo['name'].startswith(f'{orgaization}/{search_string}')]
51+
print(f"Matching repos {search_string} are: {matching_repos}")
52+
return matching_repos
53+
# Break the loop if no more pages
54+
if len(response_json) < per_page:
55+
break
56+
57+
58+
def main():
59+
""" main function to test"""
60+
load_dotenv()
61+
organization = os.getenv('ORGANIZATION')
62+
parser = argparse.ArgumentParser(description="Add specific repos matching a string in repo names to a github teams")
63+
parser.add_argument("--search_string", required=True, type=str, help="github repo name search string")
64+
args = parser.parse_args()
65+
search_string = args.search_string
66+
matching_repos = list_repos_in_github_org(organization, search_string)
67+
68+
if __name__ == '__main__':
69+
main()

0 commit comments

Comments
 (0)