Skip to content

Instantly share code, notes, and snippets.

@rwv
Last active February 7, 2025 02:28
Show Gist options
  • Save rwv/864935b721874f848a108c706d9ce274 to your computer and use it in GitHub Desktop.
Save rwv/864935b721874f848a108c706d9ce274 to your computer and use it in GitHub Desktop.
Remove old GitHub Actions artifacts
// Script to delete old GitHub Actions artifacts from the 'user/repo' repository
const githubToken = 'github_pat_xxxxxxx'; // Replace with your GitHub token
const headers = {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `Bearer ${githubToken}`,
'User-Agent': 'ArtifactsCleaner/1.0'
};
async function fetchJson(url) {
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`Failed to fetch ${url}, Status: ${response.status}`);
}
return response.json();
}
async function deleteOldArtifacts() {
const repository = 'user/repo'; // Replace
console.log(`Checking artifacts for repository: ${repository}`);
let pageIndex = 1;
const pageSize = 100;
let data;
do {
const artifactsUrl = `https://api.github.com/repos/${repository}/actions/artifacts?per_page=${pageSize}&page=${pageIndex}`;
try {
data = await fetchJson(artifactsUrl);
for (const artifact of data.artifacts) {
const createdAt = new Date(artifact.created_at);
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
if (!artifact.expired && createdAt < oneDayAgo) {
await deleteArtifact(repository, artifact);
}
}
pageIndex++;
} catch (error) {
console.error(`Error retrieving artifacts for ${repository}: ${error.message}`);
break;
}
} while (data.artifacts.length === pageSize);
}
async function deleteArtifact(repository, artifact) {
const deleteUrl = `https://api.github.com/repos/${repository}/actions/artifacts/${artifact.id}`;
try {
const response = await fetch(deleteUrl, { method: 'DELETE', headers });
if (response.ok) {
console.log(`Deleted artifact: ${artifact.name} (Created: ${artifact.created_at})`);
} else {
console.error(`Failed to delete artifact: ${artifact.name}, Status: ${response.status}`);
}
} catch (error) {
console.error(`Error deleting artifact: ${artifact.name}, ${error.message}`);
}
}
async function cleanUpArtifacts() {
await deleteOldArtifacts();
}
cleanUpArtifacts();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment