Files
Bifrost/src/main/resources/static/import.js
T
Arnaud Dartois 021281f3dd
Build Bifrost / build (push) Failing after 2m37s
feat: add reproducible local import validation
2026-10-29 10:56:19 +01:00

171 lines
7.9 KiB
JavaScript

(function () {
window.registerExtension("bifrost/import", function (options) {
const root = options.el;
const selected = new Map();
const resultById = new Map();
const tableRows = new Map();
let organizations = [];
let repositories = [];
root.innerHTML = "";
const heading = document.createElement("h1");
heading.textContent = "Import from Gitea";
const status = document.createElement("p");
status.setAttribute("role", "status");
const selectorLabel = document.createElement("label");
selectorLabel.textContent = "Organization ";
const selector = document.createElement("select");
selector.setAttribute("aria-label", "Organization");
selectorLabel.appendChild(selector);
const selectAll = document.createElement("button");
selectAll.type = "button";
selectAll.textContent = "Select all (displayed organization)";
const importButton = document.createElement("button");
importButton.type = "button";
importButton.textContent = "Import selected repositories";
const table = document.createElement("table");
const head = table.createTHead().insertRow();
["Select", "Organization", "Repository", "Default branch", "URL", "Status"].forEach(function (name) {
const cell = document.createElement("th");
cell.scope = "col";
cell.textContent = name;
head.appendChild(cell);
});
const body = table.createTBody();
root.append(heading, status, selectorLabel, selectAll, importButton, table);
function keyOf(org, repo) {
let value = (org + "_" + repo).replace(/[^A-Za-z0-9_.:-]/g, "_").toLowerCase();
if (!/^[a-z0-9]/.test(value)) value = "_" + value;
return value;
}
function request(path, init) {
const options = Object.assign({ credentials: "same-origin" }, init || {});
options.headers = Object.assign({ "X-Requested-With": "XMLHttpRequest" }, options.headers || {});
const xsrfCookie = document.cookie.split("; ").find(function (cookie) { return cookie.startsWith("XSRF-TOKEN="); });
if (xsrfCookie && (options.method || "GET").toUpperCase() !== "GET") {
options.headers["X-XSRF-TOKEN"] = xsrfCookie.substring("XSRF-TOKEN=".length);
}
return fetch(path, options).then(function (response) {
if (!response.ok) return response.text().then(function (text) { throw new Error(text || ("Request failed (" + response.status + ")")); });
return response.json();
});
}
function repositoryId(repository) {
return repository.org + "/" + repository.name;
}
function render() {
body.textContent = "";
tableRows.clear();
repositories.forEach(function (repository) {
const row = body.insertRow();
const id = repositoryId(repository);
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = selected.has(id);
checkbox.disabled = repository.alreadyImported === true;
checkbox.setAttribute("aria-label", "Select " + repository.org + "/" + repository.name);
checkbox.addEventListener("change", function () {
if (checkbox.checked) selected.set(id, repository);
else selected.delete(id);
});
row.insertCell().appendChild(checkbox);
row.insertCell().textContent = repository.org;
row.insertCell().textContent = repository.name;
row.insertCell().textContent = repository.defaultBranch || "";
const urlCell = row.insertCell();
try {
const repositoryUrl = new URL(repository.url);
if (repositoryUrl.protocol === "http:" || repositoryUrl.protocol === "https:") {
const link = document.createElement("a");
link.href = repositoryUrl.href;
link.textContent = repository.url;
link.rel = "noopener noreferrer";
urlCell.appendChild(link);
} else {
urlCell.textContent = "Invalid repository URL";
}
} catch (error) {
urlCell.textContent = "Invalid repository URL";
}
row.insertCell().textContent = resultById.get(id) || (repository.alreadyImported ? "Already imported" : "");
if (repository.alreadyImported) row.style.opacity = "0.55";
tableRows.set(id, checkbox);
});
}
function loadRepositories() {
const organization = selector.value;
status.textContent = "Loading repositories…";
const selectedOrganizations = organization === "*" ? organizations : [organization];
Promise.all(selectedOrganizations.map(function (org) {
return request("/api/bifrost/repos?org=" + encodeURIComponent(org)).then(function (data) { return data.repositories || []; });
})).then(function (groups) {
repositories = groups.flat();
}).then(function () {
status.textContent = repositories.length + " repositories displayed.";
render();
}).catch(function (error) { status.textContent = error.message; });
}
request("/api/bifrost/orgs").then(function (data) {
organizations = data.organizations || [];
const allOption = document.createElement("option");
allOption.value = "*";
allOption.textContent = "All organizations";
selector.appendChild(allOption);
organizations.forEach(function (org) {
const option = document.createElement("option");
option.value = org;
option.textContent = org;
selector.appendChild(option);
});
selector.addEventListener("change", loadRepositories);
if (organizations.length) loadRepositories();
else status.textContent = "No allowed organizations are configured.";
}).catch(function (error) { status.textContent = error.message; });
selectAll.addEventListener("click", function () {
repositories.forEach(function (repository) {
if (!repository.alreadyImported) selected.set(repositoryId(repository), repository);
});
render();
});
importButton.addEventListener("click", function () {
const items = Array.from(selected.values());
if (!items.length) { status.textContent = "Select at least one repository."; return; }
const keys = new Map();
for (const item of items) {
const key = keyOf(item.org, item.name);
if (keys.has(key)) {
resultById.set(repositoryId(item), "Error: project key collides with " + keys.get(key) + ".");
resultById.set(keys.get(key), "Error: project key collides with " + repositoryId(item) + ".");
} else keys.set(key, repositoryId(item));
}
const collisions = items.filter(function (item) { return (resultById.get(repositoryId(item)) || "").startsWith("Error:"); });
const permittedItems = items.filter(function (item) { return !collisions.includes(item); });
if (!permittedItems.length) { render(); return; }
status.textContent = "Importing selected repositories…";
const payload = permittedItems.map(function (item) { return { org: item.org, repo: item.name }; });
request("/api/bifrost/import", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ selection: JSON.stringify(payload) }) })
.then(function (data) {
(data.results || []).forEach(function (result) {
const id = result.org + "/" + result.repo;
const label = result.status === "created" ? (result.message.indexOf("link could not") >= 0 ? "Created; link failed" : "Created") :
result.status === "already_exists" ? "Already exists" : "Error: " + result.message;
resultById.set(id, label);
});
status.textContent = "Import finished.";
permittedItems.forEach(function (item) { selected.delete(repositoryId(item)); });
loadRepositories();
}).catch(function (error) { status.textContent = error.message; render(); });
});
return function () { root.textContent = ""; };
});
}());