Skip to content

Instantly share code, notes, and snippets.

@ThomazPom
Created September 8, 2024 09:19
Show Gist options
  • Save ThomazPom/2d8a9ceb2702dc0de0bf2d1ff398755b to your computer and use it in GitHub Desktop.
Save ThomazPom/2d8a9ceb2702dc0de0bf2d1ff398755b to your computer and use it in GitHub Desktop.

Description: Delete-WorkflowRuns Function

This Delete-WorkflowRuns function, now available in multiple programming languages (PowerShell, Python, JavaScript, and Bash), is used to automate the deletion of GitHub Actions workflow runs in a specified repository. It interacts with GitHub's REST API using the GitHub CLI (gh) to fetch and delete workflow runs by their IDs.


Function Overview:

  1. Parameters:

    • username: The GitHub username or organization name.
    • reponame: The name of the repository from which to delete workflow runs.
  2. Logic:

    • The function first checks if both username and reponame parameters are provided. If either is missing, it outputs a usage message and exits.
    • It then uses the gh command-line tool to fetch a list of workflow runs for the specified repository via the GitHub API.
    • If workflow runs are found, it iterates over each run ID and sends a DELETE request to remove the corresponding workflow run.
    • If no workflow runs are found, it outputs a message indicating there are no runs to delete.
    • After processing, the function outputs a message confirming the deletion of all workflow runs.

Use Cases:

This function is useful for GitHub repository maintainers or administrators who want to:

  • Clean up old or unused workflow runs.
  • Automate the deletion process for multiple repositories.
  • Reduce clutter and improve repository management by managing workflow runs programmatically.

Important Notes:

  • GitHub CLI (gh): This tool is required for the function to work. The CLI provides an interface to interact with GitHub APIs.
  • Permissions: The user executing the script must have appropriate permissions (e.g., admin or maintain rights) to delete workflow runs in the repository.

Languages Supported:

  • PowerShell: The original script, ideal for Windows environments or platforms supporting PowerShell.
  • Python: Suitable for cross-platform automation, using the subprocess module to execute GitHub CLI commands.
  • JavaScript (Node.js): A common choice for web developers who may want to integrate this script with other Node.js automation tools.
  • Bash: Best for Unix-based systems, such as Linux and macOS, where Bash scripting is widely used for automation tasks.

Each version of the function behaves similarly and serves the same purpose, with syntax adapted to the corresponding language.

const { execSync } = require('child_process');
function deleteWorkflowRuns(username, reponame) {
if (!username || !reponame) {
console.log("Usage: deleteWorkflowRuns(username, reponame)");
return 1;
}
console.log(`Fetching workflow runs for ${username}/${reponame}...`);
try {
// Fetch the workflow runs
const result = execSync(`gh api /repos/${username}/${reponame}/actions/runs`).toString();
const runs = JSON.parse(result).workflow_runs;
const runIds = runs.map(run => run.id);
if (runIds.length === 0) {
console.log("No workflow runs found.");
return 0;
}
runIds.forEach(runId => {
console.log(`Deleting workflow run ID ${runId}`);
execSync(`gh api -X DELETE /repos/${username}/${reponame}/actions/runs/${runId}`);
});
console.log("All workflow runs deleted.");
} catch (error) {
console.error(`Error: ${error.message}`);
return 1;
}
}
// Example usage
deleteWorkflowRuns("your-username", "your-repo");
function Delete-WorkflowRuns {
param (
[string]$username,
[string]$reponame
)
if (-not $username -or -not $reponame) {
Write-Host "Usage: Delete-WorkflowRuns -username <username> -reponame <reponame>"
return 1
}
Write-Host "Fetching workflow runs for $username/$reponame..."
# Fetch the workflow runs and extract the run IDs
$runs = gh api "/repos/$username/$reponame/actions/runs" | ConvertFrom-Json | ForEach-Object { $_.workflow_runs.id }
if (-not $runs) {
Write-Host "No workflow runs found."
return 0
}
foreach ($runId in $runs) {
Write-Host "Deleting workflow run ID $runId"
gh api -X DELETE "/repos/$username/$reponame/actions/runs/$runId"
}
Write-Host "All workflow runs deleted."
}
import subprocess
import json
def delete_workflow_runs(username, reponame):
if not username or not reponame:
print("Usage: delete_workflow_runs(username, reponame)")
return 1
print(f"Fetching workflow runs for {username}/{reponame}...")
try:
# Fetch the workflow runs
result = subprocess.run(
['gh', 'api', f'/repos/{username}/{reponame}/actions/runs'],
capture_output=True, text=True
)
runs = json.loads(result.stdout)['workflow_runs']
run_ids = [run['id'] for run in runs]
if not run_ids:
print("No workflow runs found.")
return 0
for run_id in run_ids:
print(f"Deleting workflow run ID {run_id}")
subprocess.run(['gh', 'api', '-X', 'DELETE', f'/repos/{username}/{reponame}/actions/runs/{run_id}'])
print("All workflow runs deleted.")
except Exception as e:
print(f"Error: {e}")
return 1
# Example usage
delete_workflow_runs("your-username", "your-repo")
#!/bin/bash
delete_workflow_runs() {
local username="$1"
local reponame="$2"
if [ -z "$username" ] || [ -z "$reponame" ]; then
echo "Usage: delete_workflow_runs <username> <reponame>"
return 1
fi
echo "Fetching workflow runs for $username/$reponame..."
# Fetch the workflow runs
runs=$(gh api "/repos/$username/$reponame/actions/runs" | jq -r '.workflow_runs[].id')
if [ -z "$runs" ]; then
echo "No workflow runs found."
return 0
fi
for runId in $runs; do
echo "Deleting workflow run ID $runId"
gh api -X DELETE "/repos/$username/$reponame/actions/runs/$runId"
done
echo "All workflow runs deleted."
}
# Example usage
delete_workflow_runs "your-username" "your-repo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment