Last active
October 23, 2023 18:46
-
-
Save thevickypedia/fecf024c108bf296c52d6682ffca7a4e to your computer and use it in GitHub Desktop.
Delete GitHub workflows using API
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
import os | |
from typing import List | |
import requests | |
SESSION = requests.Session() | |
headers = { | |
'Accept': 'application/vnd.github+json', | |
'Authorization': f"Bearer {os.getenv('GIT_TOKEN')}", | |
'X-GitHub-Api-Version': '2022-11-28', | |
} | |
class WorkFlow: | |
def __init__(self, owner: str, repo: str): | |
self.owner = owner | |
self.repo = repo | |
def get_workflow_id_by_name(self, name: str) -> int: | |
url = f"https://api.github.com/repos/{self.owner}/{self.repo}/actions/workflows" | |
res = SESSION.get(url) | |
if not res.ok: | |
raise res.raise_for_status() | |
names = [] | |
for workflow in res.json()['workflows']: | |
names.append(workflow['name']) | |
if workflow['name'] == name: | |
return workflow['id'] | |
else: | |
raise ValueError( | |
f"\n\tNo workflows were found with the name: {name}\n\tAvailable: {', '.join(names)}" | |
) | |
def delete_workflow_by_id(self, workflow_id: int, run_numbers: List[int] = None, dry_run: bool = False): | |
url = f"https://api.github.com/repos/{self.owner}/{self.repo}/actions/workflows/{workflow_id}/runs" | |
response = SESSION.get(url) | |
if not any((dry_run, run_numbers)): | |
raise ValueError( | |
"\n\tEither 'dry_run' or 'run_numbers' is required!" | |
) | |
for workflow in response.json()['workflow_runs']: | |
if dry_run: | |
print(workflow['id'], workflow['display_title'], workflow['run_number'], | |
workflow['head_commit']['message'].split('\n')) | |
continue | |
if not os.getenv('GIT_TOKEN'): | |
raise ValueError( | |
"\n\t'GIT_TOKEN' is required to proceed" | |
) | |
if workflow['run_number'] in run_numbers: | |
print(workflow['id'], workflow['display_title'], workflow['run_number'], | |
workflow['head_commit']['message'].split('\n')) | |
url = f"https://api.github.com/repos/{self.owner}/{self.repo}/actions/runs/{workflow['id']}" | |
res = SESSION.delete(url, headers=headers) | |
if res.ok: | |
print('successful') | |
else: | |
print(url) | |
print(res.text) | |
print('unsuccessful') | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment