Clean up gitlab pipelines

I’ve been trying to set up a new repository with a CI in my GitLab environment. During the configuration, I’d created many failed jobs and pipelines. I searched for a solution to delete and remove the failed pipelines from my history. This was only possible for single jobs. This was not a satisfying solution for me. Therefore, I’ve created a small JavaScript snippet.

Usage:

Go to your pipelines view for example gitlab.com/user/project/-/pipelines and execute the JavaScript.

Sadly, this code requires personal access tokens. I was hoping it was working with the already stored session information in the cookies. You can find all here. The snippet will ask for the token and will store it in the local storage.

Code:

let token;
function checkToken() {
	const KEY = "PIPELINEDELETIONTOKEN";
	token = localStorage.getItem(KEY);
	if (!token) {
		token = window.prompt(
			"Please input gitlab token for pipeline deletion.",
			""
		);
		localStorage.setItem(KEY, token);
	}

	if (!token) {
		throw "Missing token to delete pipelines";
	}
}

function send(verb, url, callback) {
	const xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4 && xhr.status == 200 && callback) {
			callback(xhr.responseText);
		}
	};
	xhr.open(verb, url);
	xhr.setRequestHeader("PRIVATE-TOKEN", token);
	xhr.send();
}

const getCurrentProjectId = () => document.body.getAttribute("data-project-id");

function getShownPipelineIds() {
	return Array.prototype.slice
		.call(document.querySelectorAll("[data-testid='pipeline-url-link']"))
		.map((x) => x.innerText.match(/(\d*)$/))
		.filter((x) => x.length > 1)
		.map((x) => x[1]);
}

const deletePipeline = (projectId, pipelineId) =>
	send(
		"DELETE",
		`${location.origin}/api/v4/projects/${projectId}/pipelines/${pipelineId}`
	);
function deleteShownPipelines() {
	checkToken();
	const projectId = getCurrentProjectId();
	const ids = getShownPipelineIds();
	ids.forEach((id) => deletePipeline(projectId, id));
	location.reload();
}
deleteShownPipelines();