Files
Bifrost/src/main/resources/static/import.js
T

178 lines
8.4 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) {
return fetch(path, Object.assign({ credentials: "same-origin", headers: { "X-Requested-With": "XMLHttpRequest" } }, init || {}))
.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 = "Validating selection…";
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 (validation) {
const approvedItems = (validation.repositories || []).map(function (repository) {
return { org: repository.org, name: repository.repo, url: repository.url, defaultBranch: repository.defaultBranch };
});
return Promise.all(approvedItems.map(function (item) {
const id = repositoryId(item);
const key = keyOf(item.org, item.name);
return request("/api/projects/create", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ project: key, name: item.name }) })
.then(function () {
return request("/api/project_links/create", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ projectKey: key, name: "Gitea", url: item.url }) })
.then(function () { resultById.set(id, "Created"); })
.catch(function () { resultById.set(id, "Created; repository link could not be added"); });
})
.catch(function (error) {
const text = error.message || "";
resultById.set(id, /already exists|already been taken|already used/i.test(text) ? "Already exists" : "Error: " + text);
});
}));
}).then(function () {
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 = ""; };
});
}());