Implement the Gitea extension
The repository was a bare Nova scaffold. This builds it out to match the
capabilities of the official Gitea VS Code extension.
Sidebar sections:
- Current Branch: pull requests and workflow runs for the checked-out
branch, with a current/all/pinned branch filter
- Workflows: runs grouped by workflow file, expanding into jobs, steps,
and artifacts
- Pull Requests: open pull requests across repositories, expanding into
reviews, review comments, and changed files
- Settings: per-instance connection state, plus repository Actions
secrets and variables
Commands cover run control (re-run, re-run failed jobs, re-run a job,
cancel), job logs, artifact download/reveal/open, pull request overview,
diff, checkout, creation, merge and close, the full review cycle, and
secret and variable management. Multiple instances are supported, routed
by git remote host, with tokens held per instance in the Keychain.
Nova exposes no webview, diff editor, editor decorations, or extension
status bar, so four features are shaped differently from the VS Code
original: the pull request timeline renders as Markdown, diffs open as
unified .diff documents, review comments are published through an
IssueCollection so they appear in the gutter and the Issues sidebar, and
a failed run posts a notification. OAuth and insecureSkipVerify have no
Nova equivalent and are omitted. README.md records all of this.
Endpoints were taken from Gitea's published swagger.v1.json. Servers
predating the workflow runs API fall back to /actions/tasks.
Tests/ runs the extension's real code under Node against a stubbed Nova
runtime and a canned Gitea instance: 88 checks, no install step and no
network. Images are generated by Tools/make-icons.py.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MQuusXgZC2dzwpJJ1qhtti
This commit is contained in:
@@ -0,0 +1,338 @@
|
||||
//
|
||||
// Endpoint methods for the Gitea v1 API. Each takes a `repo` of the shape
|
||||
// { owner, name } and returns plain objects with the fields the views need.
|
||||
//
|
||||
|
||||
const { GiteaError } = require("./client.js");
|
||||
const log = require("../util/log.js");
|
||||
|
||||
function segment(value) {
|
||||
return encodeURIComponent(String(value));
|
||||
}
|
||||
|
||||
function repoPath(repo, suffix = "") {
|
||||
return `/repos/${segment(repo.owner)}/${segment(repo.name)}${suffix}`;
|
||||
}
|
||||
|
||||
class GiteaApi {
|
||||
constructor(client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
get baseUrl() {
|
||||
return this.client.baseUrl;
|
||||
}
|
||||
|
||||
// -- Instance ---------------------------------------------------------
|
||||
|
||||
async version() {
|
||||
const body = await this.client.get("/version");
|
||||
return (body && body.version) || "unknown";
|
||||
}
|
||||
|
||||
async currentUser() {
|
||||
return await this.client.get("/user");
|
||||
}
|
||||
|
||||
async accessibleRepositories(limit = 100) {
|
||||
return await this.client.paginate("/user/repos", { limit: limit });
|
||||
}
|
||||
|
||||
async repository(repo) {
|
||||
return await this.client.get(repoPath(repo));
|
||||
}
|
||||
|
||||
async branches(repo, limit = 100) {
|
||||
return await this.client.paginate(repoPath(repo, "/branches"), { limit: limit });
|
||||
}
|
||||
|
||||
async combinedStatus(repo, ref) {
|
||||
return await this.client.get(repoPath(repo, `/commits/${segment(ref)}/status`));
|
||||
}
|
||||
|
||||
// -- Actions: runs ----------------------------------------------------
|
||||
|
||||
/**
|
||||
* Lists workflow runs. Gitea gained /actions/runs in 1.24; older servers only
|
||||
* expose /actions/tasks, which the caller sees as the "recent runs" fallback.
|
||||
*/
|
||||
async listRuns(repo, { limit = 20, branch = null, event = null } = {}) {
|
||||
const query = { limit: limit, branch: branch, event: event };
|
||||
try {
|
||||
const body = await this.client.get(repoPath(repo, "/actions/runs"), { query: query });
|
||||
return {
|
||||
runs: (body && body.workflow_runs) || [],
|
||||
total: (body && body.total_count) || 0,
|
||||
legacy: false,
|
||||
};
|
||||
} catch (error) {
|
||||
if (!(error instanceof GiteaError) || !error.isMissing) throw error;
|
||||
log.debug("falling back to /actions/tasks for", repo.owner + "/" + repo.name);
|
||||
const body = await this.client.get(repoPath(repo, "/actions/tasks"), {
|
||||
query: { limit: limit },
|
||||
});
|
||||
return {
|
||||
runs: (body && body.workflow_runs) || [],
|
||||
total: (body && body.total_count) || 0,
|
||||
legacy: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async listWorkflows(repo) {
|
||||
try {
|
||||
const body = await this.client.get(repoPath(repo, "/actions/workflows"));
|
||||
return (body && body.workflows) || [];
|
||||
} catch (error) {
|
||||
if (error instanceof GiteaError && error.isMissing) return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async listJobs(repo, runId, limit = 50) {
|
||||
const body = await this.client.get(
|
||||
repoPath(repo, `/actions/runs/${segment(runId)}/jobs`),
|
||||
{ query: { limit: limit } },
|
||||
);
|
||||
return (body && body.jobs) || [];
|
||||
}
|
||||
|
||||
async jobLogs(repo, jobId) {
|
||||
return await this.client.get(repoPath(repo, `/actions/jobs/${segment(jobId)}/logs`), {
|
||||
responseType: "text",
|
||||
headers: { Accept: "text/plain, */*" },
|
||||
});
|
||||
}
|
||||
|
||||
async rerunRun(repo, runId) {
|
||||
await this.client.post(repoPath(repo, `/actions/runs/${segment(runId)}/rerun`), null);
|
||||
}
|
||||
|
||||
async rerunFailedJobs(repo, runId) {
|
||||
await this.client.post(
|
||||
repoPath(repo, `/actions/runs/${segment(runId)}/rerun-failed-jobs`),
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
async rerunJob(repo, runId, jobId) {
|
||||
await this.client.post(
|
||||
repoPath(repo, `/actions/runs/${segment(runId)}/jobs/${segment(jobId)}/rerun`),
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
async cancelRun(repo, runId) {
|
||||
await this.client.post(repoPath(repo, `/actions/runs/${segment(runId)}/cancel`), null);
|
||||
}
|
||||
|
||||
// -- Actions: artifacts -----------------------------------------------
|
||||
|
||||
async listArtifacts(repo, runId) {
|
||||
try {
|
||||
const body = await this.client.get(
|
||||
repoPath(repo, `/actions/runs/${segment(runId)}/artifacts`),
|
||||
);
|
||||
return (body && body.artifacts) || [];
|
||||
} catch (error) {
|
||||
if (error instanceof GiteaError && error.isMissing) return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads an artifact zip. Gitea answers the zip endpoint with a redirect
|
||||
* to storage; Nova's fetch follows it, so the bytes come back directly.
|
||||
*/
|
||||
async downloadArtifact(repo, artifact) {
|
||||
const path = artifact.archive_download_url
|
||||
? artifact.archive_download_url
|
||||
: repoPath(repo, `/actions/artifacts/${segment(artifact.id)}/zip`);
|
||||
return await this.client.get(path, {
|
||||
responseType: "binary",
|
||||
headers: { Accept: "application/zip, */*" },
|
||||
});
|
||||
}
|
||||
|
||||
// -- Actions: secrets and variables -----------------------------------
|
||||
|
||||
async listSecrets(repo) {
|
||||
return await this.client.paginate(repoPath(repo, "/actions/secrets"), { limit: 100 });
|
||||
}
|
||||
|
||||
async setSecret(repo, name, value) {
|
||||
await this.client.put(repoPath(repo, `/actions/secrets/${segment(name)}`), {
|
||||
data: value,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteSecret(repo, name) {
|
||||
await this.client.delete(repoPath(repo, `/actions/secrets/${segment(name)}`));
|
||||
}
|
||||
|
||||
async listVariables(repo) {
|
||||
return await this.client.paginate(repoPath(repo, "/actions/variables"), { limit: 100 });
|
||||
}
|
||||
|
||||
async createVariable(repo, name, value) {
|
||||
await this.client.post(repoPath(repo, `/actions/variables/${segment(name)}`), {
|
||||
value: value,
|
||||
});
|
||||
}
|
||||
|
||||
async updateVariable(repo, name, value) {
|
||||
await this.client.put(repoPath(repo, `/actions/variables/${segment(name)}`), {
|
||||
value: value,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteVariable(repo, name) {
|
||||
await this.client.delete(repoPath(repo, `/actions/variables/${segment(name)}`));
|
||||
}
|
||||
|
||||
// -- Pull requests -----------------------------------------------------
|
||||
|
||||
async listPullRequests(repo, { state = "open", limit = 30 } = {}) {
|
||||
return await this.client.paginate(repoPath(repo, "/pulls"), {
|
||||
limit: limit,
|
||||
query: { state: state, sort: "recentupdate" },
|
||||
});
|
||||
}
|
||||
|
||||
async pullRequest(repo, index) {
|
||||
return await this.client.get(repoPath(repo, `/pulls/${segment(index)}`));
|
||||
}
|
||||
|
||||
async pullRequestFiles(repo, index, limit = 200) {
|
||||
return await this.client.paginate(repoPath(repo, `/pulls/${segment(index)}/files`), {
|
||||
limit: limit,
|
||||
});
|
||||
}
|
||||
|
||||
async pullRequestDiff(repo, index) {
|
||||
return await this.client.get(repoPath(repo, `/pulls/${segment(index)}.diff`), {
|
||||
responseType: "text",
|
||||
headers: { Accept: "text/plain, */*" },
|
||||
});
|
||||
}
|
||||
|
||||
async pullRequestCommits(repo, index, limit = 100) {
|
||||
return await this.client.paginate(repoPath(repo, `/pulls/${segment(index)}/commits`), {
|
||||
limit: limit,
|
||||
});
|
||||
}
|
||||
|
||||
async createPullRequest(repo, { head, base, title, body }) {
|
||||
return await this.client.post(repoPath(repo, "/pulls"), {
|
||||
head: head,
|
||||
base: base,
|
||||
title: title,
|
||||
body: body || "",
|
||||
});
|
||||
}
|
||||
|
||||
async closePullRequest(repo, index) {
|
||||
return await this.client.patch(repoPath(repo, `/issues/${segment(index)}`), {
|
||||
state: "closed",
|
||||
});
|
||||
}
|
||||
|
||||
async mergePullRequest(repo, index, { strategy = "merge", title, message } = {}) {
|
||||
await this.client.post(repoPath(repo, `/pulls/${segment(index)}/merge`), {
|
||||
Do: strategy,
|
||||
MergeTitleField: title || "",
|
||||
MergeMessageField: message || "",
|
||||
});
|
||||
}
|
||||
|
||||
// -- Reviews -----------------------------------------------------------
|
||||
|
||||
async listReviews(repo, index) {
|
||||
return await this.client.paginate(repoPath(repo, `/pulls/${segment(index)}/reviews`), {
|
||||
limit: 100,
|
||||
});
|
||||
}
|
||||
|
||||
async reviewComments(repo, index, reviewId) {
|
||||
return await this.client.get(
|
||||
repoPath(repo, `/pulls/${segment(index)}/reviews/${segment(reviewId)}/comments`),
|
||||
);
|
||||
}
|
||||
|
||||
/** Every review comment on a pull request, flattened across its reviews. */
|
||||
async allReviewComments(repo, index) {
|
||||
const reviews = await this.listReviews(repo, index);
|
||||
const withComments = reviews.filter((review) => (review.comments_count || 0) > 0);
|
||||
|
||||
const batches = await Promise.all(
|
||||
withComments.map(async (review) => {
|
||||
try {
|
||||
const comments = await this.reviewComments(repo, index, review.id);
|
||||
return (comments || []).map((comment) =>
|
||||
Object.assign({}, comment, { review: review }),
|
||||
);
|
||||
} catch (error) {
|
||||
log.debug("review comments failed", review.id, String(error));
|
||||
return [];
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return { reviews: reviews, comments: batches.flat() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits a review. `event` is APPROVED, REQUEST_CHANGES, or COMMENT, and
|
||||
* `comments` are file-anchored notes of the shape
|
||||
* { path, body, new_position } / { path, body, old_position }.
|
||||
*/
|
||||
async submitReview(repo, index, { event, body = "", comments = [], commitId } = {}) {
|
||||
return await this.client.post(repoPath(repo, `/pulls/${segment(index)}/reviews`), {
|
||||
event: event,
|
||||
body: body,
|
||||
comments: comments,
|
||||
commit_id: commitId,
|
||||
});
|
||||
}
|
||||
|
||||
async replyToReviewComment(repo, index, commentId, body) {
|
||||
return await this.client.post(
|
||||
repoPath(repo, `/pulls/${segment(index)}/comments/${segment(commentId)}/replies`),
|
||||
{ body: body },
|
||||
);
|
||||
}
|
||||
|
||||
async resolveReviewThread(repo, commentId) {
|
||||
await this.client.post(repoPath(repo, `/pulls/comments/${segment(commentId)}/resolve`), null);
|
||||
}
|
||||
|
||||
async unresolveReviewThread(repo, commentId) {
|
||||
await this.client.post(
|
||||
repoPath(repo, `/pulls/comments/${segment(commentId)}/unresolve`),
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
// -- Issue timeline ----------------------------------------------------
|
||||
|
||||
async timeline(repo, index, limit = 100) {
|
||||
return await this.client.paginate(repoPath(repo, `/issues/${segment(index)}/timeline`), {
|
||||
limit: limit,
|
||||
});
|
||||
}
|
||||
|
||||
async issueComments(repo, index, limit = 100) {
|
||||
return await this.client.paginate(repoPath(repo, `/issues/${segment(index)}/comments`), {
|
||||
limit: limit,
|
||||
});
|
||||
}
|
||||
|
||||
async addIssueComment(repo, index, body) {
|
||||
return await this.client.post(repoPath(repo, `/issues/${segment(index)}/comments`), {
|
||||
body: body,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
exports.GiteaApi = GiteaApi;
|
||||
exports.repoPath = repoPath;
|
||||
@@ -0,0 +1,209 @@
|
||||
//
|
||||
// HTTP client for one Gitea instance. Handles auth, query building, pagination,
|
||||
// binary downloads, and a small concurrency cap so a refresh across several
|
||||
// repositories does not open dozens of sockets at once.
|
||||
//
|
||||
|
||||
const log = require("../util/log.js");
|
||||
|
||||
const MAX_CONCURRENT = 6;
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
class GiteaError extends Error {
|
||||
constructor(message, status, body) {
|
||||
super(message);
|
||||
this.name = "GiteaError";
|
||||
this.status = status;
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
get isAuth() {
|
||||
return this.status === 401 || this.status === 403;
|
||||
}
|
||||
|
||||
get isMissing() {
|
||||
return this.status === 404;
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs at most `max` tasks at once, queueing the rest. */
|
||||
class Limiter {
|
||||
constructor(max) {
|
||||
this.max = max;
|
||||
this.active = 0;
|
||||
this.queue = [];
|
||||
}
|
||||
|
||||
run(task) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.queue.push({ task, resolve, reject });
|
||||
this._drain();
|
||||
});
|
||||
}
|
||||
|
||||
_drain() {
|
||||
while (this.active < this.max && this.queue.length) {
|
||||
const entry = this.queue.shift();
|
||||
this.active += 1;
|
||||
Promise.resolve()
|
||||
.then(entry.task)
|
||||
.then(entry.resolve, entry.reject)
|
||||
.then(() => {
|
||||
this.active -= 1;
|
||||
this._drain();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildQuery(query) {
|
||||
if (!query) return "";
|
||||
const parts = [];
|
||||
for (const key of Object.keys(query)) {
|
||||
const value = query[key];
|
||||
if (value === null || value === undefined || value === "") continue;
|
||||
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
|
||||
}
|
||||
return parts.length ? `?${parts.join("&")}` : "";
|
||||
}
|
||||
|
||||
class GiteaClient {
|
||||
/**
|
||||
* @param {String} baseUrl Instance root, without a trailing slash.
|
||||
* @param {Function} tokenProvider Returns the token string, or null.
|
||||
*/
|
||||
constructor(baseUrl, tokenProvider) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.tokenProvider = tokenProvider;
|
||||
this.limiter = new Limiter(MAX_CONCURRENT);
|
||||
}
|
||||
|
||||
get apiRoot() {
|
||||
return `${this.baseUrl}/api/v1`;
|
||||
}
|
||||
|
||||
get token() {
|
||||
try {
|
||||
return this.tokenProvider(this.baseUrl);
|
||||
} catch (error) {
|
||||
log.error("token lookup failed", String(error));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
headers(extra) {
|
||||
const headers = Object.assign({ Accept: "application/json" }, extra || {});
|
||||
const token = this.token;
|
||||
if (token) headers["Authorization"] = `token ${token}`;
|
||||
return headers;
|
||||
}
|
||||
|
||||
/** Absolute URLs (artifact redirects) pass through untouched. */
|
||||
resolve(path) {
|
||||
if (/^https?:\/\//i.test(path)) return path;
|
||||
return `${this.apiRoot}${path.startsWith("/") ? path : "/" + path}`;
|
||||
}
|
||||
|
||||
async request(method, path, options = {}) {
|
||||
const url = this.resolve(path) + buildQuery(options.query);
|
||||
const init = { method: method, headers: this.headers(options.headers) };
|
||||
|
||||
if (options.body !== undefined && options.body !== null) {
|
||||
init.body = JSON.stringify(options.body);
|
||||
init.headers["Content-Type"] = "application/json";
|
||||
}
|
||||
|
||||
log.debug(method, url);
|
||||
|
||||
const response = await this.limiter.run(() => fetch(url, init));
|
||||
|
||||
if (!response.ok) {
|
||||
let detail = "";
|
||||
try {
|
||||
detail = await response.text();
|
||||
} catch (error) {
|
||||
detail = "";
|
||||
}
|
||||
throw new GiteaError(
|
||||
describeFailure(method, path, response.status, detail),
|
||||
response.status,
|
||||
detail,
|
||||
);
|
||||
}
|
||||
|
||||
if (options.responseType === "text") return await response.text();
|
||||
if (options.responseType === "binary") return await response.arrayBuffer();
|
||||
if (options.responseType === "response") return response;
|
||||
if (response.status === 204) return null;
|
||||
|
||||
const text = await response.text();
|
||||
if (!text) return null;
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch (error) {
|
||||
throw new GiteaError(`Unexpected response from ${url}`, response.status, text);
|
||||
}
|
||||
}
|
||||
|
||||
get(path, options) {
|
||||
return this.request("GET", path, options);
|
||||
}
|
||||
|
||||
post(path, body, options) {
|
||||
return this.request("POST", path, Object.assign({ body: body }, options));
|
||||
}
|
||||
|
||||
put(path, body, options) {
|
||||
return this.request("PUT", path, Object.assign({ body: body }, options));
|
||||
}
|
||||
|
||||
patch(path, body, options) {
|
||||
return this.request("PATCH", path, Object.assign({ body: body }, options));
|
||||
}
|
||||
|
||||
delete(path, options) {
|
||||
return this.request("DELETE", path, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks paged list endpoints until `limit` items are collected or the server
|
||||
* returns a short page.
|
||||
*/
|
||||
async paginate(path, options = {}) {
|
||||
const limit = options.limit || PAGE_SIZE;
|
||||
const pageSize = Math.min(limit, PAGE_SIZE);
|
||||
const collected = [];
|
||||
|
||||
for (let page = 1; collected.length < limit; page += 1) {
|
||||
const query = Object.assign({}, options.query, { page: page, limit: pageSize });
|
||||
const body = await this.get(path, { query: query });
|
||||
const items = options.pick ? options.pick(body) : body;
|
||||
if (!Array.isArray(items) || !items.length) break;
|
||||
collected.push(...items);
|
||||
if (items.length < pageSize) break;
|
||||
}
|
||||
|
||||
return collected.slice(0, limit);
|
||||
}
|
||||
}
|
||||
|
||||
function describeFailure(method, path, status, detail) {
|
||||
let message = "";
|
||||
try {
|
||||
const parsed = JSON.parse(detail);
|
||||
message = parsed.message || parsed.error || "";
|
||||
} catch (error) {
|
||||
message = (detail || "").slice(0, 200);
|
||||
}
|
||||
|
||||
if (status === 401) return "Gitea rejected the token (401). Set a valid token.";
|
||||
if (status === 403) {
|
||||
return `Gitea denied the request (403). The token is missing a required scope. ${message}`.trim();
|
||||
}
|
||||
if (status === 404) return `Not found: ${method} ${path}. ${message}`.trim();
|
||||
return `Gitea request failed (${status}): ${method} ${path}. ${message}`.trim();
|
||||
}
|
||||
|
||||
exports.GiteaClient = GiteaClient;
|
||||
exports.GiteaError = GiteaError;
|
||||
exports.Limiter = Limiter;
|
||||
@@ -0,0 +1,56 @@
|
||||
//
|
||||
// Token storage. Tokens live in the macOS Keychain, one entry per instance,
|
||||
// keyed by the instance's base URL. Reads are memoised because the sidebar
|
||||
// consults them on every render and each miss is a synchronous Keychain call.
|
||||
//
|
||||
|
||||
const SERVICE = "unsupervised.giteanova";
|
||||
const log = require("../util/log.js");
|
||||
|
||||
const cache = new Map();
|
||||
|
||||
function getToken(baseUrl) {
|
||||
if (!baseUrl) return null;
|
||||
if (cache.has(baseUrl)) return cache.get(baseUrl);
|
||||
|
||||
let token = null;
|
||||
try {
|
||||
token = nova.credentials.getPassword(SERVICE, baseUrl);
|
||||
} catch (error) {
|
||||
log.error("keychain read failed", String(error));
|
||||
}
|
||||
cache.set(baseUrl, token);
|
||||
return token;
|
||||
}
|
||||
|
||||
function setToken(baseUrl, token) {
|
||||
nova.credentials.setPassword(SERVICE, baseUrl, token);
|
||||
cache.set(baseUrl, token);
|
||||
}
|
||||
|
||||
function removeToken(baseUrl) {
|
||||
try {
|
||||
nova.credentials.removePassword(SERVICE, baseUrl);
|
||||
} catch (error) {
|
||||
log.debug("keychain delete failed", String(error));
|
||||
}
|
||||
cache.delete(baseUrl);
|
||||
}
|
||||
|
||||
function hasToken(baseUrl) {
|
||||
const token = getToken(baseUrl);
|
||||
return Boolean(token && token.length);
|
||||
}
|
||||
|
||||
/** Forgets memoised tokens, so the next read goes back to the Keychain. */
|
||||
function invalidate(baseUrl) {
|
||||
if (baseUrl) cache.delete(baseUrl);
|
||||
else cache.clear();
|
||||
}
|
||||
|
||||
exports.SERVICE = SERVICE;
|
||||
exports.getToken = getToken;
|
||||
exports.setToken = setToken;
|
||||
exports.removeToken = removeToken;
|
||||
exports.hasToken = hasToken;
|
||||
exports.invalidate = invalidate;
|
||||
@@ -0,0 +1,141 @@
|
||||
//
|
||||
// Repository discovery. In workspace mode the open folder's git remotes decide
|
||||
// which repositories appear; in allAccessible mode every repository the token
|
||||
// can reach is listed.
|
||||
//
|
||||
|
||||
const config = require("../util/config.js");
|
||||
const credentials = require("./credentials.js");
|
||||
const git = require("../util/git.js");
|
||||
const log = require("../util/log.js");
|
||||
const remotes = require("./remotes.js");
|
||||
|
||||
/** Stable identity for a repository across refreshes. */
|
||||
function keyFor(baseUrl, owner, name) {
|
||||
return `${baseUrl}#${owner}/${name}`;
|
||||
}
|
||||
|
||||
function makeRepo({ baseUrl, owner, name, dir = null, remoteName = null, remoteUrl = null }) {
|
||||
return {
|
||||
key: keyFor(baseUrl, owner, name),
|
||||
baseUrl: baseUrl,
|
||||
owner: owner,
|
||||
name: name,
|
||||
fullName: `${owner}/${name}`,
|
||||
dir: dir,
|
||||
remoteName: remoteName,
|
||||
remoteUrl: remoteUrl,
|
||||
htmlUrl: `${baseUrl}/${owner}/${name}`,
|
||||
branch: null,
|
||||
headSha: null,
|
||||
};
|
||||
}
|
||||
|
||||
async function discoverFromWorkspace(router) {
|
||||
const root = nova.workspace.path;
|
||||
if (!root) return [];
|
||||
|
||||
const dirs = await git.discoverRepositories(root);
|
||||
const found = new Map();
|
||||
|
||||
for (const dir of dirs) {
|
||||
const list = await git.remotes(dir);
|
||||
if (!list.length) continue;
|
||||
|
||||
// Prefer origin, but consider every remote so forks still resolve.
|
||||
const ordered = list.slice().sort((a, b) => {
|
||||
if (a.name === b.name) return 0;
|
||||
if (a.name === "origin") return -1;
|
||||
if (b.name === "origin") return 1;
|
||||
return 0;
|
||||
});
|
||||
|
||||
for (const remote of ordered) {
|
||||
const parsed = remotes.parse(remote.url);
|
||||
if (!parsed) continue;
|
||||
|
||||
const baseUrl = router.baseUrlForHost(parsed.host);
|
||||
if (!baseUrl) {
|
||||
log.debug(`no configured instance for host ${parsed.host} (${remote.url})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const repo = makeRepo({
|
||||
baseUrl: baseUrl,
|
||||
owner: parsed.owner,
|
||||
name: parsed.name,
|
||||
dir: dir,
|
||||
remoteName: remote.name,
|
||||
remoteUrl: remote.url,
|
||||
});
|
||||
|
||||
if (!found.has(repo.key)) {
|
||||
repo.branch = await git.currentBranch(dir);
|
||||
repo.headSha = await git.headSha(dir);
|
||||
found.set(repo.key, repo);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return [...found.values()];
|
||||
}
|
||||
|
||||
async function discoverFromApi(router) {
|
||||
const found = [];
|
||||
|
||||
for (const baseUrl of router.baseUrls) {
|
||||
if (!credentials.hasToken(baseUrl)) continue;
|
||||
const api = router.apiFor(baseUrl);
|
||||
try {
|
||||
const list = await api.accessibleRepositories(100);
|
||||
for (const entry of list) {
|
||||
const owner = (entry.owner && entry.owner.login) || entry.full_name.split("/")[0];
|
||||
const name = entry.name;
|
||||
found.push(
|
||||
Object.assign(makeRepo({ baseUrl: baseUrl, owner: owner, name: name }), {
|
||||
htmlUrl: entry.html_url || `${baseUrl}/${owner}/${name}`,
|
||||
branch: entry.default_branch || null,
|
||||
}),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
log.error(`repository discovery failed for ${baseUrl}:`, String(error));
|
||||
}
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discovers repositories for the configured mode. Workspace mode additionally
|
||||
* merges in local checkouts so allAccessible never loses the local directory
|
||||
* needed for checkout and log-saving.
|
||||
*/
|
||||
async function discover(router) {
|
||||
const mode = config.discoveryMode();
|
||||
const workspaceRepos = await discoverFromWorkspace(router);
|
||||
|
||||
if (mode !== "allAccessible") return workspaceRepos;
|
||||
|
||||
const byKey = new Map();
|
||||
for (const repo of await discoverFromApi(router)) byKey.set(repo.key, repo);
|
||||
for (const repo of workspaceRepos) {
|
||||
const existing = byKey.get(repo.key);
|
||||
if (existing) {
|
||||
existing.dir = repo.dir;
|
||||
existing.remoteName = repo.remoteName;
|
||||
existing.remoteUrl = repo.remoteUrl;
|
||||
existing.branch = repo.branch;
|
||||
existing.headSha = repo.headSha;
|
||||
} else {
|
||||
byKey.set(repo.key, repo);
|
||||
}
|
||||
}
|
||||
|
||||
return [...byKey.values()].sort((a, b) => a.fullName.localeCompare(b.fullName));
|
||||
}
|
||||
|
||||
exports.discover = discover;
|
||||
exports.makeRepo = makeRepo;
|
||||
exports.keyFor = keyFor;
|
||||
@@ -0,0 +1,68 @@
|
||||
//
|
||||
// Git remote URL parsing. Covers the four shapes Gitea hands out: HTTPS, SCP
|
||||
// style SSH, ssh:// URLs, and git:// URLs.
|
||||
//
|
||||
|
||||
function stripCredentials(host) {
|
||||
const at = host.lastIndexOf("@");
|
||||
return at === -1 ? host : host.slice(at + 1);
|
||||
}
|
||||
|
||||
function splitPath(path) {
|
||||
const parts = path
|
||||
.replace(/^\/+/, "")
|
||||
.replace(/\.git$/i, "")
|
||||
.replace(/\/+$/, "")
|
||||
.split("/")
|
||||
.filter(Boolean);
|
||||
|
||||
if (parts.length < 2) return null;
|
||||
// Sub-path installs ("https://example.com/gitea/owner/repo") still end with
|
||||
// owner/repo, so take the last two components.
|
||||
return { owner: parts[parts.length - 2], name: parts[parts.length - 1] };
|
||||
}
|
||||
|
||||
/** Parses a remote URL into { host, port, owner, name }, or null. */
|
||||
function parse(url) {
|
||||
if (!url) return null;
|
||||
const trimmed = String(url).trim();
|
||||
|
||||
let match = trimmed.match(/^[a-z][a-z0-9+.-]*:\/\/([^/]+)(\/.*)$/i);
|
||||
if (match) {
|
||||
let authority = stripCredentials(match[1]);
|
||||
let port = null;
|
||||
const portMatch = authority.match(/^(.+):(\d+)$/);
|
||||
if (portMatch) {
|
||||
authority = portMatch[1];
|
||||
port = Number(portMatch[2]);
|
||||
}
|
||||
const path = splitPath(match[2]);
|
||||
if (!path) return null;
|
||||
return { host: authority.toLowerCase(), port: port, owner: path.owner, name: path.name };
|
||||
}
|
||||
|
||||
// SCP-like: git@host:owner/repo.git
|
||||
match = trimmed.match(/^([^/@]+@)?([^/:]+):(.+)$/);
|
||||
if (match) {
|
||||
const path = splitPath(match[3]);
|
||||
if (!path) return null;
|
||||
return {
|
||||
host: match[2].toLowerCase(),
|
||||
port: null,
|
||||
owner: path.owner,
|
||||
name: path.name,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The host of an instance base URL, for matching against a remote's host. */
|
||||
function hostOf(baseUrl) {
|
||||
const match = String(baseUrl || "").match(/^[a-z][a-z0-9+.-]*:\/\/([^/]+)/i);
|
||||
if (!match) return null;
|
||||
return stripCredentials(match[1]).replace(/:\d+$/, "").toLowerCase();
|
||||
}
|
||||
|
||||
exports.parse = parse;
|
||||
exports.hostOf = hostOf;
|
||||
@@ -0,0 +1,61 @@
|
||||
//
|
||||
// Instance routing. Repositories are matched to a configured Gitea instance by
|
||||
// their git remote's host; anything unmatched falls back to the default one.
|
||||
//
|
||||
|
||||
const config = require("../util/config.js");
|
||||
const credentials = require("./credentials.js");
|
||||
const remotes = require("./remotes.js");
|
||||
const { GiteaClient } = require("./client.js");
|
||||
const { GiteaApi } = require("./api.js");
|
||||
|
||||
class InstanceRouter {
|
||||
constructor() {
|
||||
this.apis = new Map();
|
||||
}
|
||||
|
||||
/** Base URLs of every configured instance, default first. */
|
||||
get baseUrls() {
|
||||
return config.instances();
|
||||
}
|
||||
|
||||
apiFor(baseUrl) {
|
||||
const normalized = config.normalizeBaseUrl(baseUrl);
|
||||
if (!normalized) return null;
|
||||
|
||||
let api = this.apis.get(normalized);
|
||||
if (!api) {
|
||||
api = new GiteaApi(new GiteaClient(normalized, credentials.getToken));
|
||||
this.apis.set(normalized, api);
|
||||
}
|
||||
return api;
|
||||
}
|
||||
|
||||
get defaultApi() {
|
||||
const urls = this.baseUrls;
|
||||
return urls.length ? this.apiFor(urls[0]) : null;
|
||||
}
|
||||
|
||||
/** The instance whose host matches `host`, or null when none does. */
|
||||
baseUrlForHost(host) {
|
||||
if (!host) return null;
|
||||
const target = host.toLowerCase();
|
||||
for (const baseUrl of this.baseUrls) {
|
||||
if (remotes.hostOf(baseUrl) === target) return baseUrl;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
apiForHost(host) {
|
||||
const baseUrl = this.baseUrlForHost(host);
|
||||
return baseUrl ? this.apiFor(baseUrl) : null;
|
||||
}
|
||||
|
||||
/** Drops cached clients and tokens so the next call re-reads preferences. */
|
||||
invalidate() {
|
||||
this.apis.clear();
|
||||
credentials.invalidate();
|
||||
}
|
||||
}
|
||||
|
||||
exports.InstanceRouter = InstanceRouter;
|
||||
Reference in New Issue
Block a user