diff --git a/CLAUDE.md b/CLAUDE.md
index 8b9f94e..050cbe4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -48,6 +48,21 @@ README doesn't: conventions, environment and pitfalls.
with more of its pads and track pieces; even = stay), and the 3D view
glides to the Top or Bottom preset around it (`Board3D.focusOn(box, side)`,
`onView` presses the preset button). Clicks inside a view never move it.
+- **Forges** (`src/forge/`): every GitHub request (REST, GraphQL, raw files,
+ search) and github.com link is in `src/forge/github.js`; the rest of the app
+ talks to a forge object only (`forge()` / `forgeInHash()` / `parseRepoSpec()`
+ from `src/forge/index.js`, whose JSDoc typedefs are the interface: `Forge`,
+ `Source`, `RepoInfo`, `PullRequest`, `ChangedFile`, `Comparison`,
+ `SearchItem`, `ReviewThreads`) and gets forge-neutral shapes back, never
+ GitHub JSON. Forge sources carry `source.forge` (app code tests that, not
+ `kind === "github"`); page hashes use `forge.hashKey` (`gh=`); review
+ stores and diff specs carry `forge` (an id, GitHub by default). A new forge
+ = a new adapter added to `FORGES` (`tests/review.js` checks each one has
+ every member). Not forge-neutral yet: tokens and sign-in (settings `token`,
+ the GitHub App device flow in tauri.js, which uses `github` directly), the
+ Rust git commands (github.com URLs in git.rs/git_http.rs, `git_link_github`)
+ and most UI wording ("GitHub"). No DOM or Tauri in `src/forge/`: it runs
+ under gjs.
- `src/desktop/` holds the Tauri integration; it's a no-op when
`window.__TAURI__` is missing (`isDesktop`), which is what lets the pages run
in a plain headless browser for tests.
@@ -174,10 +189,10 @@ README doesn't: conventions, environment and pitfalls.
netclasses: a missing field inherits from Default in KiCad 9+, netclass
patterns and assignments) and `.kicad_dru` (`#` comments, several top-level
rules). Everything else in a `.kicad_pro` is ignored. `RULE_FILES`
- (sources.js) files are fetched by the diff page, shown as a table
+ (project.js) files are fetched by the diff page, shown as a table
(`#rules-view`, `.rules-mode`) and dropped when unchanged
(`dropUnchangedRules`). The inbox badge counts the same files
- (`src/desktop/pr-files.js`): a modified `.kicad_pro` is read at the PR head
+ (`src/desktop/pr-files.js`, on `forge.pullFiles` ChangedFiles): a modified `.kicad_pro` is read at the PR head
and its base rebuilt from the PR's `patch` (`textBeforePatch`, sources.js),
so no extra API request for the base; unverifiable files count.
- Changes may carry `boxesBefore`/`boxesAfter` (per-side marks) and `rows`
@@ -197,8 +212,9 @@ README doesn't: conventions, environment and pitfalls.
- The user's design: issues pinned like review comments, outside PRs, listed
in a home view; only issues labelled `kivi` (`ISSUE_LABEL`, the user's
choice over listing every issue).
-- `src/issues.js` `IssueComments` extends `ReviewComments` (same request and
- error code) and turns issues into the same thread shape: `rootId` = issue
+- `GitHubIssues` extends `GitHubReviews` (forge/github.js; same request and
+ error code) and turns issues into the same thread shape (`issueThread`,
+ review.js; `ISSUE_LABEL` is there too): `rootId` = issue
number (so `thread=12` is issue #12), resolved = closed, the body is the
first comment (never deletable). The marker carries `file` (repository path)
and `commit`. Signed in: one GraphQL query (issues + comments); signed out:
@@ -213,7 +229,7 @@ README doesn't: conventions, environment and pitfalls.
- In PR mode the store holds both (`api` = review comments, `issueApi` =
issues; `apiFor(t)`, `wordsFor(t)`), keys keep them apart (`t.key`: comment
id, or "i12"), only review threads are numbered 1…n, issue pins are green
- (`.cm-pin.issue`), `openCounts` skips issues. `closingIssues()` (review.js:
+ (`.cm-pin.issue`), `openCounts` skips issues. `closingIssues()` (forge/github.js:
GraphQL `closingIssuesReferences` signed in, else `closingNumbers` of the
description) marks the ones the PR closes; **Close with this PR**
(`addClosingIssue`) appends "Fixes #N" to the description, re-read first. An
@@ -258,7 +274,7 @@ README doesn't: conventions, environment and pitfalls.
on a blocking thread.
- Branch menu `#branch-menu` (`src/app/branch-menu.js`, shared, the user's
design): the same button and branch list for GitHub projects (main.js
- `mountGitHubBranches`: `/branches` API, switching rewrites the URL's `gh=`
+ `mountForgeBranches`: `forge.branches`, switching rewrites the URL's `gh=`
ref so `restoreFromHash` reopens the project, same tab) and local copies
(git.js `mountGitMenu`: `git_branches` after a best-effort fetch,
`git_switch_branch` = safe checkout like `git switch`, plus New branch…,
@@ -268,12 +284,12 @@ README doesn't: conventions, environment and pitfalls.
nothing to do); a folder without a GitHub remote gets no Push (no sign-in
needed; the user's request), and before its first
commit `git_info.branch` is the unborn branch and a new branch replaces it). `data-kind` tells which side owns it: main.js
- removes only a "github" one, desktop.js mounts the "local" one after a folder
+ removes only a "forge" one, desktop.js mounts the "local" one after a folder
opens and on live reload/focus. The left of the bar shows the repository
(GitHub) or folder (local), no longer the ref.
- History menu `#history-menu` (`src/app/history-menu.js`, shared, next to
the branch menu; `data-kind` like it): the branch's commits, 50 per
- **Show more**. GitHub (main.js `mountGitHubHistory`, hidden in PR mode):
+ **Show more**. GitHub (main.js `mountForgeHistory`, `forge.commits`, hidden in PR mode):
`/commits?sha=[` (one API request per page per page load); picking one
sets `commit=]` in the URL, which `openGitHub` turns into the source's
`sha`/`commit` while `ref` (and the branch menu) keep the branch. Local
@@ -283,7 +299,7 @@ README doesn't: conventions, environment and pitfalls.
repository's root). While a `GitRevSource` is open, live reload is skipped
and Open in KiCad is greyed out; switching branch returns to the working files.
- Visual diff button `#visual-diff` (index.html, set by `setDiffButton` in
- `src/app/diff-button.js` from main.js `setGitHubDiff` or git.js
+ `src/app/diff-button.js` from main.js `setForgeDiff` or git.js
`mountGitMenu`; it replaced the branch menu's "Visual diff of changes", the
user's request). The side pickers, in the Before/After pane labels and the
Overlay one (`.pick-slot`, the user's design; the bar shows only the
@@ -296,7 +312,7 @@ README doesn't: conventions, environment and pitfalls.
takes a base branch (from the merge base) or revision (that commit itself,
`base_tip`) and an optional head (`rev_tip`: local branch, GitHub's, then any
revision; none = working files); `git_log` takes `rev`. GitHub
- (`resolveComparison`): no base = default branch, base = head → that commit
+ (`forge.compare`, `compare` in forge/github.js): no base = default branch, base = head → that commit
vs its parent, a full-SHA base that isn't the merge base → `treeDiff` (two
recursive trees; refuses truncated ones).
- `src/desktop/git.js`: card menu actions (projects.js), the local branch
@@ -458,7 +474,7 @@ python3 tools/fetch_demos.py # KiCad demo files → tests/kicad-
gjs -m tests/run.js # parse+render all KiCad demos
gjs -m tests/diff.js
gjs -m tests/nets.js
-gjs -m tests/review.js # GitHub API layer, mocked
+gjs -m tests/review.js # GitHub adapter and forge interface, mocked
gjs -m tests/models.js # 3D model path resolution order
cargo test --manifest-path src-tauri/Cargo.toml --lib # Rust: model folders, git (needs dist/web)
tests/smoke.sh # pages load cleanly, viewer opens pic_programmer (~15 s)
diff --git a/README.md b/README.md
index 201206c..cd41083 100644
--- a/README.md
+++ b/README.md
@@ -288,10 +288,13 @@ src/geom.js matrices, arcs, bounding boxes
src/text.js text layout (KiCad metrics, markup, escapes)
src/drawing-sheet.js .kicad_wks parser/renderer, built-in default sheet
src/project.js project discovery, hierarchy walk, page numbering
-src/sources.js GitHub (API, PR/commit comparison), 3D model path resolution
+src/forge/ code hosts: the forge interface (index.js) and the GitHub
+ adapter (github.js: every API request, comparisons, review
+ comments, issues, search, github.com links)
+src/sources.js text before a patch, 3D model path resolution
src/diff/ semantic schematic, net, board and design rule diffs, comment anchors
-src/review.js review comments on GitHub (threads, replies, resolve)
-src/issues.js change requests as GitHub issues (same threads, labelled kivi)
+src/review.js comment markers and the thread shape (review comments and
+ change requests), the same on every forge
src/sch/ schematic model, renderer, themes
src/pcb/ board model, renderer, shapes, hit testing,
outline extraction, face textures, three.js scene,
diff --git a/src/app/branch-menu.js b/src/app/branch-menu.js
index fdbe632..5e4872d 100644
--- a/src/app/branch-menu.js
+++ b/src/app/branch-menu.js
@@ -16,7 +16,7 @@ export const BRANCH_ICON = `) a local git copy's working files with
// the point where its branch left main.
-import { DIFFABLE, RULE_FILES, GitHubSource, resolveComparison } from "../sources.js";
+import { DIFFABLE, RULE_FILES } from "../project.js";
+import { forge, forgeInHash } from "../forge/index.js";
import { parseSchematic } from "../sch/model.js";
import { renderSchematic } from "../sch/render.js";
import { parsePcb } from "../pcb/model.js";
@@ -69,7 +70,7 @@ class DiffApp {
this.pendingLocal = null;
}
- /** A local copy (its working files, or `spec.head`) against main or `spec.base`, in the shape resolveComparison returns. */
+ /** A local copy (its working files, or `spec.head`) against main or `spec.base`, in the shape a forge's compare() returns. */
async localComparison(spec) {
if (!this.localGit) throw new Error("Local changes can only be shown in the KiVi desktop app");
const lc = await this.localGit.changes(spec.local, spec.base, spec.head);
@@ -119,13 +120,14 @@ class DiffApp {
specFromHash(p) {
if (p.get("local")) return { local: p.get("local"), base: p.get("base"), head: p.get("head") };
- const gh = p.get("gh");
- if (!gh) return null;
- const [owner, repo] = gh.split("/");
- if (p.get("pr")) return { owner, repo, pr: Number(p.get("pr")) };
- if (p.get("commit")) return { owner, repo, commit: p.get("commit") };
- // Without a base: the default branch (resolveComparison).
- if (p.get("head")) return { owner, repo, base: p.get("base"), head: p.get("head") };
+ const at = forgeInHash(p);
+ if (!at) return null;
+ const [owner, repo] = at.value.split("/");
+ const f = at.forge.id;
+ if (p.get("pr")) return { forge: f, owner, repo, pr: Number(p.get("pr")) };
+ if (p.get("commit")) return { forge: f, owner, repo, commit: p.get("commit") };
+ // Without a base: the default branch (the forge's compare).
+ if (p.get("head")) return { forge: f, owner, repo, base: p.get("base"), head: p.get("head") };
return null;
}
@@ -137,7 +139,7 @@ class DiffApp {
if (s.base) p.set("base", s.base);
if (s.head) p.set("head", s.head);
} else {
- p.set("gh", `${s.owner}/${s.repo}`);
+ p.set(forge(s.forge).hashKey, `${s.owner}/${s.repo}`);
if (s.pr) p.set("pr", String(s.pr));
else if (s.commit) p.set("commit", s.commit);
else {
@@ -160,8 +162,8 @@ class DiffApp {
this.cache.clear();
this.proCache = new Map(); // the sides may be other commits now
try {
- this.busy(spec.local ? "Reading local changes…" : "Reading changes from GitHub…");
- const cmp = spec.local ? await this.localComparison(spec) : await resolveComparison(spec, settings().token);
+ this.busy(spec.local ? "Reading local changes…" : `Reading changes from ${forge(spec.forge).name}…`);
+ const cmp = spec.local ? await this.localComparison(spec) : await forge(spec.forge).compare(spec, settings().token);
this.cmp = cmp;
$("#diff-bar").hidden = false;
$("#diff-main").hidden = false;
@@ -193,7 +195,7 @@ class DiffApp {
cmp.files.sort((a, b) => order(a.path) - order(b.path) || a.path.localeCompare(b.path));
this.renderFileList();
if (spec.pr) {
- this.store.open({ owner: spec.owner, repo: spec.repo, number: spec.pr, headSha: cmp.head.sha });
+ this.store.open({ forge: spec.forge, owner: spec.owner, repo: spec.repo, number: spec.pr, headSha: cmp.head.sha });
if (focus) this.review.setFocus(focus);
} else this.store.close();
const first = cmp.files.find((f) => f.path === initialFile) ?? cmp.files[0];
@@ -235,27 +237,16 @@ class DiffApp {
for (const slot of document.querySelectorAll(".pick-slot")) slot.replaceChildren();
if (spec.pr) return;
const local = !!spec.local;
- const gh = local ? null : spec;
+ const f = local ? null : forge(spec.forge);
// Both pickers list the same branches, read once per comparison.
let branchList = null;
const branches = () =>
(branchList ??= local
? this.localGit.branches(cmp.root).then((bs) => bs.map((b) => ({ name: b.name, note: b.current ? "checked out" : b.remote ? "on GitHub" : "" })))
- : (async () => {
- const all = [];
- for (let page = 1; page <= 5; page++) {
- const batch = await GitHubSource.api(`/repos/${gh.owner}/${gh.repo}/branches?per_page=100&page=${page}`, settings().token);
- all.push(...batch);
- if (batch.length < 100) break;
- }
- return all.map((b) => ({ name: b.name }));
- })());
+ : f.branches(spec.owner, spec.repo, settings().token));
const commits = local
? (branch, offset, count) => this.localGit.commits(cmp.root, branch, offset, count)
- : async (branch, offset, count) => {
- const batch = await GitHubSource.api(`/repos/${gh.owner}/${gh.repo}/commits?sha=${encodeURIComponent(branch)}&per_page=${count}&page=${Math.floor(offset / count) + 1}`, settings().token);
- return batch.map((c) => ({ sha: c.sha, summary: c.commit.message.split("\n")[0], author: c.commit.author?.name ?? c.author?.login ?? "", time: Date.parse(c.commit.author?.date) / 1000 }));
- };
+ : (branch, offset, count) => f.commits(spec.owner, spec.repo, branch, offset, count, settings().token);
const sha = /^[0-9a-f]{7,40}\^?$/i;
// What each side is now: the URL's choice, else what it was resolved to
// (a local copy's default base is e.g. origin/main, listed as main).
@@ -263,7 +254,7 @@ class DiffApp {
const headValue = local ? (spec.head ?? "") : (spec.head ?? cmp.head.sha);
const headBranch = local ? (spec.head && !sha.test(spec.head) ? spec.head : cmp.branch) : !sha.test(headValue) ? headValue : null;
const pick = (side) => async (value) => {
- const next = local ? { local: spec.local, base: spec.base, head: spec.head } : { owner: gh.owner, repo: gh.repo, base: baseValue, head: headValue };
+ const next = local ? { local: spec.local, base: spec.base, head: spec.head } : { forge: spec.forge, owner: spec.owner, repo: spec.repo, base: baseValue, head: headValue };
next[side] = value || null;
await this.open(next, this.file?.path);
this.writeHash();
@@ -323,7 +314,7 @@ class DiffApp {
const ref = this.cmp[side];
if (ref.src) return ref.src.readText(path); // a local copy
if (!ref.sha) return null;
- const src = new GitHubSource({ owner: ref.owner, repo: ref.repo, ref: ref.sha, sha: ref.sha, token: settings().token });
+ const src = forge(this.spec.forge).source({ owner: ref.owner, repo: ref.repo, ref: ref.sha, sha: ref.sha, token: settings().token });
return src.readText(path);
}
@@ -342,7 +333,7 @@ class DiffApp {
this.proCache.set(
key,
(async () => {
- const src = ref.src ?? new GitHubSource({ owner: ref.owner, repo: ref.repo, ref: ref.sha, sha: ref.sha, path: dir, token: settings().token });
+ const src = ref.src ?? forge(this.spec.forge).source({ owner: ref.owner, repo: ref.repo, ref: ref.sha, sha: ref.sha, path: dir, token: settings().token });
const pro = (await src.list()).find((p) => p.endsWith(".kicad_pro") && dirname(p) === dir) ?? null;
if (!pro) return { pro, vars: {} };
return { pro, vars: JSON.parse(await src.readText(pro)).text_variables ?? {} };
@@ -420,7 +411,7 @@ class DiffApp {
// A local copy opens its working files (the folder, with the project of this file), or the compared commit.
const viewerHash = this.cmp.root
? new URLSearchParams({ folder: this.cmp.root, project: fl.path.replace(/\.kicad_(sch|pcb|dru)$/i, ".kicad_pro"), ...(this.cmp.head.sha && { commit: this.cmp.head.sha }) })
- : new URLSearchParams({ gh: `${this.cmp.head.owner}/${this.cmp.head.repo}@${this.cmp.head.sha}${dirname(fl.path) ? `:${dirname(fl.path)}` : ""}`, tab: res.kind === "sch" ? "sch" : "pcb", ...(res.kind !== "rules" && { file: fl.path }) });
+ : new URLSearchParams({ [forge(this.spec.forge).hashKey]: `${this.cmp.head.owner}/${this.cmp.head.repo}@${this.cmp.head.sha}${dirname(fl.path) ? `:${dirname(fl.path)}` : ""}`, tab: res.kind === "sch" ? "sch" : "pcb", ...(res.kind !== "rules" && { file: fl.path }) });
if (this.spec.pr) viewerHash.set("pr", `${this.spec.owner}/${this.spec.repo}#${this.spec.pr}`);
$("#open-viewer").href = `index.html#${viewerHash}`;
this.writeHash();
diff --git a/src/app/history-menu.js b/src/app/history-menu.js
index 8784e9f..80f6893 100644
--- a/src/app/history-menu.js
+++ b/src/app/history-menu.js
@@ -18,7 +18,7 @@ const PAGE = 50; // commits per "Show more"
/**
* Put the history menu in the project bar (replacing any earlier one), after the branch menu.
* @param {object} o
- * @param {string} o.kind "github" | "local", so each side removes only its own menu
+ * @param {string} o.kind "forge" | "local", so each side removes only its own menu
* @param {string|null} o.viewing the commit shown (full SHA), or null for the latest
* @param {string} o.latest the first item, e.g. "Latest on main" or "Working files"
* @param {string} [o.latestNote] a note after it (local: the changed files)
diff --git a/src/app/main.js b/src/app/main.js
index b0897a8..8934ed0 100644
--- a/src/app/main.js
+++ b/src/app/main.js
@@ -1,7 +1,8 @@
// KiVi application controller: sources, project loading, tabs, deep links.
import { findProjects, loadProject } from "../project.js";
-import { GitHubSource, parseGitHubSpec, makeModelResolver } from "../sources.js";
+import { makeModelResolver } from "../sources.js";
+import { forgeInHash } from "../forge/index.js";
import { DEFAULT_MODEL_BASE } from "../pcb/board3d.js";
/** 3D model sources from Settings (the account menu; older settings had a single library URL). */
@@ -23,7 +24,7 @@ class App {
this.tab = "sch";
this.pr = null; // pull request under review: comments in the schematic and PCB tabs
this.store = new ReviewStore(); // its review comments, or else the repository's issues
- this.localIssues = null; // {folder, owner, repo, prefix, commit}: a local copy's GitHub repository (desktop.js)
+ this.localIssues = null; // {folder, owner, repo, prefix, commit}: a local copy's forge repository (desktop.js)
this.sch = new SchematicTab(this);
this.pcb = new PcbTab(this);
this.bom = new BomTab(this);
@@ -49,13 +50,14 @@ class App {
$("#loading-text").textContent = msg || "";
}
- async openGitHub(spec, state = null) {
+ /** Open a forge repository from its hash spec ("owner/repo@ref:dir"). */
+ async openRemote(f, spec, state = null) {
try {
- this.busy("Connecting to GitHub…");
+ this.busy(`Connecting to ${f.name}…`);
// Reviewing a pull request: show its head commit and its review comments.
- const pr = state?.pr ? await this.resolvePr(state.pr, spec) : null;
+ const pr = state?.pr ? await this.resolvePr(f, state.pr, spec) : null;
if (pr) spec = pr.spec;
- const src = await GitHubSource.open(spec, settings().token);
+ const src = await f.open(spec, settings().token);
// An earlier commit from the history menu: read at that commit, still labelled with the branch.
if (!pr && /^[0-9a-f]{40}$/i.test(state?.commit ?? "")) src.sha = src.commit = state.commit;
this.pr = pr;
@@ -68,23 +70,23 @@ class App {
}
/** "owner/repo#12" (or "12" with the repository from `spec`) → head commit and spec to open. */
- async resolvePr(value, spec) {
- const gh = parseGitHubSpec(spec);
+ async resolvePr(f, value, spec) {
+ const at = f.parseSpec(spec);
const m = /^(?:([\w.-]+)\/([\w.-]+))?#?(\d+)$/.exec(String(value).trim());
- if (!m || !gh) return null;
- const owner = m[1] ?? gh.owner, repo = m[2] ?? gh.repo, number = Number(m[3]);
+ if (!m || !at) return null;
+ const owner = m[1] ?? at.owner, repo = m[2] ?? at.repo, number = Number(m[3]);
this.busy(`Reading pull request #${number}…`);
- const pr = await GitHubSource.api(`/repos/${owner}/${repo}/pulls/${number}`, settings().token);
- const head = pr.head.repo ?? { owner: { login: owner }, name: repo }; // fork deleted: the base repo still has the commits
- const path = gh.path ?? "";
+ const pr = await f.pullRequest(owner, repo, number, settings().token);
+ const path = at.path ?? "";
return {
+ forge: f.id,
owner, repo, number,
headSha: pr.head.sha,
- // Fork branches are shown as "owner:branch", like GitHub does.
- headRef: pr.head.repo && pr.head.repo.owner.login !== owner ? pr.head.label : pr.head.ref,
+ headRef: pr.head.label,
title: pr.title,
- url: pr.html_url,
- spec: `${head.owner.login}/${head.name}@${pr.head.sha}${path ? `:${path}` : ""}`,
+ url: pr.url,
+ // The head's repository: a fork's, or this one when the fork is gone.
+ spec: `${pr.head.owner}/${pr.head.repo}@${pr.head.sha}${path ? `:${path}` : ""}`,
};
}
@@ -109,7 +111,7 @@ class App {
*/
showIssues() {
const s = this.source;
- if (s?.kind === "github") this.store.openIssues({ owner: s.owner, repo: s.repo, prefix: "", commit: s.sha ?? s.commit ?? null });
+ if (s?.forge) this.store.openIssues({ forge: s.forge.id, owner: s.owner, repo: s.repo, prefix: "", commit: s.sha ?? s.commit ?? null });
else if (s && this.localIssues && s.path === this.localIssues.folder) this.store.openIssues(this.localIssues);
else this.store.close();
}
@@ -123,13 +125,13 @@ class App {
/** Branch (or short commit) being viewed, for the project bar; the full address goes in the tooltip. */
refLabel() {
const s = this.source;
- if (s.kind !== "github") return s.label;
+ if (!s.forge) return s.label;
if (this.pr?.headRef) return this.pr.headRef;
return /^[0-9a-f]{40}$/i.test(s.ref) ? s.ref.slice(0, 7) : s.ref;
}
async openSource(source, state = null) {
- if (source.kind !== "github" || (source.sha ?? source.ref) !== this.pr?.headSha) {
+ if (!source.forge || (source.sha ?? source.ref) !== this.pr?.headSha) {
this.pr = null;
this.showPr();
}
@@ -179,15 +181,15 @@ class App {
$("#proj-name").textContent = project.name;
// Where it comes from on the left (repository or folder); the branch is the menu on the right.
const srcLabel = $("#proj-source");
- srcLabel.textContent = this.source.kind === "github" ? this.source.repo : this.source.label;
+ srcLabel.textContent = this.source.forge ? this.source.repo : this.source.label;
srcLabel.title = this.source.label;
- if (this.source.kind === "github") {
- this.mountGitHubBranches(entry);
- this.mountGitHubHistory();
- this.setGitHubDiff();
+ if (this.source.forge) {
+ this.mountForgeBranches(entry);
+ this.mountForgeHistory();
+ this.setForgeDiff();
} else {
// a local copy's come from desktop.js
- for (const id of ["#branch-menu", "#history-menu"]) if ($(id)?.dataset.kind === "github") $(id).remove();
+ for (const id of ["#branch-menu", "#history-menu"]) if ($(id)?.dataset.kind === "forge") $(id).remove();
}
document.title = `${project.name} — KiVi`;
@@ -392,10 +394,10 @@ class App {
// ---- deep links ----
stateForHash() {
- if (!this.source || this.source.kind !== "github") return null;
+ if (!this.source?.forge) return null;
const s = this.source;
const p = new URLSearchParams();
- p.set("gh", `${s.owner}/${s.repo}@${s.ref}${s.dir ? `:${s.dir}` : ""}`);
+ p.set(s.forge.hashKey, `${s.owner}/${s.repo}@${s.ref}${s.dir ? `:${s.dir}` : ""}`);
if (s.commit) p.set("commit", s.commit);
if (this.entry) p.set("project", this.entry.pro ?? this.entry.sch ?? this.entry.pcb);
p.set("tab", this.tab);
@@ -418,54 +420,40 @@ class App {
setTimeout(() => (this._writingHash = false), 0);
}
- /** The branch menu of a GitHub project: the repository's branches; picking one reopens the project there. */
- mountGitHubBranches(entry) {
+ /** The branch menu of a forge project: the repository's branches; picking one reopens the project there. */
+ mountForgeBranches(entry) {
const s = this.source;
const project = entry.pro ?? entry.sch ?? entry.pcb;
const current = this.pr?.headRef ?? s.ref;
mountBranchMenu({
- kind: "github",
+ kind: "forge",
branch: this.refLabel(),
title: `${s.owner}/${s.repo} at ${this.refLabel()}`,
listBranches: async () => {
- const all = [];
- for (let page = 1; page <= 5; page++) {
- const batch = await GitHubSource.api(`/repos/${s.owner}/${s.repo}/branches?per_page=100&page=${page}`, settings().token);
- all.push(...batch);
- if (batch.length < 100) break;
- }
+ const all = await s.forge.branches(s.owner, s.repo, settings().token);
return all.map((b) => ({ name: b.name, current: b.name === current })).sort((a, b) => b.current - a.current || a.name.localeCompare(b.name));
},
// Through the URL, like a link: the viewer reopens the same project and tab on that branch.
switchTo: async (name) => {
- location.hash = new URLSearchParams({ gh: `${s.owner}/${s.repo}@${name}${s.dir ? `:${s.dir}` : ""}`, project, tab: this.tab }).toString();
+ location.hash = new URLSearchParams({ [s.forge.hashKey]: `${s.owner}/${s.repo}@${name}${s.dir ? `:${s.dir}` : ""}`, project, tab: this.tab }).toString();
},
});
}
/**
- * The history menu of a GitHub project: the branch's commits; picking one reopens
+ * The history menu of a forge project: the branch's commits; picking one reopens
* the project at that commit, through the URL (`commit=`, the branch stays in `gh=`).
* Not for a pull request, which shows its head commit with its review comments.
*/
- mountGitHubHistory() {
+ mountForgeHistory() {
if (this.pr) return $("#history-menu")?.remove();
const s = this.source;
mountHistoryMenu({
- kind: "github",
+ kind: "forge",
viewing: s.commit ?? null,
latest: `Latest on ${this.refLabel()}`,
branch: this.refLabel(),
- listCommits: async (offset, count) => {
- const page = Math.floor(offset / count) + 1;
- const batch = await GitHubSource.api(`/repos/${s.owner}/${s.repo}/commits?sha=${encodeURIComponent(s.ref)}&per_page=${count}&page=${page}`, settings().token);
- return batch.map((c) => ({
- sha: c.sha,
- summary: c.commit.message.split("\n")[0],
- author: c.commit.author?.name ?? c.author?.login ?? "",
- time: Date.parse(c.commit.author?.date ?? c.commit.committer?.date) / 1000,
- }));
- },
+ listCommits: (offset, count) => s.forge.commits(s.owner, s.repo, s.ref, offset, count, settings().token),
// The same project, tab, sheet and selection at the other commit.
show: async (sha) => {
const p = this.stateForHash();
@@ -477,25 +465,25 @@ class App {
}
/**
- * The Visual diff button of a GitHub project: the pull request, the commit
+ * The Visual diff button of a forge project: the pull request, the commit
* shown, or the branch against the default branch (the diff page then lets
* other branches and commits be picked).
*/
- setGitHubDiff() {
+ setForgeDiff() {
const s = this.source;
const at = this.pr ? { pr: String(this.pr.number) } : s.commit || /^[0-9a-f]{40}$/i.test(s.ref) ? { commit: s.commit ?? s.ref } : { head: s.ref };
const owner = this.pr?.owner ?? s.owner, repo = this.pr?.repo ?? s.repo; // a fork's PR is diffed in the base repository
setDiffButton({
- href: `diff.html#${new URLSearchParams({ gh: `${owner}/${repo}`, ...at })}`,
+ href: `diff.html#${new URLSearchParams({ [s.forge.hashKey]: `${owner}/${repo}`, ...at })}`,
title: this.pr ? `Visual diff of pull request #${this.pr.number}` : at.commit ? `Visual diff of commit ${at.commit.slice(0, 7)}` : `Visual diff of ${s.ref} against the default branch (its latest commit if it is the default); pick other branches or commits there`,
});
}
restoreFromHash() {
const p = new URLSearchParams(location.hash.slice(1));
- const gh = p.get("gh");
- if (!gh) return;
- this.openGitHub(gh, { project: p.get("project"), tab: p.get("tab"), page: p.get("page"), sel: p.get("sel"), net: p.get("net"), file: p.get("file"), pr: p.get("pr"), thread: p.get("thread"), commit: p.get("commit") });
+ const at = forgeInHash(p);
+ if (!at) return;
+ this.openRemote(at.forge, at.value, { project: p.get("project"), tab: p.get("tab"), page: p.get("page"), sel: p.get("sel"), net: p.get("net"), file: p.get("file"), pr: p.get("pr"), thread: p.get("thread"), commit: p.get("commit") });
}
}
diff --git a/src/app/review-ui.js b/src/app/review-ui.js
index 83018ec..9d3cb60 100644
--- a/src/app/review-ui.js
+++ b/src/app/review-ui.js
@@ -1,7 +1,7 @@
// Review comments on pull requests, in the visual diff and in the viewer's
// schematic and PCB tabs: comment pins on a canvas, a composer and thread
// popover, and the list of threads in a side panel. Outside a pull request the
-// same pins are GitHub issues (hardware change requests, ../issues.js).
+// same pins are forge issues (hardware change requests, see ../review.js).
//
// Threads live on GitHub (see ../review.js). A ReviewStore holds the threads
// of one pull request, or the issues of one repository; each canvas gets a
@@ -24,8 +24,8 @@
// host.zoomMin minimum zoom box (mm)
// host.writeHash() (optional)
-import { ReviewComments, anchorLabel, anchorKind, renderCommentText } from "../review.js";
-import { IssueComments, ISSUE_LABEL } from "../issues.js";
+import { ISSUE_LABEL, anchorLabel, anchorKind, renderCommentText } from "../review.js";
+import { forge } from "../forge/index.js";
import { trackPath, circlePath } from "../pcb/shapes.js";
import { f } from "../geom.js";
import { $, toast, settings, collapsible } from "./ui.js";
@@ -95,9 +95,10 @@ export class ReviewStore {
for (const fn of this.listeners) fn();
}
- /** @param {{owner: string, repo: string, number: number, headSha: string}} pr */
+ /** @param {{owner: string, repo: string, number: number, headSha: string, forge?: string}} pr `forge`: its id, GitHub by default */
async open(pr) {
const token = settings().token ?? null;
+ const f = forge(pr.forge);
this.pr = pr;
this.issues = null;
this.kind = "pr";
@@ -106,8 +107,8 @@ export class ReviewStore {
this.loadedAt = 0;
this.error = this.issueError = null;
this.changed = null;
- this.api = new ReviewComments({ owner: pr.owner, repo: pr.repo, pr: pr.number, token });
- this.issueApi = new IssueComments({ owner: pr.owner, repo: pr.repo, token });
+ this.api = f.reviews({ owner: pr.owner, repo: pr.repo, pr: pr.number, token });
+ this.issueApi = f.issues({ owner: pr.owner, repo: pr.repo, token });
this.emit();
// Only signed in (writing needs it anyway; spares the anonymous rate limit). Not
// known (or failed): new pins stay review comments and GitHub has the last word.
@@ -140,11 +141,12 @@ export class ReviewStore {
* the repository ("" at its root, "hw/" below it): threads carry paths
* relative to the folder, like the documents. `commit` is what new issues
* are made on. Opening the same repository again only updates the commit.
- * @param {{owner: string, repo: string, prefix?: string, commit?: string|null}} target
+ * @param {{owner: string, repo: string, prefix?: string, commit?: string|null, forge?: string}} target
*/
- async openIssues({ owner, repo, prefix = "", commit = null }) {
- const same = this.kind === "issues" && this.api && this.issues.owner === owner && this.issues.repo === repo && this.issues.prefix === prefix;
- this.issues = { owner, repo, prefix, commit };
+ async openIssues({ owner, repo, prefix = "", commit = null, forge: forgeId = undefined }) {
+ const f = forge(forgeId);
+ const same = this.kind === "issues" && this.api && this.issues.forge === f.id && this.issues.owner === owner && this.issues.repo === repo && this.issues.prefix === prefix;
+ this.issues = { forge: f.id, owner, repo, prefix, commit };
if (same) return;
this.pr = null;
this.changed = null;
@@ -153,7 +155,7 @@ export class ReviewStore {
this.closing = new Set();
this.loadedAt = 0;
this.error = this.issueError = null;
- this.api = this.issueApi = new IssueComments({ owner, repo, token: settings().token ?? null });
+ this.api = this.issueApi = f.issues({ owner, repo, token: settings().token ?? null });
this.emit();
await this.reload();
}
diff --git a/src/desktop/account.js b/src/desktop/account.js
index f632752..56221ba 100644
--- a/src/desktop/account.js
+++ b/src/desktop/account.js
@@ -11,7 +11,8 @@
// "Open in KiCad" uses its program, and the 3D view its path variables.
import { $, escapeHtml, settings, saveSettings, toast } from "../app/ui.js";
-import { GitHubSource, parseModelSource } from "../sources.js";
+import { parseModelSource } from "../sources.js";
+import { forge } from "../forge/index.js";
import { ICONS } from "./icons.js";
import { appInstallUrl, inspectKicad, pickFolder, signInWithGitHub, withoutGitHubToken } from "./tauri.js";
@@ -213,16 +214,16 @@ export function initHeader({ homeLinks = true, onAccountChange = () => location.
} else {
let me = null, error = null;
try {
- me = await GitHubSource.api("/user", token);
+ me = await forge().user(token);
} catch (e) {
error = e;
}
const access = me ? await appInstallUrl() : null;
el.innerHTML = me
? accountMenu(
- `${escapeHtml(me.login)} `,
- `${escapeHtml(me.login)} ${me.name ? `${escapeHtml(me.name)} ` : ""}
`,
- [[["person", "Your GitHub profile", null, me.html_url], ...(access ? [["key", "Repository access", null, access]] : []), settingsItem], [["signOut", "Sign out", "signout"]]],
+ `${escapeHtml(me.login)} `,
+ `${escapeHtml(me.login)} ${me.name ? `${escapeHtml(me.name)} ` : ""}
`,
+ [[["person", "Your GitHub profile", null, me.url], ...(access ? [["key", "Repository access", null, access]] : []), settingsItem], [["signOut", "Sign out", "signout"]]],
)
: accountMenu(
`signed out `,
diff --git a/src/desktop/add-project.js b/src/desktop/add-project.js
index 17aee64..5afb976 100644
--- a/src/desktop/add-project.js
+++ b/src/desktop/add-project.js
@@ -3,8 +3,8 @@
// repository, added to the watched repositories that the gallery scans).
// It replaced the address bar the pages used to have.
-import { settings, saveSettings } from "../app/ui.js";
-import { GitHubSource, parseGitHubSpec } from "../sources.js";
+import { escapeHtml, settings, saveSettings } from "../app/ui.js";
+import { forge } from "../forge/index.js";
import { dialog } from "./git.js";
import { ICONS } from "./icons.js";
import { ensureFreshToken } from "./tauri.js";
@@ -63,6 +63,7 @@ export function removeRepo(nwo) {
* Resolves with "owner/repo" once added, or null.
*/
export function addRemoteProject({ inGallery, hasProjects }) {
+ const host = forge();
return new Promise((resolve) => {
const dlg = dialog(`
GitHub repository
-
+
Cancel Add
`);
@@ -85,20 +86,20 @@ export function addRemoteProject({ inGallery, hasProjects }) {
dlg.querySelector("form").addEventListener("submit", async (e) => {
if (e.submitter?.value !== "ok") return;
e.preventDefault();
- const gh = parseGitHubSpec(box.value.trim());
- if (!gh) return fail("Enter the repository as owner/repo or its github.com address");
+ const gh = host.parseSpec(box.value.trim());
+ if (!gh) return fail(`Enter the repository as owner/repo or its ${host.host} address`);
error.hidden = true;
add.disabled = true;
try {
- const r = await GitHubSource.api(`/repos/${gh.owner}/${gh.repo}`, await ensureFreshToken());
- const nwo = r.full_name; // its real name and case
+ const r = await host.repo(`${gh.owner}/${gh.repo}`, await ensureFreshToken());
+ const nwo = r.nwo; // its real name and case
if (inGallery(nwo)) return fail(`${nwo} is in the gallery already`);
if (!(await hasProjects(nwo))) return fail(`${nwo} has no KiCad projects`);
watchRepo(nwo);
dlg.close("added");
resolve(nwo);
} catch (err) {
- fail(err.status === 404 ? `${gh.owner}/${gh.repo} isn't on GitHub, or this account can't see it` : String(err.message ?? err));
+ fail(err.status === 404 ? `${gh.owner}/${gh.repo} isn't on ${host.name}, or this account can't see it` : String(err.message ?? err));
} finally {
add.disabled = false;
}
diff --git a/src/desktop/git.js b/src/desktop/git.js
index b798fae..0f2a138 100644
--- a/src/desktop/git.js
+++ b/src/desktop/git.js
@@ -6,7 +6,7 @@
// Links are kept in settings.localCopies: {"owner/repo" (lower case): folder}.
import { $, escapeHtml, settings, saveSettings, toast } from "../app/ui.js";
-import { GitHubSource } from "../sources.js";
+import { forge } from "../forge/index.js";
import { ensureFreshToken, folderPrefix, invoke, listen, pickFolder } from "./tauri.js";
import { mountBranchMenu } from "../app/branch-menu.js";
import { mountHistoryMenu } from "../app/history-menu.js";
@@ -316,15 +316,9 @@ function newBranchDialog(info) {
});
}
-/** The commit author when the copy has no git identity: the GitHub account, with its private e-mail. */
+/** The commit author when the copy has no git identity: the forge account, with its private e-mail. */
async function fallbackAuthor() {
- if (!settings().token) return { name: "KiVi user", email: "kivi@users.noreply.github.com" };
- try {
- const me = await GitHubSource.api("/user", await ensureFreshToken());
- return { name: me.name || me.login, email: `${me.id}+${me.login}@users.noreply.github.com` };
- } catch {
- return { name: "KiVi user", email: "kivi@users.noreply.github.com" };
- }
+ return forge().gitAuthor(settings().token ? await ensureFreshToken() : null);
}
/** Commit chosen files with a message, on this computer (Push… sends them to GitHub). */
@@ -419,7 +413,7 @@ async function pushDialog(info) {
result.textContent = "Pushing to GitHub…";
const token = await ensureFreshToken();
const branch = await invoke("git_push", { path: info.root, owner: info.owner, repo: info.repo, token });
- const compare = `https://github.com/${info.owner}/${info.repo}/compare/${encodeURIComponent(branch)}?expand=1`;
+ const compare = forge().web.compare(`${info.owner}/${info.repo}`, branch);
result.innerHTML = `Pushed ${escapeHtml(branch)} to GitHub. ${onMain ? "" : `Open a pull request `}`;
dlg.querySelector("button[value=push]")?.remove();
} catch (err) {
diff --git a/src/desktop/inbox.js b/src/desktop/inbox.js
index 1b35fd6..42cea19 100644
--- a/src/desktop/inbox.js
+++ b/src/desktop/inbox.js
@@ -4,48 +4,38 @@
// user's review, their own, and those of remote projects, only in
// repositories with KiCad projects, marked with the KiCad files they change,
// opening in the visual diff or the hardware viewer) and Issues (open
-// hardware change requests, the "kivi" issues of ../issues.js, opening in the
+// hardware change requests, the "kivi" issues of ../review.js, opening in the
// viewer on their pin).
// The avatar opens the shared account menu (account.js).
// "+" adds projects to the gallery: a local folder or a GitHub repository.
// Reload lists every repository again, bringing back those removed from projects.
import { $, escapeHtml, settings, saveSettings } from "../app/ui.js";
-import { GitHubSource } from "../sources.js";
+import { forge } from "../forge/index.js";
import { initHeader } from "./account.js";
import { ICONS } from "./icons.js";
import { galleryRepos, initProjects, repoHasProjects } from "./projects.js";
import { localCopy } from "./git.js";
-import { decodeBody, anchorLabel } from "../review.js";
-import { ISSUE_LABEL } from "../issues.js";
+import { ISSUE_LABEL, decodeBody, anchorLabel } from "../review.js";
import { kicadFilesChanged } from "./pr-files.js";
import { ensureFreshToken, invoke, isDesktop, onDrop, routeExternalLinks } from "./tauri.js";
const token = () => settings().token ?? null;
+// The forge the home page lists; repositories ("owner/repo") are on it.
+const host = forge();
const hidden = () => new Set((settings().hiddenRepos ?? []).map((h) => h.toLowerCase())); // removed from projects
// Repositories added with + → Remote project…, unless removed from projects since.
const watched = () => (settings().watchRepos ?? []).filter((r) => !hidden().has(r.toLowerCase()));
-async function api(path) {
- const headers = { Accept: "application/vnd.github+json" };
- if (token()) headers.Authorization = `Bearer ${token()}`;
- const r = await fetch(`https://api.github.com${path}`, { headers });
- if (!r.ok) {
- const body = await r.json().catch(() => ({}));
- throw new Error(`GitHub ${r.status}: ${body.message ?? r.statusText}`);
- }
- return r.json();
-}
-
// ---- pull requests -----------------------------------------------------------------
function sections() {
const out = [];
if (token()) {
- out.push({ title: "Waiting for your review", q: "is:pr is:open archived:false review-requested:@me" });
- out.push({ title: "Your pull requests", q: "is:pr is:open archived:false author:@me" });
+ out.push({ title: "Waiting for your review", filter: { reviewRequested: true } });
+ out.push({ title: "Your pull requests", filter: { author: "me" } });
}
- if (watched().length) out.push({ title: "Remote projects", q: `is:pr is:open ${watched().map((r) => `repo:${r}`).join(" ")}` });
+ if (watched().length) out.push({ title: "Remote projects", filter: { repos: watched() } });
return out;
}
@@ -55,21 +45,21 @@ function ago(iso) {
return "just now";
}
+/** @param {import("../forge/index.js").SearchItem} it */
function prRow(it) {
- const [owner, repo] = it.repository_url.split("/").slice(-2);
- const nwo = `${owner}/${repo}`;
- const diff = `diff.html#${new URLSearchParams({ gh: nwo, pr: String(it.number) })}`;
- const hw = `index.html#${new URLSearchParams({ gh: nwo, pr: `${nwo}#${it.number}` })}`;
+ const nwo = it.nwo;
+ const diff = `diff.html#${new URLSearchParams({ [host.hashKey]: nwo, pr: String(it.number) })}`;
+ const hw = `index.html#${new URLSearchParams({ [host.hashKey]: nwo, pr: `${nwo}#${it.number}` })}`;
return `
-
+
-
${escapeHtml(nwo)}#${it.number} · ${escapeHtml(it.user.login)} · updated ${ago(it.updated_at)} · checking files…
+
${escapeHtml(nwo)}#${it.number} · ${escapeHtml(it.author)} · updated ${ago(it.updatedAt)} · checking files…
`;
}
@@ -81,9 +71,9 @@ async function checkKicadFiles(rows) {
for (let row; (row = queue.shift()); ) {
const badge = row.querySelector(".kicad-badge");
try {
- const files = await api(`/repos/${row.dataset.repo}/pulls/${row.dataset.number}/files?per_page=100`);
const [owner, repo] = row.dataset.repo.split("/");
- const read = (path, ref) => new GitHubSource({ owner, repo, ref, sha: ref, token: token() }).readText(path);
+ const files = await host.pullFiles(owner, repo, Number(row.dataset.number), token(), { max: 1 });
+ const read = (path, ref) => host.source({ owner, repo, ref, sha: ref, token: token() }).readText(path);
const n = (await kicadFilesChanged(files, read)).length;
badge.textContent = n ? `${n} KiCad file${n > 1 ? "s" : ""} changed` : "no KiCad changes";
badge.classList.toggle("has-kicad", n > 0);
@@ -108,7 +98,7 @@ async function renderLists() {
const hasProjects = new Map(); // "owner/repo" → Promise, once per refresh
const removed = hidden();
const keep = (it) => {
- const nwo = it.repository_url.split("/").slice(-2).join("/");
+ const nwo = it.nwo;
if (removed.has(nwo.toLowerCase())) return false;
if (!hasProjects.has(nwo)) hasProjects.set(nwo, repoHasProjects(nwo).catch(() => true)); // unknown: show it
return hasProjects.get(nwo);
@@ -116,9 +106,8 @@ async function renderLists() {
for (const [i, s] of secs.entries()) {
const ul = $(`#sec-${i}`);
try {
- const res = await api(`/search/issues?${new URLSearchParams({ q: s.q, sort: "updated", per_page: "30" })}`);
- const found = res.items.filter((it) => !seen.has(it.html_url));
- for (const it of found) seen.add(it.html_url);
+ const found = (await host.searchPullRequests(s.filter, token())).filter((it) => !seen.has(it.url));
+ for (const it of found) seen.add(it.url);
// Only pull requests in repositories with KiCad projects.
const flags = await Promise.all(found.map(keep));
const items = found.filter((_, j) => flags[j]);
@@ -132,46 +121,28 @@ async function renderLists() {
// ---- issues ------------------------------------------------------------------------
-const ISSUE_Q = `is:issue is:open archived:false label:${ISSUE_LABEL}`;
-const MAX_Q = 250; // GitHub's search rejects queries over 256 characters
-
-/** Search queries for open KiVi issues in these repositories, as few as fit. */
-function repoQueries(repos) {
- const out = [];
- let q = ISSUE_Q;
- for (const r of repos) {
- if (q !== ISSUE_Q && q.length + r.length + 6 > MAX_Q) {
- out.push(q);
- q = ISSUE_Q;
- }
- q += ` repo:${r}`;
- }
- if (q !== ISSUE_Q) out.push(q);
- return out;
-}
-
-/** Where an issue opens: on its pin in the local copy if there is one, else on GitHub's default branch. */
+/** Where an issue opens: on its pin in the local copy if there is one, else on the forge's default branch. */
function issueViewUrl(nwo, number, anchor) {
const at = anchor?.file ? { file: anchor.file, tab: anchor.file.endsWith(".kicad_pcb") ? "pcb" : "sch", thread: String(number) } : {};
const copy = localCopy(nwo);
- return `index.html#${new URLSearchParams(copy ? { folder: copy, ...at } : { gh: nwo, ...at })}`;
+ return `index.html#${new URLSearchParams(copy ? { folder: copy, ...at } : { [host.hashKey]: nwo, ...at })}`;
}
+/** @param {import("../forge/index.js").SearchItem} it */
function issueRow(it) {
- const [owner, repo] = it.repository_url.split("/").slice(-2);
- const nwo = `${owner}/${repo}`;
+ const nwo = it.nwo;
const { anchor } = decodeBody(it.body);
const pin = anchor?.file ? `📍 ${escapeHtml(anchorLabel(anchor))} in ${escapeHtml(anchor.file.split("/").pop())} ` : "not pinned";
const hw = issueViewUrl(nwo, it.number, anchor);
return `
-
+
-
${escapeHtml(nwo)}#${it.number} · ${escapeHtml(it.user.login)} · updated ${ago(it.updated_at)} · ${pin}${it.comments ? ` · ${it.comments} comment${it.comments > 1 ? "s" : ""}` : ""}
+
${escapeHtml(nwo)}#${it.number} · ${escapeHtml(it.author)} · updated ${ago(it.updatedAt)} · ${pin}${it.comments ? ` · ${it.comments} comment${it.comments > 1 ? "s" : ""}` : ""}
`;
}
@@ -182,10 +153,10 @@ async function renderIssues() {
const repos = galleryRepos();
const secs = [];
if (token()) {
- secs.push({ title: "Assigned to you", qs: [`${ISSUE_Q} assignee:@me`] });
- secs.push({ title: "Opened by you", qs: [`${ISSUE_Q} author:@me`] });
+ secs.push({ title: "Assigned to you", filter: { label: ISSUE_LABEL, assignee: "me" } });
+ secs.push({ title: "Opened by you", filter: { label: ISSUE_LABEL, author: "me" } });
}
- if (repos.length) secs.push({ title: "In your projects", qs: repoQueries(repos) });
+ if (repos.length) secs.push({ title: "In your projects", filter: { label: ISSUE_LABEL, repos } });
if (!secs.length) {
lists.innerHTML = `Nothing to show yet: sign in, or add a remote project with + in Projects.
`;
return;
@@ -195,13 +166,12 @@ async function renderIssues() {
for (const [i, s] of secs.entries()) {
const ul = $(`#isec-${i}`);
try {
- const found = [];
- for (const q of s.qs) found.push(...(await api(`/search/issues?${new URLSearchParams({ q, sort: "updated", per_page: "50" })}`)).items);
+ const found = await host.searchIssues(s.filter, token());
const items = found
- .filter((it) => !seen.has(it.html_url) && !removed.has(it.repository_url.split("/").slice(-2).join("/").toLowerCase()))
- .sort((a, b) => b.updated_at.localeCompare(a.updated_at))
+ .filter((it) => !seen.has(it.url) && !removed.has(it.nwo.toLowerCase()))
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
.slice(0, 50);
- for (const it of items) seen.add(it.html_url);
+ for (const it of items) seen.add(it.url);
ul.innerHTML = items.length ? items.map(issueRow).join("") : `None `;
} catch (e) {
ul.innerHTML = `${escapeHtml(e.message)} `;
diff --git a/src/desktop/local-projects.js b/src/desktop/local-projects.js
index b7a9c9c..2917b04 100644
--- a/src/desktop/local-projects.js
+++ b/src/desktop/local-projects.js
@@ -10,7 +10,7 @@
// linked to that repository's card instead (settings.localCopies, git.js).
import { escapeHtml, settings, saveSettings, toast } from "../app/ui.js";
-import { GitHubSource, parseGitHubSpec } from "../sources.js";
+import { forge } from "../forge/index.js";
import { findProjects } from "../project.js";
import { dialog, localCopy, setLocalCopy } from "./git.js";
import { ensureFreshToken, invoke, pickFolder } from "./tauri.js";
@@ -134,12 +134,13 @@ export function removeLocalProject(folder) {
* KiVi can't merge a history GitHub already has. Resolves true once linked.
*/
export function linkLocalProject(p, inGallery) {
+ const host = forge();
return new Promise((resolve) => {
const dlg = dialog(``);
@@ -150,26 +151,26 @@ export function linkLocalProject(p, inGallery) {
form.addEventListener("submit", async (e) => {
if (e.submitter?.value !== "ok") return;
e.preventDefault();
- const gh = parseGitHubSpec(box.value.trim());
+ const gh = host.parseSpec(box.value.trim());
const fail = (msg) => {
error.textContent = msg;
error.hidden = false;
};
- if (!gh || gh.ref || gh.path || gh.rest) return fail("Enter the repository as owner/repo or its github.com address");
+ if (!gh || gh.ref || gh.path || gh.rest) return fail(`Enter the repository as owner/repo or its ${host.host} address`);
try {
// Its real name and case, and whether this account can see it.
- const r = await GitHubSource.api(`/repos/${gh.owner}/${gh.repo}`, await ensureFreshToken());
- const [owner, repo] = r.full_name.split("/");
+ const r = await host.repo(`${gh.owner}/${gh.repo}`, await ensureFreshToken());
+ const [owner, repo] = r.nwo.split("/");
const info = await invoke("git_link_github", { path: p.folder, owner, repo });
dlg.close("linked");
- if (inGallery(r.full_name)) {
+ if (inGallery(r.nwo)) {
// The repository has cards already: the folder becomes their local copy.
saveFolders(folders().filter((f) => !sameFolder(f, p.folder)));
- adopt(r.full_name, info.root);
- } else toast(`Linked ${p.folder} to ${r.full_name}`);
+ adopt(r.nwo, info.root);
+ } else toast(`Linked ${p.folder} to ${r.nwo}`);
resolve(true);
} catch (err) {
- fail(err.status === 404 ? `${gh.owner}/${gh.repo} isn't on GitHub, or this account can't see it` : String(err.message ?? err));
+ fail(err.status === 404 ? `${gh.owner}/${gh.repo} isn't on ${host.name}, or this account can't see it` : String(err.message ?? err));
}
});
dlg.addEventListener("close", () => dlg.returnValue !== "linked" && resolve(false));
diff --git a/src/desktop/pr-files.js b/src/desktop/pr-files.js
index b643387..1c4898e 100644
--- a/src/desktop/pr-files.js
+++ b/src/desktop/pr-files.js
@@ -1,29 +1,29 @@
// Which files of a pull request count as KiCad changes, for the inbox badge:
// the same files the visual diff lists, so the two agree.
-import { DIFFABLE, RULE_FILES, textBeforePatch } from "../sources.js";
+import { DIFFABLE, RULE_FILES } from "../project.js";
+import { textBeforePatch } from "../sources.js";
import { diffRules } from "../diff/rules-diff.js";
/**
* Schematics, boards and .kicad_dru files always count; a .kicad_pro only when
* its design rules changed (KiCad rewrites it on almost every save). A file
* that can't be checked counts, so a change is never hidden.
- * @param {object[]} files entries of GET /repos/x/y/pulls/N/files
+ * @param {import("../forge/index.js").ChangedFile[]} files a pull request's files (forge.pullFiles)
* @param {(path: string, ref: string) => Promise} readText reads a file at a commit
* @returns {Promise} the files that count
*/
export async function kicadFilesChanged(files, readText) {
const checks = files.map(async (f) => {
- if (DIFFABLE.test(f.filename) || DIFFABLE.test(f.previous_filename ?? "")) return true;
- if (!RULE_FILES.test(f.filename)) return false;
- if (/\.kicad_dru$/i.test(f.filename) || f.status !== "modified" && f.status !== "renamed" && f.status !== "changed") return true;
- const ref = /[?&]ref=([^&]+)/.exec(f.contents_url ?? "")?.[1];
- if (!f.patch || !ref) return true; // GitHub leaves out the patch of very large diffs
+ if (DIFFABLE.test(f.path) || DIFFABLE.test(f.previous ?? "")) return true;
+ if (!RULE_FILES.test(f.path)) return false;
+ if (/\.kicad_dru$/i.test(f.path) || f.status !== "modified" && f.status !== "renamed" && f.status !== "changed") return true;
+ if (!f.patch || !f.ref) return true; // forges leave out the patch of very large diffs
try {
- const after = await readText(f.filename, ref);
- return diffRules(f.filename, textBeforePatch(after, f.patch), after).changes.length > 0;
+ const after = await readText(f.path, f.ref);
+ return diffRules(f.path, textBeforePatch(after, f.patch), after).changes.length > 0;
} catch (e) {
- console.warn(f.filename, e);
+ console.warn(f.path, e);
return true;
}
});
diff --git a/src/desktop/projects.js b/src/desktop/projects.js
index 461388e..f40f285 100644
--- a/src/desktop/projects.js
+++ b/src/desktop/projects.js
@@ -5,13 +5,13 @@
//
// API cost is kept low with two caches:
// - the project list per repository (localStorage), reused until the
-// repository's `pushed_at` or default branch changes, so a refresh without
+// repository's last push or default branch changes, so a refresh without
// new commits costs only the repository listing;
// - thumbnails (IndexedDB), keyed by the board file's git blob SHA, so a board
// is fetched and rendered once per version.
import { escapeHtml, settings, toast } from "../app/ui.js";
-import { GitHubSource } from "../sources.js";
+import { forge } from "../forge/index.js";
import { findProjects } from "../project.js";
import { cloneProject, forgetSync, knownSync, linkProject, localCopy, localViewUrl, syncState, unlinkLocalCopy } from "./git.js";
import { kicadAction, openInKicad, projectPath } from "./tauri.js";
@@ -23,37 +23,16 @@ const THUMB_W = 640, THUMB_H = 400;
const PAGE = 48; // cards rendered at a time; more as the end of the grid scrolls into view
const MAX_PREVIEW = 30e6; // bytes; bigger boards (KiCad's 85 MB Jetson demo) take minutes and a lot of memory to parse
const token = () => settings().token ?? null;
-const api = (path) => GitHubSource.api(path, token());
+// The forge the gallery lists; its repositories are named "owner/repo".
+const host = forge();
// ---- repositories and projects ------------------------------------------------------
-/** All pages of a listing (capped at `max` pages of 100). */
-async function all(path, key, max = 10) {
- const out = [];
- for (let page = 1; page <= max; page++) {
- const res = await api(`${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`);
- const items = key ? res[key] : res;
- out.push(...items);
- if (items.length < 100) break;
- }
- return out;
-}
-
-/** Repositories to scan, by full name. */
-async function listRepos() {
- const repos = new Map();
+/** Repositories to scan: the signed-in account's, then remote projects, less those removed from projects. */
+function listRepos() {
// Removed from the gallery by the user (Remove from projects), until added again.
const hidden = new Set((settings().hiddenRepos ?? []).map((h) => h.toLowerCase()));
- // Not `size`: GitHub computes it later, so a repository just filled by a push can still say 0.
- // An empty one is found by its scan instead (409, no projects).
- const add = (r) => r && !r.disabled && !hidden.has(r.full_name.toLowerCase()) && repos.set(r.full_name, r);
- if (token()) {
- // Exactly the repositories the GitHub App is installed on (and the user can see).
- for (const inst of await all("/user/installations", "installations"))
- for (const r of await all(`/user/installations/${inst.id}/repositories`, "repositories")) add(r);
- }
- for (const nwo of settings().watchRepos ?? []) if (!repos.has(nwo) && !hidden.has(nwo.toLowerCase())) add(await api(`/repos/${nwo}`).catch(() => null));
- return [...repos.values()];
+ return host.listRepos(token(), { watched: settings().watchRepos ?? [], hidden });
}
function loadIndex() {
@@ -71,24 +50,18 @@ function saveIndex(index) {
}
}
-/** Projects of one repository at its default branch (one tree request). */
+/** Projects of one repository at its default branch (one tree request). @param {import("../forge/index.js").RepoInfo} r */
async function scanRepo(r) {
- let tree;
- try {
- tree = await api(`/repos/${r.full_name}/git/trees/${encodeURIComponent(r.default_branch)}?recursive=1`);
- } catch (e) {
- if (e.status !== 409) throw e; // 409: empty repository
- tree = { tree: [] };
- }
- const blobs = new Map(tree.tree.filter((e) => e.type === "blob" && /\.kicad_(pro|sch|pcb)$/.test(e.path)).map((e) => [e.path, e]));
+ const tree = await host.tree(r.nwo, r.defaultBranch, token());
+ const blobs = new Map(tree.files.filter((e) => /\.kicad_(pro|sch|pcb)$/.test(e.path)).map((e) => [e.path, e]));
// Without a .kicad_pro, findProjects lists every loose schematic (sub-sheets too); keep only boards then.
const projects = findProjects([...blobs.keys()])
.filter((p) => p.pro || p.pcb)
.map((p) => ({ name: p.name, dir: p.dir, pro: p.pro, sch: p.sch, pcb: p.pcb, pcbSha: blobs.get(p.pcb)?.sha ?? null, pcbSize: blobs.get(p.pcb)?.size ?? 0 }));
return {
- repo: { nwo: r.full_name, private: r.private, archived: r.archived },
- pushed: r.pushed_at,
- branch: r.default_branch,
+ repo: { nwo: r.nwo, private: r.private, archived: r.archived },
+ pushed: r.pushedAt,
+ branch: r.defaultBranch,
truncated: !!tree.truncated,
projects,
};
@@ -126,15 +99,15 @@ export async function repoHasProjects(nwo) {
} catch {
cache = {};
}
- const r = await api(`/repos/${nwo}`);
- const hit = cache[r.full_name];
- if (hit && hit.pushed === r.pushed_at && hit.branch === r.default_branch) return hit.has;
+ const r = await host.repo(nwo, token());
+ const hit = cache[r.nwo];
+ if (hit && hit.pushed === r.pushedAt && hit.branch === r.defaultBranch) return hit.has;
const scanned = await scanRepo(r);
// A truncated tree may hide projects: show its pull requests rather than lose them.
const has = scanned.projects.length > 0 || scanned.truncated;
try {
cache = JSON.parse(localStorage.getItem(KICAD_REPOS_KEY) ?? "{}"); // other checks ran meanwhile
- localStorage.setItem(KICAD_REPOS_KEY, JSON.stringify({ ...cache, [r.full_name]: { pushed: r.pushed_at, branch: r.default_branch, has } }));
+ localStorage.setItem(KICAD_REPOS_KEY, JSON.stringify({ ...cache, [r.nwo]: { pushed: r.pushedAt, branch: r.defaultBranch, has } }));
} catch {
/* storage unavailable: checked again next time */
}
@@ -232,7 +205,7 @@ function thumbnail(p) {
if (!blob) {
blob = await limited(async () => {
const [owner, repo] = p.local ? [] : p.nwo.split("/");
- const text = p.local ? await readLocalBoard(p) : await new GitHubSource({ owner, repo, ref: p.branch, token: token() }).readText(p.pcb);
+ const text = p.local ? await readLocalBoard(p) : await host.source({ owner, repo, ref: p.branch, token: token() }).readText(p.pcb);
return rasterize(await renderInWorker(text, p.pcb));
});
await idb("readwrite", (s) => s.put(blob, k));
@@ -262,7 +235,6 @@ function when(iso) {
}
const tooBig = (p) => p.pcbSize > MAX_PREVIEW;
-const enc = (path) => path.split("/").map(encodeURIComponent).join("/");
function thumbHtml(p) {
const url = thumbKey(p) && thumbUrls.get(thumbKey(p));
@@ -280,8 +252,8 @@ function cardHtml(p) {
const spec = `${p.nwo}@${p.branch}:${p.pro ?? p.pcb}`;
const local = localCopy(p.nwo);
// A linked project always opens from its local copy; otherwise from GitHub.
- const view = (tab) => (local ? localViewUrl(local, p.pro ?? p.pcb, tab) : `index.html#${new URLSearchParams({ gh: spec, ...(tab && { tab }) })}`);
- const github = `https://github.com/${p.nwo}/tree/${enc(p.branch)}${p.dir ? `/${enc(p.dir)}` : ""}`;
+ const view = (tab) => (local ? localViewUrl(local, p.pro ?? p.pcb, tab) : `index.html#${new URLSearchParams({ [host.hashKey]: spec, ...(tab && { tab }) })}`);
+ const web = host.web.tree(p.nwo, p.branch, p.dir);
const thumb = thumbHtml(p);
const where = p.dir ? `${p.nwo}/${p.dir}` : p.nwo;
// Linked: the views above open the copy; otherwise download the repository or link a clone.
@@ -302,7 +274,7 @@ function cardHtml(p) {
${p.pcb ? `PCB 3D view ` : ""}
Bill of materials
Open in KiCad
- View on GitHub
+ View on ${escapeHtml(host.name)}
${localItems}
Remove from projects
@@ -345,7 +317,7 @@ function localCardHtml(p) {
// The project's place in the repository, on the branch checked out.
const sub = p.git ? [relativeTo(p.git.root, p.folder), p.dir].filter(Boolean).join("/") : "";
const github = p.git
- ? `View on GitHub `
+ ? `View on ${escapeHtml(host.name)} `
: `View on GitHub `;
const link = p.git ? "" : `Link to GitHub… `;
const known = p.git ? knownSync(p.git.nwo, p.git.root) : { color: "grey", title: "Not linked to GitHub: Link to GitHub… from the ⋯ menu" };
@@ -617,18 +589,18 @@ export function initProjects({ grid, status, filter, add = null, onWatched = nul
}
if (id !== scan) return;
// Forget repositories that are no longer reachable.
- const names = new Set(repos.map((r) => r.full_name));
+ const names = new Set(repos.map((r) => r.nwo));
for (const k of Object.keys(index)) if (!names.has(k)) delete index[k];
queueRender();
- const todo = repos.filter((r) => index[r.full_name]?.pushed !== r.pushed_at || index[r.full_name]?.branch !== r.default_branch);
+ const todo = repos.filter((r) => index[r.nwo]?.pushed !== r.pushedAt || index[r.nwo]?.branch !== r.defaultBranch);
let done = 0, failed = 0, stop = null;
const progress = () => (status.textContent = `Scanning repositories… ${done} of ${todo.length}`);
if (todo.length) progress();
const work = async () => {
for (let r; !stop && id === scan && (r = todo.shift()); ) {
try {
- index[r.full_name] = await scanRepo(r);
+ index[r.nwo] = await scanRepo(r);
queueRender();
} catch (e) {
failed++; // keep the previous result, if any; don't cache the failure
diff --git a/src/desktop/tauri.js b/src/desktop/tauri.js
index 54a941c..167c8c2 100644
--- a/src/desktop/tauri.js
+++ b/src/desktop/tauri.js
@@ -3,6 +3,7 @@
// gets wired up.
import { settings, saveSettings, toast } from "../app/ui.js";
+import { github } from "../forge/github.js";
const T = window.__TAURI__;
export const isDesktop = !!T;
@@ -204,7 +205,7 @@ const SIGNIN_HTML = `
Sign in with GitHub
This build has no GitHub App configured. Register one at
- github.com/settings/apps/new with Enable Device Flow
+ ${github.web.newApp.replace(/^https:\/\//, "")} with Enable Device Flow
ticked, and paste its Client ID (or build with KIVI_GITHUB_CLIENT_ID set).
GitHub App Client ID
@@ -230,7 +231,7 @@ const SIGNIN_HTML = `
/** Install / repository-access page of the App, or null if its URL name isn't known. */
export async function appInstallUrl() {
const slug = (await invoke("github_app_slug")) ?? settings().githubAppSlug;
- return slug ? `https://github.com/apps/${encodeURIComponent(slug)}/installations/new` : null;
+ return slug ? github.web.appInstall(slug) : null;
}
/** Settings fields for a token response from GitHub. */
@@ -396,14 +397,7 @@ export async function signInWithGitHub() {
async function offerInstall(dlg, step, go, token) {
const url = await appInstallUrl();
if (!url) return;
- try {
- const r = await fetch("https://api.github.com/user/installations?per_page=1", {
- headers: { Accept: "application/vnd.github+json", Authorization: `Bearer ${token}` },
- });
- if (!r.ok || (await r.json()).total_count > 0) return;
- } catch {
- return;
- }
+ if ((await github.hasAppInstallation(token)) !== false) return; // installed, or GitHub can't tell
step("install");
go.textContent = "Install on GitHub";
go.onclick = () => T.opener.openUrl(url);
diff --git a/src/forge/github.js b/src/forge/github.js
new file mode 100644
index 0000000..bfe9aba
--- /dev/null
+++ b/src/forge/github.js
@@ -0,0 +1,836 @@
+// The GitHub adapter: every request KiVi makes to GitHub's REST and GraphQL
+// APIs, raw.githubusercontent.com, and every github.com page address it links
+// to. The rest of the app reaches GitHub only through the `github` forge
+// object below (the interface is described in ./index.js), and gets back
+// forge-neutral shapes: RepoInfo, PullRequest, ChangedFile, Comparison,
+// SearchItem and the review/issue thread shape of ../review.js.
+//
+// No DOM and no Tauri: this runs under gjs (tests/review.js) and in pages.
+
+import { COMPARED, SOURCE_FILES } from "../project.js";
+import { ISSUE_LABEL, LABEL_COLOUR, LABEL_DESCRIPTION, closingNumbers, comment, encodeBody, issueThread } from "../review.js";
+
+const API = "https://api.github.com";
+const WEB = "https://github.com";
+const FULL_SHA = /^[0-9a-f]{40}$/i;
+const encPath = (p) => p.split("/").map(encodeURIComponent).join("/");
+
+// ---- requests ------------------------------------------------------------------------
+
+/**
+ * One GitHub API request. `writeHint` (what a refused write needs access to,
+ * e.g. "pull requests") turns 401/403/404/422 into the review panel's
+ * explanations; without it errors say "GitHub
: ".
+ * @returns {Promise} the JSON reply (null for 204)
+ */
+async function request(path, { token = null, method = "GET", body, fetch: fetchFn = null, writeHint = null } = {}) {
+ const headers = { Accept: "application/vnd.github+json" };
+ if (token) headers.Authorization = `Bearer ${token}`;
+ if (body) headers["Content-Type"] = "application/json";
+ const doFetch = fetchFn ?? ((...a) => globalThis.fetch(...a));
+ const r = await doFetch(`${API}${path}`, { method, headers, body: body ? JSON.stringify(body) : undefined });
+ if (r.status === 204) return null;
+ if (r.ok) return r.json();
+ const data = await r.json().catch(() => ({}));
+ throw writeHint ? githubError(r.status, data, r.headers, writeHint) : readError(r, data);
+}
+
+function readError(r, data) {
+ const msg = r.status === 403 && r.headers?.get?.("x-ratelimit-remaining") === "0" ? "GitHub API rate limit reached — sign in with GitHub for a higher limit" : data.message || r.statusText;
+ const err = new Error(`GitHub ${r.status}: ${msg}`);
+ err.status = r.status;
+ return err;
+}
+
+/**
+ * One entry of a 422's `errors`: a string, or {resource, field, code} with a
+ * `message` only for code "custom", so the others are spelt out
+ * ("PullRequestReviewComment path invalid") instead of "[object Object]".
+ * A message that doesn't name its field ("could not be resolved") gets it.
+ */
+function validationError(e) {
+ if (typeof e !== "object" || e === null) return String(e);
+ if (e.message) return e.field && !e.message.includes(e.field) ? `${e.field} ${e.message}` : e.message;
+ return [e.resource, e.field, e.code].filter(Boolean).join(" ") || JSON.stringify(e);
+}
+
+function githubError(status, data, headers, what) {
+ let msg = data?.message || `HTTP ${status}`;
+ if (status === 403 && headers?.get?.("x-ratelimit-remaining") === "0") msg = "API rate limit reached — sign in with GitHub for a higher limit";
+ else if (status === 401) msg = "GitHub ended the sign-in; sign in again";
+ else if (status === 403 || status === 404) msg += ` — the token needs write access to ${what}`;
+ else if (status === 422 && data?.errors?.length) msg += `: ${data.errors.map(validationError).join("; ")}`;
+ const err = new Error(`GitHub ${status}: ${msg}`);
+ err.status = status;
+ return err;
+}
+
+/** All pages of a listing of 100 per page (capped at `max` pages); `key` picks the list out of an object reply. */
+async function pages(path, token, { key = null, max = 10 } = {}) {
+ const out = [];
+ for (let page = 1; page <= max; page++) {
+ const res = await request(`${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`, { token });
+ const items = key ? res[key] : res;
+ out.push(...items);
+ if (items.length < 100) break;
+ }
+ return out;
+}
+
+// ---- shapes --------------------------------------------------------------------------
+
+/** @returns {import("./index.js").RepoInfo} */
+const repoInfo = (r) => ({
+ nwo: r.full_name,
+ defaultBranch: r.default_branch,
+ pushedAt: r.pushed_at,
+ private: !!r.private,
+ archived: !!r.archived,
+ disabled: !!r.disabled,
+ url: r.html_url,
+});
+
+/** @returns {import("./index.js").ChangedFile} */
+const changedFile = (f) => ({
+ path: f.filename,
+ previous: f.previous_filename ?? f.filename,
+ status: f.status,
+ patch: f.patch ?? null,
+ // The commit the file was listed at (the pull request's head), for reading it.
+ ref: /[?&]ref=([^&]+)/.exec(f.contents_url ?? "")?.[1] ?? null,
+});
+
+const commitEntry = (c) => ({
+ sha: c.sha,
+ summary: c.commit.message.split("\n")[0],
+ author: c.commit.author?.name ?? c.author?.login ?? "",
+ time: Date.parse(c.commit.author?.date ?? c.commit.committer?.date) / 1000,
+});
+
+/** A search hit (pull request or issue) → SearchItem. */
+const searchItem = (it) => ({
+ nwo: it.repository_url.split("/").slice(-2).join("/"),
+ number: it.number,
+ title: it.title,
+ body: it.body ?? "",
+ draft: !!it.draft,
+ author: it.user?.login ?? "ghost",
+ avatar: it.user?.avatar_url ?? null,
+ updatedAt: it.updated_at,
+ comments: it.comments ?? 0,
+ url: it.html_url,
+});
+
+// ---- specs ---------------------------------------------------------------------------
+
+/**
+ * Parse github.com URLs and shorthands:
+ * owner/repo, owner/repo@ref, owner/repo@ref:path,
+ * https://github.com/owner/repo[/tree|blob/[/]]
+ * Refs containing "/" are resolved later against the API (`rest`).
+ */
+function parseSpec(spec) {
+ spec = spec.trim();
+ let m = /^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/]+)\/([^/#?]+?)(?:\.git)?(?:\/(tree|blob)\/(.+?))?\/?(?:[?#].*)?$/.exec(spec);
+ if (m) return { owner: m[1], repo: m[2], rest: m[4] ? decodeURIComponent(m[4]) : null, kind: m[3] ?? null };
+ m = /^([\w.-]+)\/([\w.-]+)(?:@([^:]+))?(?::(.*))?$/.exec(spec);
+ if (m) return { owner: m[1], repo: m[2], ref: m[3] ?? null, path: m[4] ?? "", rest: null };
+ return null;
+}
+
+// ---- files of a repository -------------------------------------------------------------
+
+/** A repository at a branch or commit, read through the API (signed in) or the raw CDN (public). */
+export class GitHubSource {
+ constructor({ owner, repo, ref, path = "", token = null, sha = null }) {
+ this.kind = "github";
+ this.forge = github;
+ this.owner = owner;
+ this.repo = repo;
+ this.ref = ref;
+ this.sha = sha;
+ this.path = path; // sub-directory or file the user pointed at
+ this.token = token;
+ this.label = `${owner}/${repo}@${ref}${path ? `:${path}` : ""}`;
+ this._list = null;
+ }
+
+ /** Directory the listing is restricted to ("" = whole repository). */
+ get dir() {
+ const p = this.path.replace(/\/+$/, "");
+ return SOURCE_FILES.test(p) ? p.slice(0, Math.max(0, p.lastIndexOf("/"))) : p;
+ }
+
+ async list() {
+ if (!this._list) {
+ // "[:]" lists just a sub-tree, which keeps huge repositories manageable.
+ const dir = this.dir;
+ const rev = encodeURIComponent(this.sha ?? this.ref) + (dir ? ":" + encPath(dir) : "");
+ let tree;
+ try {
+ tree = await request(`/repos/${this.owner}/${this.repo}/git/trees/${rev}?recursive=1`, { token: this.token });
+ } catch (e) {
+ // The folder isn't in this commit (moved, or a mangled link): list the whole repository instead.
+ if (!(dir && e.status === 404)) throw e;
+ tree = await request(`/repos/${this.owner}/${this.repo}/git/trees/${encodeURIComponent(this.sha ?? this.ref)}?recursive=1`, { token: this.token });
+ console.warn(`${dir} not found in ${this.ref}; listing the whole repository`);
+ this.path = "";
+ this.label = `${this.owner}/${this.repo}@${this.ref}`;
+ }
+ const listed = this.dir;
+ this.truncated = !!tree.truncated;
+ const paths = tree.tree.filter((e) => e.type === "blob").map((e) => (listed ? `${listed}/${e.path}` : e.path));
+ this._list = paths.filter((p) => SOURCE_FILES.test(p));
+ }
+ return this._list;
+ }
+
+ has(path) {
+ return !!this._list?.includes(path);
+ }
+
+ rawUrl(path) {
+ return `https://raw.githubusercontent.com/${this.owner}/${this.repo}/${encodeURIComponent(this.sha ?? this.ref)}/${encPath(path)}`;
+ }
+
+ async fetchFile(path) {
+ const rev = encodeURIComponent(this.sha ?? this.ref);
+ let r;
+ if (this.token) {
+ // Private with token: contents API with the raw media type.
+ r = await fetch(`${API}/repos/${this.owner}/${this.repo}/contents/${encPath(path)}?ref=${rev}`, {
+ headers: { Accept: "application/vnd.github.raw", Authorization: `Bearer ${this.token}` },
+ });
+ } else {
+ // Public: raw CDN (no API rate limit).
+ r = await fetch(this.rawUrl(path));
+ }
+ if (!r.ok) throw new Error(`${path}: HTTP ${r.status}`);
+ return r;
+ }
+
+ async readText(path) {
+ const text = await (await this.fetchFile(path)).text();
+ if (text.startsWith("version https://git-lfs")) throw new Error(`${path} is stored in Git LFS, which is not supported yet`);
+ return text;
+ }
+
+ async readBinary(path) {
+ return new Uint8Array(await (await this.fetchFile(path)).arrayBuffer());
+ }
+
+ url(path) {
+ return this.token ? null : this.rawUrl(path);
+ }
+}
+
+/** Build a source from a spec, resolving the default branch and ambiguous refs. */
+async function open(spec, token = null) {
+ const p = typeof spec === "string" ? parseSpec(spec) : spec;
+ if (!p) throw new Error("Not a GitHub repository URL");
+ let ref = p.ref, path = p.path ?? "";
+ if (p.rest) {
+ // "[/]": the shortest ref that exists (shortest first is cheaper).
+ const parts = p.rest.split("/");
+ for (let i = 1; i <= parts.length; i++) {
+ const cand = parts.slice(0, i).join("/");
+ try {
+ const c = await request(`/repos/${p.owner}/${p.repo}/commits/${encodeURIComponent(cand)}`, { token });
+ return new GitHubSource({ owner: p.owner, repo: p.repo, ref: cand, path: parts.slice(i).join("/"), token, sha: c.sha });
+ } catch (e) {
+ if (e.status && e.status !== 404 && e.status !== 422) throw e;
+ }
+ }
+ throw new Error(`Could not resolve branch/commit in "${p.rest}"`);
+ }
+ if (!ref) ref = (await request(`/repos/${p.owner}/${p.repo}`, { token })).default_branch;
+ // "HEAD" is the default branch: show its name if the API can tell (it can't
+ // for a private repository without a token, which still opens as HEAD).
+ else if (ref === "HEAD") ref = (await request(`/repos/${p.owner}/${p.repo}`, { token }).catch(() => null))?.default_branch ?? ref;
+ return new GitHubSource({ owner: p.owner, repo: p.repo, ref, path, token });
+}
+
+// ---- comparisons -----------------------------------------------------------------------
+
+/** Files that differ between two commits, from their trees (the compare API only measures from the merge base). */
+async function treeDiff(token, owner, repo, a, b) {
+ const blobs = async (sha) => {
+ const t = await request(`/repos/${owner}/${repo}/git/trees/${sha}?recursive=1`, { token });
+ if (t.truncated) throw new Error("Repository too large to compare these two commits directly; pick a branch as the base instead");
+ return new Map(t.tree.filter((e) => e.type === "blob").map((e) => [e.path, e.sha]));
+ };
+ const [before, after] = await Promise.all([blobs(a), blobs(b)]);
+ const files = [];
+ for (const [path, sha] of after) if (before.get(path) !== sha) files.push({ filename: path, status: before.has(path) ? "modified" : "added" });
+ for (const path of before.keys()) if (!after.has(path)) files.push({ filename: path, status: "removed" });
+ return files;
+}
+
+/**
+ * Resolve what to compare:
+ * {owner, repo, pr: 42} pull request (base = merge base, like GitHub)
+ * {owner, repo, commit: ""} commit against its first parent
+ * {owner, repo, base: "main", head: "x"} any two refs: from where head left a base branch
+ * (three-dot, like a pull request); a base commit
+ * (full SHA) as it is; no base = the default branch
+ * Only KiCad files the visual diff compares are listed.
+ * @returns {Promise}
+ */
+async function compare(spec, token = null) {
+ const { owner, repo } = spec;
+ const api = (p) => request(p, { token });
+ let base, head, files, title, url;
+ if (spec.pr) {
+ const pr = await pullRequest(owner, repo, spec.pr, token);
+ head = { owner: pr.head.owner, repo: pr.head.repo, sha: pr.head.sha, ref: pr.head.ref };
+ // Diff against the merge base so unrelated base-branch changes don't show up.
+ const cmp = await api(`/repos/${owner}/${repo}/compare/${pr.base.sha}...${pr.head.sha}`).catch(() => null);
+ base = { owner, repo, sha: cmp?.merge_base_commit?.sha ?? pr.base.sha, ref: pr.base.ref };
+ files = await pullFiles(owner, repo, spec.pr, token);
+ title = `#${pr.number} ${pr.title}`;
+ url = pr.url;
+ } else if (spec.commit) {
+ const c = await api(`/repos/${owner}/${repo}/commits/${encodeURIComponent(spec.commit)}`);
+ head = { owner, repo, sha: c.sha, ref: c.sha.slice(0, 7) };
+ const parent = c.parents[0]?.sha;
+ base = { owner, repo, sha: parent ?? null, ref: parent ? parent.slice(0, 7) : "(none)" };
+ files = (c.files ?? []).map(changedFile);
+ title = c.commit.message.split("\n")[0];
+ url = c.html_url;
+ } else {
+ const baseRef = spec.base || (await api(`/repos/${owner}/${repo}`)).default_branch;
+ // The same branch on both sides (e.g. the viewer's Visual diff on the default branch): its latest commit.
+ if (baseRef === spec.head) return compare({ owner, repo, commit: spec.head }, token);
+ const cmp = await api(`/repos/${owner}/${repo}/compare/${encodeURIComponent(baseRef)}...${encodeURIComponent(spec.head)}`);
+ const short = (r) => (FULL_SHA.test(r) ? r.slice(0, 7) : r);
+ const headSha = cmp.commits.at(-1)?.sha ?? (FULL_SHA.test(spec.head) ? spec.head : (await api(`/repos/${owner}/${repo}/commits/${encodeURIComponent(spec.head)}`)).sha);
+ base = { owner, repo, sha: cmp.merge_base_commit.sha, ref: short(baseRef) };
+ head = { owner, repo, sha: headSha, ref: short(spec.head) };
+ files = (cmp.files ?? []).map(changedFile);
+ // A commit that isn't where the head left it (on another branch, or newer): compared as it is.
+ if (FULL_SHA.test(baseRef) && cmp.merge_base_commit.sha !== baseRef) {
+ base.sha = baseRef;
+ files = (await treeDiff(token, owner, repo, baseRef, headSha)).map(changedFile);
+ }
+ title = `${base.ref} → ${head.ref}`;
+ url = cmp.html_url;
+ }
+ files = files.filter((f) => COMPARED(f.path) || COMPARED(f.previous)).map((f) => ({ path: f.path, previous: f.previous, status: f.status }));
+ return { base, head, files, title, url };
+}
+
+// ---- repositories, branches, commits, pull requests -----------------------------------
+
+async function repoOf(nwo, token = null) {
+ return repoInfo(await request(`/repos/${nwo}`, { token }));
+}
+
+/**
+ * Repositories for the gallery: signed in, exactly those the GitHub App is
+ * installed on (and the user can see); then the watched ones. `hidden` are
+ * lower-case names left out.
+ * @returns {Promise}
+ */
+async function listRepos(token, { watched = [], hidden = new Set() } = {}) {
+ const repos = new Map();
+ const add = (r) => r && !r.disabled && !hidden.has(r.nwo.toLowerCase()) && repos.set(r.nwo, r);
+ if (token) {
+ for (const inst of await pages("/user/installations", token, { key: "installations" }))
+ for (const r of await pages(`/user/installations/${inst.id}/repositories`, token, { key: "repositories" })) add(repoInfo(r));
+ }
+ for (const nwo of watched) if (!repos.has(nwo) && !hidden.has(nwo.toLowerCase())) add(await repoOf(nwo, token).catch(() => null));
+ return [...repos.values()];
+}
+
+/**
+ * Every file of a branch (one request): [{path, sha, size}], plus whether
+ * GitHub cut the listing short. An empty repository has no files.
+ */
+async function tree(nwo, ref, token = null) {
+ let t;
+ try {
+ t = await request(`/repos/${nwo}/git/trees/${encodeURIComponent(ref)}?recursive=1`, { token });
+ } catch (e) {
+ if (e.status !== 409) throw e; // 409: empty repository
+ t = { tree: [] };
+ }
+ return { files: t.tree.filter((e) => e.type === "blob").map((e) => ({ path: e.path, sha: e.sha, size: e.size ?? 0 })), truncated: !!t.truncated };
+}
+
+async function branches(owner, repo, token = null) {
+ return (await pages(`/repos/${owner}/${repo}/branches`, token, { max: 5 })).map((b) => ({ name: b.name }));
+}
+
+/** `count` commits of `ref` from `offset` (a multiple of `count`), newest first. */
+async function commits(owner, repo, ref, offset, count, token = null) {
+ const page = Math.floor(offset / count) + 1;
+ const batch = await request(`/repos/${owner}/${repo}/commits?sha=${encodeURIComponent(ref)}&per_page=${count}&page=${page}`, { token });
+ return batch.map(commitEntry);
+}
+
+/** @returns {Promise} */
+async function pullRequest(owner, repo, number, token = null) {
+ const pr = await request(`/repos/${owner}/${repo}/pulls/${number}`, { token });
+ const fork = pr.head.repo && pr.head.repo.owner.login !== owner;
+ return {
+ owner, repo,
+ number: pr.number,
+ title: pr.title,
+ body: pr.body ?? "",
+ url: pr.html_url,
+ base: { owner, repo, sha: pr.base.sha, ref: pr.base.ref },
+ // A deleted fork: the base repository still has the head's commits.
+ head: {
+ owner: pr.head.repo?.owner.login ?? owner,
+ repo: pr.head.repo?.name ?? repo,
+ sha: pr.head.sha,
+ ref: pr.head.ref,
+ label: fork ? pr.head.label : pr.head.ref, // fork branches read "owner:branch", as on GitHub
+ },
+ };
+}
+
+/** The files a pull request changes (up to `max` pages of 100). */
+async function pullFiles(owner, repo, number, token = null, { max = 30 } = {}) {
+ return (await pages(`/repos/${owner}/${repo}/pulls/${number}/files`, token, { max })).map(changedFile);
+}
+
+// ---- search (the home page's lists) --------------------------------------------------
+
+const MAX_Q = 250; // GitHub's search rejects queries over 256 characters
+
+/** `base` plus `repo:` qualifiers, split into as few queries as fit. */
+function repoQueries(base, repos) {
+ const out = [];
+ let q = base;
+ for (const r of repos) {
+ if (q !== base && q.length + r.length + 6 > MAX_Q) {
+ out.push(q);
+ q = base;
+ }
+ q += ` repo:${r}`;
+ }
+ if (q !== base) out.push(q);
+ return out;
+}
+
+async function search(queries, perPage, token) {
+ const out = [];
+ // Spelt out rather than URLSearchParams, which gjs (the tests) doesn't have.
+ for (const q of queries) out.push(...(await request(`/search/issues?q=${encodeURIComponent(q)}&sort=updated&per_page=${perPage}`, { token })).items);
+ return out.map(searchItem);
+}
+
+/**
+ * Open pull requests, most recently updated first: `{reviewRequested: true}`
+ * (waiting for the user's review), `{author: "me"}`, or `{repos: [nwo…]}`.
+ * @returns {Promise}
+ */
+function searchPullRequests(filter, token = null) {
+ if (filter.repos) return search([`is:pr is:open ${filter.repos.map((r) => `repo:${r}`).join(" ")}`], 30, token);
+ const who = filter.reviewRequested ? "review-requested:@me" : "author:@me";
+ return search([`is:pr is:open archived:false ${who}`], 30, token);
+}
+
+/**
+ * Open issues labelled `label`: `{label, assignee: "me"}`, `{label, author: "me"}`
+ * or `{label, repos: [nwo…]}` (any number of repositories).
+ * @returns {Promise}
+ */
+function searchIssues(filter, token = null) {
+ const base = `is:issue is:open archived:false label:${filter.label}`;
+ if (filter.repos) return search(repoQueries(base, filter.repos), 50, token);
+ return search([`${base} ${filter.assignee ? "assignee:@me" : "author:@me"}`], 50, token);
+}
+
+// ---- the signed-in user -----------------------------------------------------------------
+
+/** @returns {Promise<{login: string, name: string|null, id: number, avatar: string, url: string}>} */
+async function user(token) {
+ const me = await request("/user", { token });
+ return { login: me.login, name: me.name ?? null, id: me.id, avatar: me.avatar_url, url: me.html_url };
+}
+
+const NOREPLY = "kivi@users.noreply.github.com";
+
+/** The commit author when a copy has no git identity: the account, with its private e-mail. */
+async function gitAuthor(token) {
+ if (!token) return { name: "KiVi user", email: NOREPLY };
+ try {
+ const me = await user(token);
+ return { name: me.name || me.login, email: `${me.id}+${me.login}@users.noreply.github.com` };
+ } catch {
+ return { name: "KiVi user", email: NOREPLY };
+ }
+}
+
+/** Whether the GitHub App is installed anywhere this user can see; null when GitHub can't tell. */
+async function hasAppInstallation(token) {
+ try {
+ return (await request("/user/installations?per_page=1", { token })).total_count > 0;
+ } catch {
+ return null;
+ }
+}
+
+/** An avatar image at `px` pixels. */
+const avatar = (url, px) => (url ? `${url}${url.includes("?") ? "&" : "?"}s=${px}` : "");
+
+// ---- review comments on pull requests ----------------------------------------------------
+//
+// Every KiVi comment is an ordinary file-level review comment on the
+// .kicad_sch / .kicad_pcb file, so it shows up (and can be replied to and
+// resolved) on GitHub itself; what it points at travels in the body's marker
+// (../review.js). Threads are read through GraphQL (the REST API has no
+// resolved state); without signing in only public repositories can be read,
+// through REST, and resolve state is unknown. Writing always needs a sign-in.
+
+const THREADS_QUERY = `query($owner: String!, $repo: String!, $pr: Int!, $after: String) {
+ viewer { login }
+ repository(owner: $owner, name: $repo) {
+ pullRequest(number: $pr) {
+ reviewThreads(first: 50, after: $after) {
+ pageInfo { hasNextPage endCursor }
+ nodes {
+ id isResolved isOutdated path subjectType line
+ viewerCanResolve viewerCanUnresolve viewerCanReply
+ resolvedBy { login }
+ comments(first: 100) {
+ nodes { databaseId body createdAt url viewerDidAuthor author { login avatarUrl } }
+ }
+ }
+ }
+ }
+ }
+}`;
+
+const CLOSING_QUERY = `query($owner: String!, $repo: String!, $pr: Int!) {
+ repository(owner: $owner, name: $repo) {
+ pullRequest(number: $pr) { closingIssuesReferences(first: 50) { nodes { number repository { nameWithOwner } } } }
+ }
+}`;
+
+/** A pull request's review threads (the ReviewThreads interface of ./index.js). */
+export class GitHubReviews {
+ /** @param {{owner: string, repo: string, pr: number, token?: string|null, fetch?: Function}} o */
+ constructor({ owner, repo, pr, token = null, fetch: fetchFn = null }) {
+ this.owner = owner;
+ this.repo = repo;
+ this.pr = pr;
+ this.token = token;
+ this.fetch = fetchFn;
+ this.threads = [];
+ this.viewer = null;
+ this.writeWhat = "pull requests"; // what a refused write needs access to
+ }
+
+ get canWrite() {
+ return !!this.token;
+ }
+
+ request(method, path, body) {
+ return request(path, { method, body, token: this.token, fetch: this.fetch, writeHint: this.writeWhat });
+ }
+
+ async graphql(query, variables) {
+ const data = await this.request("POST", "/graphql", { query, variables });
+ if (data.errors?.length) {
+ const e = data.errors[0];
+ const err = new Error(`GitHub: ${e.message}`);
+ err.type = e.type;
+ throw err;
+ }
+ return data.data;
+ }
+
+ /** Load all threads. */
+ async load() {
+ this.threads = this.token ? await this.loadGraphql() : await this.loadRest();
+ return this.threads;
+ }
+
+ async loadGraphql() {
+ const out = [];
+ let after = null;
+ for (let page = 0; page < 40; page++) {
+ const d = await this.graphql(THREADS_QUERY, { owner: this.owner, repo: this.repo, pr: this.pr, after });
+ this.viewer = d.viewer?.login ?? null;
+ const rt = d.repository?.pullRequest?.reviewThreads;
+ if (!rt) break;
+ for (const n of rt.nodes) {
+ const comments = n.comments.nodes.map((c) => comment(c.databaseId, c.body, c.author?.login, c.author?.avatarUrl, c.createdAt, c.url, c.viewerDidAuthor));
+ if (!comments.length) continue;
+ out.push({
+ id: n.id,
+ rootId: comments[0].id,
+ path: n.path,
+ line: n.line,
+ isResolved: n.isResolved,
+ isOutdated: n.isOutdated,
+ resolvedBy: n.resolvedBy?.login ?? null,
+ canResolve: n.viewerCanResolve,
+ canUnresolve: n.viewerCanUnresolve,
+ canReply: n.viewerCanReply,
+ anchor: comments[0].anchor,
+ comments,
+ });
+ }
+ if (!rt.pageInfo.hasNextPage) break;
+ after = rt.pageInfo.endCursor;
+ }
+ return out;
+ }
+
+ /** Read-only fallback: REST comments grouped into threads, resolve state unknown. */
+ async loadRest() {
+ const all = [];
+ for (let page = 1; page <= 30; page++) {
+ const batch = await this.request("GET", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}/comments?per_page=100&page=${page}`);
+ all.push(...batch);
+ if (batch.length < 100) break;
+ }
+ const roots = new Map();
+ for (const c of all) {
+ if (c.in_reply_to_id) continue;
+ const cm = comment(c.id, c.body, c.user?.login, c.user?.avatar_url, c.created_at, c.html_url, false);
+ roots.set(c.id, { id: null, rootId: c.id, path: c.path, line: c.line ?? null, isResolved: null, isOutdated: c.position === null && c.subject_type !== "file", resolvedBy: null, canResolve: false, canUnresolve: false, canReply: false, anchor: cm.anchor, comments: [cm] });
+ }
+ for (const c of all) {
+ if (!c.in_reply_to_id) continue;
+ roots.get(c.in_reply_to_id)?.comments.push(comment(c.id, c.body, c.user?.login, c.user?.avatar_url, c.created_at, c.html_url, false));
+ }
+ return [...roots.values()];
+ }
+
+ /** Start a thread on `path` at `commitId` (the head commit the anchor was placed on). */
+ async create({ path, commitId, anchor, text }) {
+ return this.request("POST", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}/comments`, {
+ body: encodeBody(text, anchor),
+ commit_id: commitId,
+ path,
+ subject_type: "file",
+ });
+ }
+
+ /**
+ * Repository paths the pull request changes: GitHub takes review comments
+ * only on these ("path could not be resolved" on any other file).
+ * @returns {Promise>}
+ */
+ async changedFiles() {
+ const out = new Set();
+ for (let page = 1; ; page++) {
+ const batch = await this.request("GET", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}/files?per_page=100&page=${page}`);
+ for (const f of batch) out.add(f.filename);
+ if (batch.length < 100) return out;
+ }
+ }
+
+ async reply(thread, text) {
+ return this.request("POST", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}/comments/${thread.rootId}/replies`, { body: text.trim() });
+ }
+
+ async setResolved(thread, resolved) {
+ if (!thread.id) throw new Error("Resolving needs a GitHub token");
+ const op = resolved ? "resolveReviewThread" : "unresolveReviewThread";
+ const d = await this.graphql(`mutation($id: ID!) { ${op}(input: {threadId: $id}) { thread { id isResolved } } }`, { id: thread.id });
+ thread.isResolved = d[op].thread.isResolved;
+ return thread;
+ }
+
+ async remove(commentId) {
+ await this.request("DELETE", `/repos/${this.owner}/${this.repo}/pulls/comments/${commentId}`);
+ }
+
+ /**
+ * Issues of this repository the pull request closes when merged: GitHub's
+ * own list signed in (keywords and manual links), else the closing keywords
+ * of its description ("Fixes #12").
+ * @returns {Promise>}
+ */
+ async closingIssues() {
+ if (this.token) {
+ const d = await this.graphql(CLOSING_QUERY, { owner: this.owner, repo: this.repo, pr: this.pr });
+ const nwo = `${this.owner}/${this.repo}`.toLowerCase();
+ const nodes = d.repository?.pullRequest?.closingIssuesReferences?.nodes ?? [];
+ return new Set(nodes.filter((n) => n.repository?.nameWithOwner?.toLowerCase() === nwo).map((n) => n.number));
+ }
+ const pr = await this.request("GET", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}`);
+ return closingNumbers(pr.body);
+ }
+
+ /** Make the pull request close issue `n` when merged: "Fixes #n" at the end of its description. */
+ async addClosingIssue(n) {
+ const pr = await this.request("GET", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}`); // the description as it is now
+ const body = String(pr.body ?? "").trimEnd();
+ if (closingNumbers(body).has(n)) return;
+ await this.request("PATCH", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}`, { body: `${body ? `${body}\n\n` : ""}Fixes #${n}` });
+ }
+}
+
+// ---- change requests (issues labelled "kivi") ------------------------------------------
+//
+// Signed in, one GraphQL request reads issues with their comments; signed out,
+// REST reads the issues of public repositories and each one's comments when
+// it's opened (`repliesPending`, `loadReplies`).
+
+const ISSUES_QUERY = `query($owner: String!, $repo: String!, $label: String!, $after: String) {
+ viewer { login }
+ repository(owner: $owner, name: $repo) {
+ issues(first: 50, after: $after, labels: [$label], orderBy: {field: CREATED_AT, direction: ASC}) {
+ pageInfo { hasNextPage endCursor }
+ nodes {
+ id number title body state createdAt url locked viewerCanUpdate viewerDidAuthor author { login avatarUrl }
+ comments(first: 100) {
+ nodes { databaseId body createdAt url viewerDidAuthor author { login avatarUrl } }
+ }
+ }
+ }
+ }
+}`;
+
+/** A repository's KiVi issues as threads (the ReviewThreads interface of ./index.js, plus `loadReplies`). */
+export class GitHubIssues extends GitHubReviews {
+ /** @param {{owner: string, repo: string, token?: string|null, fetch?: Function}} o */
+ constructor(o) {
+ super({ ...o, pr: null });
+ this.writeWhat = "issues";
+ }
+
+ async loadGraphql() {
+ const out = [];
+ let after = null;
+ for (let page = 0; page < 40; page++) {
+ const d = await this.graphql(ISSUES_QUERY, { owner: this.owner, repo: this.repo, label: ISSUE_LABEL, after });
+ this.viewer = d.viewer?.login ?? null;
+ const conn = d.repository?.issues;
+ if (!conn) break;
+ for (const n of conn.nodes) {
+ // The issue itself can't be deleted from here, so it's never "mine" to delete.
+ const root = comment(n.number, n.body, n.author?.login, n.author?.avatarUrl, n.createdAt, n.url, false);
+ const replies = n.comments.nodes.map((c) => comment(c.databaseId, c.body, c.author?.login, c.author?.avatarUrl, c.createdAt, c.url, c.viewerDidAuthor));
+ out.push(issueThread(n.id, n.number, n.title, n.state === "CLOSED", root, replies, { canUpdate: n.viewerCanUpdate, locked: n.locked, signedIn: true }));
+ }
+ if (!conn.pageInfo.hasNextPage) break;
+ after = conn.pageInfo.endCursor;
+ }
+ return out;
+ }
+
+ /** Read-only: the issues (no pull requests) of a public repository; replies come with `loadReplies`. */
+ async loadRest() {
+ const out = [];
+ for (let page = 1; page <= 30; page++) {
+ const batch = await this.request("GET", `/repos/${this.owner}/${this.repo}/issues?labels=${ISSUE_LABEL}&state=all&sort=created&direction=asc&per_page=100&page=${page}`);
+ for (const it of batch) {
+ if (it.pull_request) continue;
+ const root = comment(it.number, it.body, it.user?.login, it.user?.avatar_url, it.created_at, it.html_url, false);
+ const t = issueThread(null, it.number, it.title, it.state === "closed", root, [], { signedIn: false });
+ t.repliesPending = it.comments > 0;
+ out.push(t);
+ }
+ if (batch.length < 100) break;
+ }
+ return out;
+ }
+
+ /** An issue's comments, for threads read through REST (`repliesPending`). */
+ async loadReplies(t) {
+ const all = [];
+ for (let page = 1; page <= 10; page++) {
+ const batch = await this.request("GET", `/repos/${this.owner}/${this.repo}/issues/${t.rootId}/comments?per_page=100&page=${page}`);
+ all.push(...batch);
+ if (batch.length < 100) break;
+ }
+ t.comments = [t.comments[0], ...all.map((c) => comment(c.id, c.body, c.user?.login, c.user?.avatar_url, c.created_at, c.html_url, false))];
+ t.repliesPending = false;
+ return t;
+ }
+
+ /**
+ * Open an issue on `path` (repository path) at `commit`, labelled "kivi".
+ * @returns {Promise<{id: number, labelled: boolean, url: string}>} labelled: GitHub drops the
+ * label for people without write access, and KiVi then can't list the issue
+ */
+ async create({ path, commitId, anchor, text, title }) {
+ await this.ensureLabel();
+ const issue = await this.request("POST", `/repos/${this.owner}/${this.repo}/issues`, {
+ title: title.trim(),
+ body: encodeBody(text.trim() || "_No description._", { ...anchor, file: path, ...(commitId && { commit: commitId }) }),
+ labels: [ISSUE_LABEL],
+ });
+ return { id: issue.number, labelled: (issue.labels ?? []).some((l) => (l.name ?? l) === ISSUE_LABEL), url: issue.html_url };
+ }
+
+ /** Create the label once per repository (422 = it exists; 403 = no write access, the label is dropped). */
+ async ensureLabel() {
+ try {
+ await this.request("POST", `/repos/${this.owner}/${this.repo}/labels`, { name: ISSUE_LABEL, color: LABEL_COLOUR, description: LABEL_DESCRIPTION });
+ } catch (e) {
+ if (e.status !== 422 && e.status !== 403 && e.status !== 404) throw e;
+ }
+ }
+
+ async reply(t, text) {
+ return this.request("POST", `/repos/${this.owner}/${this.repo}/issues/${t.rootId}/comments`, { body: text.trim() });
+ }
+
+ /** Resolved = closed as completed; unresolving reopens it. */
+ async setResolved(t, resolved) {
+ const issue = await this.request("PATCH", `/repos/${this.owner}/${this.repo}/issues/${t.rootId}`, resolved ? { state: "closed", state_reason: "completed" } : { state: "open", state_reason: "reopened" });
+ t.isResolved = issue.state === "closed";
+ return t;
+ }
+
+ async remove(commentId) {
+ await this.request("DELETE", `/repos/${this.owner}/${this.repo}/issues/comments/${commentId}`);
+ }
+}
+
+// ---- the forge ------------------------------------------------------------------------
+
+/** @type {import("./index.js").Forge} */
+export const github = {
+ id: "github",
+ name: "GitHub",
+ host: "github.com",
+ hashKey: "gh", // index.html#gh=owner/repo@ref:dir, diff.html#gh=owner/repo&pr=…
+
+ parseSpec,
+ /** Whether an http(s) address is on this forge (a 3D model source may be any URL). */
+ ownsUrl: (url) => /^https?:\/\/(www\.)?github\.com\//i.test(url),
+
+ open,
+ source: (o) => new GitHubSource(o),
+ repo: repoOf,
+ listRepos,
+ tree,
+ branches,
+ commits,
+ compare,
+ pullRequest,
+ pullFiles,
+ searchPullRequests,
+ searchIssues,
+
+ reviews: (o) => new GitHubReviews(o),
+ issues: (o) => new GitHubIssues(o),
+
+ user,
+ gitAuthor,
+ avatar,
+ hasAppInstallation,
+
+ /** github.com pages KiVi links to. */
+ web: {
+ repo: (nwo) => `${WEB}/${nwo}`,
+ /** A folder of a branch (no branch: the repository's front page). */
+ tree: (nwo, branch = null, dir = "") => `${WEB}/${nwo}${branch ? `/tree/${encPath(branch)}${dir ? `/${encPath(dir)}` : ""}` : ""}`,
+ /** Where a pushed branch's pull request is opened. */
+ compare: (nwo, branch) => `${WEB}/${nwo}/compare/${encodeURIComponent(branch)}?expand=1`,
+ newRepo: `${WEB}/new`,
+ newApp: `${WEB}/settings/apps/new`,
+ /** The GitHub App's install / repository access page. */
+ appInstall: (slug) => `${WEB}/apps/${encodeURIComponent(slug)}/installations/new`,
+ },
+};
diff --git a/src/forge/index.js b/src/forge/index.js
new file mode 100644
index 0000000..88978b3
--- /dev/null
+++ b/src/forge/index.js
@@ -0,0 +1,163 @@
+// Forges: the code hosts KiVi reads projects from and keeps reviews on. Each
+// forge is one adapter module (./github.js) that makes all of that host's
+// requests and returns the forge-neutral shapes described here; the rest of
+// the app only talks to a forge object. A new forge (GitLab, Gitea, …) is a new
+// adapter implementing `Forge`, added to FORGES.
+//
+// Repositories are named "owner/repo" (`nwo`) within their forge. Tokens are
+// passed in by the caller (the pages keep them in settings).
+
+import { github } from "./github.js";
+
+/** Every forge KiVi knows, the default first. */
+export const FORGES = [github];
+
+/** The forge with this id ("github"); the default without one. */
+export function forge(id = FORGES[0].id) {
+ const f = FORGES.find((x) => x.id === id);
+ if (!f) throw new Error(`Unknown forge "${id}"`);
+ return f;
+}
+
+/** The forge whose URL hash parameter (`gh=`) a page's hash carries, with its value, or null. */
+export function forgeInHash(params) {
+ for (const f of FORGES) if (params.get(f.hashKey)) return { forge: f, value: params.get(f.hashKey) };
+ return null;
+}
+
+/**
+ * A repository spec typed by the user: an http(s) address goes to the forge
+ * that owns it; a shorthand ("owner/repo@ref:dir") to the default forge.
+ * @returns {{forge: Forge, spec: RepoSpec} | null}
+ */
+export function parseRepoSpec(text) {
+ text = String(text ?? "").trim();
+ const url = /^https?:\/\//i.test(text);
+ for (const f of FORGES) {
+ if (url && !f.ownsUrl(text)) continue;
+ const spec = f.parseSpec(text);
+ if (spec) return { forge: f, spec };
+ if (!url) break; // shorthands belong to the default forge
+ }
+ return null;
+}
+
+/**
+ * @typedef {object} RepoSpec a parsed repository address
+ * @property {string} owner
+ * @property {string} repo
+ * @property {string|null} [ref] branch, tag or commit
+ * @property {string} [path] folder or file inside
+ * @property {string|null} rest "[/]" still to be split (refs may hold "/")
+ *
+ * @typedef {object} Source files of a repository at one commit (see ../project.js)
+ * @property {string} kind the forge id
+ * @property {Forge} forge
+ * @property {string} owner
+ * @property {string} repo
+ * @property {string} ref what the user asked for (branch, tag, commit)
+ * @property {string|null} sha the commit, when known
+ * @property {string|null} [commit] an earlier commit picked in the history menu
+ * @property {string} path folder or file the user pointed at
+ * @property {string} dir folder the listing is restricted to
+ * @property {string} label
+ * @property {() => Promise} list
+ * @property {(path: string) => Promise} readText
+ * @property {(path: string) => Promise} readBinary
+ * @property {(path: string) => string|null} url a fetchable URL (public files), else null
+ *
+ * @typedef {object} RepoInfo
+ * @property {string} nwo "owner/repo", in the forge's own case
+ * @property {string} defaultBranch
+ * @property {string} pushedAt ISO time of the last push (cache key)
+ * @property {boolean} private
+ * @property {boolean} archived
+ * @property {boolean} disabled
+ * @property {string} url its web page
+ *
+ * @typedef {object} CommitRef one side of a comparison
+ * @property {string} owner
+ * @property {string} repo
+ * @property {string|null} sha null: nothing (a first commit's parent)
+ * @property {string} ref label: branch, or short SHA
+ *
+ * @typedef {object} ChangedFile
+ * @property {string} path
+ * @property {string} previous path before (a rename), else `path`
+ * @property {string} status "added" | "removed" | "modified" | "renamed" | "copied" | "changed"
+ * @property {string|null} [patch] unified diff, when the forge lists it
+ * @property {string|null} [ref] commit `path` can be read at (a pull request's head)
+ *
+ * @typedef {object} Comparison
+ * @property {CommitRef} base
+ * @property {CommitRef} head
+ * @property {ChangedFile[]} files only files the visual diff compares
+ * @property {string} title
+ * @property {string} url the comparison's web page
+ *
+ * @typedef {object} PullRequest
+ * @property {string} owner
+ * @property {string} repo
+ * @property {number} number
+ * @property {string} title
+ * @property {string} body
+ * @property {string} url
+ * @property {CommitRef} base
+ * @property {CommitRef & {label: string}} head `owner/repo` hold the head commit (a fork);
+ * `label` names the branch for display
+ *
+ * @typedef {object} SearchItem a pull request or issue in a home page list
+ * @property {string} nwo
+ * @property {number} number
+ * @property {string} title
+ * @property {string} body
+ * @property {boolean} draft
+ * @property {string} author
+ * @property {string|null} avatar
+ * @property {string} updatedAt
+ * @property {number} comments
+ * @property {string} url
+ *
+ * @typedef {object} ReviewThreads a pull request's review threads, or a repository's
+ * KiVi issues as threads (shape in ../review.js); from `reviews()` / `issues()`
+ * @property {boolean} canWrite
+ * @property {string|null} viewer
+ * @property {() => Promise} load
+ * @property {(t: object) => Promise} [loadReplies] issues read signed out
+ * @property {(o: {path: string, commitId: string, anchor: object, text: string, title?: string}) => Promise} create
+ * @property {(t: object, text: string) => Promise} reply
+ * @property {(t: object, resolved: boolean) => Promise} setResolved
+ * @property {(commentId: number) => Promise} remove
+ * @property {() => Promise>} [changedFiles] paths that take review comments
+ * @property {() => Promise>} [closingIssues] issues merging closes
+ * @property {(n: number) => Promise} [addClosingIssue]
+ *
+ * @typedef {object} Forge
+ * @property {string} id
+ * @property {string} name for UI text ("GitHub")
+ * @property {string} host "github.com"
+ * @property {string} hashKey the pages' URL hash parameter for its repositories
+ * @property {(text: string) => RepoSpec|null} parseSpec
+ * @property {(url: string) => boolean} ownsUrl
+ * @property {(spec: string|RepoSpec, token?: string|null) => Promise} open
+ * @property {(o: {owner: string, repo: string, ref: string, sha?: string|null, path?: string, token?: string|null}) => Source} source
+ * @property {(nwo: string, token?: string|null) => Promise} repo rejects with `status` 404 when not visible
+ * @property {(token: string|null, o: {watched?: string[], hidden?: Set}) => Promise} listRepos
+ * @property {(nwo: string, ref: string, token?: string|null) => Promise<{files: {path: string, sha: string, size: number}[], truncated: boolean}>} tree
+ * @property {(owner: string, repo: string, token?: string|null) => Promise<{name: string}[]>} branches
+ * @property {(owner: string, repo: string, ref: string, offset: number, count: number, token?: string|null) => Promise<{sha: string, summary: string, author: string, time: number}[]>} commits
+ * @property {(spec: object, token?: string|null) => Promise} compare
+ * @property {(owner: string, repo: string, n: number, token?: string|null) => Promise} pullRequest
+ * @property {(owner: string, repo: string, n: number, token?: string|null, o?: {max?: number}) => Promise} pullFiles
+ * @property {(filter: {reviewRequested?: boolean, author?: "me", repos?: string[]}, token?: string|null) => Promise} searchPullRequests
+ * @property {(filter: {label: string, assignee?: "me", author?: "me", repos?: string[]}, token?: string|null) => Promise} searchIssues
+ * @property {(o: {owner: string, repo: string, pr: number, token?: string|null}) => ReviewThreads} reviews
+ * @property {(o: {owner: string, repo: string, token?: string|null}) => ReviewThreads} issues
+ * @property {(token: string) => Promise<{login: string, name: string|null, id: number, avatar: string, url: string}>} user
+ * @property {(token: string|null) => Promise<{name: string, email: string}>} gitAuthor
+ * @property {(url: string|null, px: number) => string} avatar
+ * @property {(token: string) => Promise} [hasAppInstallation]
+ * @property {{repo: (nwo: string) => string, tree: (nwo: string, branch?: string|null, dir?: string) => string,
+ * compare: (nwo: string, branch: string) => string, newRepo: string, newApp?: string,
+ * appInstall?: (slug: string) => string}} web the forge's own pages
+ */
diff --git a/src/issues.js b/src/issues.js
deleted file mode 100644
index 36d95e4..0000000
--- a/src/issues.js
+++ /dev/null
@@ -1,157 +0,0 @@
-// Hardware change requests as GitHub issues, pinned to a part, pad, net or
-// spot like review comments, but on a branch rather than in a pull request.
-//
-// A KiVi issue is an ordinary GitHub issue with the label "kivi". Its body
-// ends with the same marker as a review comment (review.js), which also says
-// which file and commit it was made on, since an issue has no file of its own:
-//
-// R12 should be 10 k: the LED is too bright.
-//
-// 📍 KiVi · footprint **R12**
-//
-//
-// Issues become threads of the same shape as review threads (rootId = the
-// issue number, resolved = closed), so review-ui.js shows both. Signed in, one
-// GraphQL request reads issues with their comments; signed out, REST reads the
-// issues of public repositories and each one's comments when it's opened.
-
-import { ReviewComments, comment, encodeBody } from "./review.js";
-
-export const ISSUE_LABEL = "kivi";
-const LABEL_COLOUR = "f0a63b"; // the brand orange
-const LABEL_DESCRIPTION = "Hardware change request pinned in KiVi";
-
-const ISSUES_QUERY = `query($owner: String!, $repo: String!, $label: String!, $after: String) {
- viewer { login }
- repository(owner: $owner, name: $repo) {
- issues(first: 50, after: $after, labels: [$label], orderBy: {field: CREATED_AT, direction: ASC}) {
- pageInfo { hasNextPage endCursor }
- nodes {
- id number title body state createdAt url locked viewerCanUpdate viewerDidAuthor author { login avatarUrl }
- comments(first: 100) {
- nodes { databaseId body createdAt url viewerDidAuthor author { login avatarUrl } }
- }
- }
- }
- }
-}`;
-
-export class IssueComments extends ReviewComments {
- /** @param {{owner: string, repo: string, token?: string|null, fetch?: Function}} o */
- constructor(o) {
- super({ ...o, pr: null });
- this.writeWhat = "issues";
- }
-
- async loadGraphql() {
- const out = [];
- let after = null;
- for (let page = 0; page < 40; page++) {
- const d = await this.graphql(ISSUES_QUERY, { owner: this.owner, repo: this.repo, label: ISSUE_LABEL, after });
- this.viewer = d.viewer?.login ?? null;
- const conn = d.repository?.issues;
- if (!conn) break;
- for (const n of conn.nodes) {
- // The issue itself can't be deleted from here, so it's never "mine" to delete.
- const root = comment(n.number, n.body, n.author?.login, n.author?.avatarUrl, n.createdAt, n.url, false);
- const replies = n.comments.nodes.map((c) => comment(c.databaseId, c.body, c.author?.login, c.author?.avatarUrl, c.createdAt, c.url, c.viewerDidAuthor));
- out.push(thread(n.id, n.number, n.title, n.state === "CLOSED", root, replies, { canUpdate: n.viewerCanUpdate, locked: n.locked, signedIn: true }));
- }
- if (!conn.pageInfo.hasNextPage) break;
- after = conn.pageInfo.endCursor;
- }
- return out;
- }
-
- /** Read-only: the issues (no pull requests) of a public repository; replies come with `loadReplies`. */
- async loadRest() {
- const out = [];
- for (let page = 1; page <= 30; page++) {
- const batch = await this.request("GET", `/repos/${this.owner}/${this.repo}/issues?labels=${ISSUE_LABEL}&state=all&sort=created&direction=asc&per_page=100&page=${page}`);
- for (const it of batch) {
- if (it.pull_request) continue;
- const root = comment(it.number, it.body, it.user?.login, it.user?.avatar_url, it.created_at, it.html_url, false);
- const t = thread(null, it.number, it.title, it.state === "closed", root, [], { signedIn: false });
- t.repliesPending = it.comments > 0;
- out.push(t);
- }
- if (batch.length < 100) break;
- }
- return out;
- }
-
- /** An issue's comments, for threads read through REST (`repliesPending`). */
- async loadReplies(t) {
- const all = [];
- for (let page = 1; page <= 10; page++) {
- const batch = await this.request("GET", `/repos/${this.owner}/${this.repo}/issues/${t.rootId}/comments?per_page=100&page=${page}`);
- all.push(...batch);
- if (batch.length < 100) break;
- }
- t.comments = [t.comments[0], ...all.map((c) => comment(c.id, c.body, c.user?.login, c.user?.avatar_url, c.created_at, c.html_url, false))];
- t.repliesPending = false;
- return t;
- }
-
- /**
- * Open an issue on `path` (repository path) at `commit`, labelled "kivi".
- * @returns {Promise<{id: number, labelled: boolean, url: string}>} labelled: GitHub drops the
- * label for people without write access, and KiVi then can't list the issue
- */
- async create({ path, commitId, anchor, text, title }) {
- await this.ensureLabel();
- const issue = await this.request("POST", `/repos/${this.owner}/${this.repo}/issues`, {
- title: title.trim(),
- body: encodeBody(text.trim() || "_No description._", { ...anchor, file: path, ...(commitId && { commit: commitId }) }),
- labels: [ISSUE_LABEL],
- });
- return { id: issue.number, labelled: (issue.labels ?? []).some((l) => (l.name ?? l) === ISSUE_LABEL), url: issue.html_url };
- }
-
- /** Create the label once per repository (422 = it exists; 403 = no write access, the label is dropped). */
- async ensureLabel() {
- try {
- await this.request("POST", `/repos/${this.owner}/${this.repo}/labels`, { name: ISSUE_LABEL, color: LABEL_COLOUR, description: LABEL_DESCRIPTION });
- } catch (e) {
- if (e.status !== 422 && e.status !== 403 && e.status !== 404) throw e;
- }
- }
-
- async reply(t, text) {
- return this.request("POST", `/repos/${this.owner}/${this.repo}/issues/${t.rootId}/comments`, { body: text.trim() });
- }
-
- /** Resolved = closed as completed; unresolving reopens it. */
- async setResolved(t, resolved) {
- const issue = await this.request("PATCH", `/repos/${this.owner}/${this.repo}/issues/${t.rootId}`, resolved ? { state: "closed", state_reason: "completed" } : { state: "open", state_reason: "reopened" });
- t.isResolved = issue.state === "closed";
- return t;
- }
-
- async remove(commentId) {
- await this.request("DELETE", `/repos/${this.owner}/${this.repo}/issues/comments/${commentId}`);
- }
-}
-
-/** An issue as a review thread (see review-ui.js); `path` is the repository path from the marker. */
-function thread(id, number, title, closed, root, replies, { canUpdate = false, locked = false, signedIn }) {
- return {
- id,
- rootId: number,
- key: `i${number}`, // unlike review threads' comment ids, so both can share a store (and a link)
- issue: true,
- number,
- title,
- path: root.anchor?.file ?? null,
- commit: root.anchor?.commit ?? null,
- line: null,
- isResolved: closed,
- isOutdated: false,
- resolvedBy: null,
- canResolve: signedIn && canUpdate && !closed,
- canUnresolve: signedIn && canUpdate && closed,
- canReply: signedIn && !locked,
- anchor: root.anchor,
- comments: [root, ...replies],
- };
-}
diff --git a/src/project.js b/src/project.js
index 8c7077d..365d588 100644
--- a/src/project.js
+++ b/src/project.js
@@ -26,6 +26,15 @@ export function joinPath(dir, rel) {
return (dir.startsWith("/") ? "/" : "") + out.join("/");
}
+/** Files a repository source lists: KiCad design files and 3D models. */
+export const SOURCE_FILES = /\.(kicad_pro|kicad_sch|kicad_pcb|kicad_wks|kicad_prl|wrl|step|stp|wrz)$/i;
+/** Files that the visual diff can show. */
+export const DIFFABLE = /\.kicad_(sch|pcb)$/i;
+/** Design rule files: the visual diff compares their rules (rules-diff.js) rather than drawing them. */
+export const RULE_FILES = /\.kicad_(pro|dru)$/i;
+/** Files a comparison keeps: drawn or rule-compared ones. */
+export const COMPARED = (path) => DIFFABLE.test(path) || RULE_FILES.test(path);
+
/** Find KiCad projects among a list of paths. */
export function findProjects(paths) {
const projects = [];
diff --git a/src/review.js b/src/review.js
index 058c880..9bcb561 100644
--- a/src/review.js
+++ b/src/review.js
@@ -1,19 +1,18 @@
-// Design review comments on pull requests, stored as GitHub review comments.
-//
-// Every KiVi comment is an ordinary file-level review comment on the
-// .kicad_sch / .kicad_pcb file, so it shows up (and can be replied to and
-// resolved) on GitHub itself. What it points at — a footprint, pad, net,
-// symbol or a bare point — travels in an HTML comment at the end of the body,
-// which GitHub doesn't render:
+// KiVi's review data, the same on every forge: what a comment or change
+// request points at (a footprint, pad, net, symbol or a bare point) travels in
+// an HTML comment at the end of its body, which forges don't render:
//
// Is this the right footprint?
//
// 📍 KiVi · footprint **U3**
//
//
-// Threads are read through GraphQL (the REST API has no resolved state);
-// without signing in only public repositories can be read, through REST, and
-// resolve state is unknown. Writing always needs a sign-in.
+// A change request (an issue labelled "kivi") carries the same marker, plus
+// the file and commit it was made on, since an issue has no file of its own.
+// Forge adapters (../forge/) read and write them and hand back threads:
+// {id, rootId, key?, path, line, isResolved, isOutdated, resolvedBy,
+// canResolve, canUnresolve, canReply, anchor, comments: [comment()…]}
+// and for issues also {issue: true, number, title, commit} (issueThread).
const MARKER = //;
const FOOTER = /\n*📍 KiVi ·[^\n]*<\/sub>[ \t]*/;
@@ -69,197 +68,6 @@ function escapeMd(s) {
return String(s).replace(/[\\`*_[\]<>|]/g, (c) => `\\${c}`);
}
-const THREADS_QUERY = `query($owner: String!, $repo: String!, $pr: Int!, $after: String) {
- viewer { login }
- repository(owner: $owner, name: $repo) {
- pullRequest(number: $pr) {
- reviewThreads(first: 50, after: $after) {
- pageInfo { hasNextPage endCursor }
- nodes {
- id isResolved isOutdated path subjectType line
- viewerCanResolve viewerCanUnresolve viewerCanReply
- resolvedBy { login }
- comments(first: 100) {
- nodes { databaseId body createdAt url viewerDidAuthor author { login avatarUrl } }
- }
- }
- }
- }
- }
-}`;
-
-export class ReviewComments {
- /**
- * @param {{owner: string, repo: string, pr: number, token?: string|null, fetch?: Function}} o
- */
- constructor({ owner, repo, pr, token = null, fetch: fetchFn = null }) {
- this.owner = owner;
- this.repo = repo;
- this.pr = pr;
- this.token = token;
- this.fetch = fetchFn ?? ((...a) => globalThis.fetch(...a));
- this.threads = [];
- this.viewer = null;
- this.writeWhat = "pull requests"; // what a refused write needs access to
- }
-
- get canWrite() {
- return !!this.token;
- }
-
- async request(method, path, body) {
- const headers = { Accept: "application/vnd.github+json" };
- if (this.token) headers.Authorization = `Bearer ${this.token}`;
- if (body) headers["Content-Type"] = "application/json";
- const r = await this.fetch(`https://api.github.com${path}`, { method, headers, body: body ? JSON.stringify(body) : undefined });
- if (r.status === 204) return null;
- const data = await r.json().catch(() => ({}));
- if (!r.ok) throw githubError(r.status, data, r.headers, this.writeWhat);
- return data;
- }
-
- async graphql(query, variables) {
- const data = await this.request("POST", "/graphql", { query, variables });
- if (data.errors?.length) {
- const e = data.errors[0];
- const err = new Error(`GitHub: ${e.message}`);
- err.type = e.type;
- throw err;
- }
- return data.data;
- }
-
- /** Load all review threads of the pull request. */
- async load() {
- this.threads = this.token ? await this.loadGraphql() : await this.loadRest();
- return this.threads;
- }
-
- async loadGraphql() {
- const out = [];
- let after = null;
- for (let page = 0; page < 40; page++) {
- const d = await this.graphql(THREADS_QUERY, { owner: this.owner, repo: this.repo, pr: this.pr, after });
- this.viewer = d.viewer?.login ?? null;
- const rt = d.repository?.pullRequest?.reviewThreads;
- if (!rt) break;
- for (const n of rt.nodes) {
- const comments = n.comments.nodes.map((c) => comment(c.databaseId, c.body, c.author?.login, c.author?.avatarUrl, c.createdAt, c.url, c.viewerDidAuthor));
- if (!comments.length) continue;
- out.push({
- id: n.id,
- rootId: comments[0].id,
- path: n.path,
- line: n.line,
- isResolved: n.isResolved,
- isOutdated: n.isOutdated,
- resolvedBy: n.resolvedBy?.login ?? null,
- canResolve: n.viewerCanResolve,
- canUnresolve: n.viewerCanUnresolve,
- canReply: n.viewerCanReply,
- anchor: comments[0].anchor,
- comments,
- });
- }
- if (!rt.pageInfo.hasNextPage) break;
- after = rt.pageInfo.endCursor;
- }
- return out;
- }
-
- /** Read-only fallback: REST comments grouped into threads, resolve state unknown. */
- async loadRest() {
- const all = [];
- for (let page = 1; page <= 30; page++) {
- const batch = await this.request("GET", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}/comments?per_page=100&page=${page}`);
- all.push(...batch);
- if (batch.length < 100) break;
- }
- const roots = new Map();
- for (const c of all) {
- if (c.in_reply_to_id) continue;
- const cm = comment(c.id, c.body, c.user?.login, c.user?.avatar_url, c.created_at, c.html_url, false);
- roots.set(c.id, { id: null, rootId: c.id, path: c.path, line: c.line ?? null, isResolved: null, isOutdated: c.position === null && c.subject_type !== "file", resolvedBy: null, canResolve: false, canUnresolve: false, canReply: false, anchor: cm.anchor, comments: [cm] });
- }
- for (const c of all) {
- if (!c.in_reply_to_id) continue;
- roots.get(c.in_reply_to_id)?.comments.push(comment(c.id, c.body, c.user?.login, c.user?.avatar_url, c.created_at, c.html_url, false));
- }
- return [...roots.values()];
- }
-
- /** Start a thread on `path` at `commitId` (the head commit the anchor was placed on). */
- async create({ path, commitId, anchor, text }) {
- return this.request("POST", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}/comments`, {
- body: encodeBody(text, anchor),
- commit_id: commitId,
- path,
- subject_type: "file",
- });
- }
-
- /**
- * Repository paths the pull request changes: GitHub takes review comments
- * only on these ("path could not be resolved" on any other file).
- * @returns {Promise>}
- */
- async changedFiles() {
- const out = new Set();
- for (let page = 1; ; page++) {
- const batch = await this.request("GET", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}/files?per_page=100&page=${page}`);
- for (const f of batch) out.add(f.filename);
- if (batch.length < 100) return out;
- }
- }
-
- async reply(thread, text) {
- return this.request("POST", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}/comments/${thread.rootId}/replies`, { body: text.trim() });
- }
-
- async setResolved(thread, resolved) {
- if (!thread.id) throw new Error("Resolving needs a GitHub token");
- const op = resolved ? "resolveReviewThread" : "unresolveReviewThread";
- const d = await this.graphql(`mutation($id: ID!) { ${op}(input: {threadId: $id}) { thread { id isResolved } } }`, { id: thread.id });
- thread.isResolved = d[op].thread.isResolved;
- return thread;
- }
-
- async remove(commentId) {
- await this.request("DELETE", `/repos/${this.owner}/${this.repo}/pulls/comments/${commentId}`);
- }
-
- /**
- * Issues of this repository the pull request closes when merged: GitHub's
- * own list signed in (keywords and manual links), else the closing keywords
- * of its description ("Fixes #12").
- * @returns {Promise>}
- */
- async closingIssues() {
- if (this.token) {
- const d = await this.graphql(CLOSING_QUERY, { owner: this.owner, repo: this.repo, pr: this.pr });
- const nwo = `${this.owner}/${this.repo}`.toLowerCase();
- const nodes = d.repository?.pullRequest?.closingIssuesReferences?.nodes ?? [];
- return new Set(nodes.filter((n) => n.repository?.nameWithOwner?.toLowerCase() === nwo).map((n) => n.number));
- }
- const pr = await this.request("GET", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}`);
- return closingNumbers(pr.body);
- }
-
- /** Make the pull request close issue `n` when merged: "Fixes #n" at the end of its description. */
- async addClosingIssue(n) {
- const pr = await this.request("GET", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}`); // the description as it is now
- const body = String(pr.body ?? "").trimEnd();
- if (closingNumbers(body).has(n)) return;
- await this.request("PATCH", `/repos/${this.owner}/${this.repo}/pulls/${this.pr}`, { body: `${body ? `${body}\n\n` : ""}Fixes #${n}` });
- }
-}
-
-const CLOSING_QUERY = `query($owner: String!, $repo: String!, $pr: Int!) {
- repository(owner: $owner, name: $repo) {
- pullRequest(number: $pr) { closingIssuesReferences(first: 50) { nodes { number repository { nameWithOwner } } } }
- }
-}`;
-
/** Issue numbers after GitHub's closing keywords in a description ("Fixes #12, closes #3"). */
export function closingNumbers(text) {
const out = new Set();
@@ -267,35 +75,39 @@ export function closingNumbers(text) {
return out;
}
+export const ISSUE_LABEL = "kivi";
+export const LABEL_COLOUR = "f0a63b"; // the brand orange
+export const LABEL_DESCRIPTION = "Hardware change request pinned in KiVi";
+
+/** An issue as a review thread (rootId = the issue number, resolved = closed); `path` is the repository path from the marker. */
+export function issueThread(id, number, title, closed, root, replies, { canUpdate = false, locked = false, signedIn }) {
+ return {
+ id,
+ rootId: number,
+ key: `i${number}`, // unlike review threads' comment ids, so both can share a store (and a link)
+ issue: true,
+ number,
+ title,
+ path: root.anchor?.file ?? null,
+ commit: root.anchor?.commit ?? null,
+ line: null,
+ isResolved: closed,
+ isOutdated: false,
+ resolvedBy: null,
+ canResolve: signedIn && canUpdate && !closed,
+ canUnresolve: signedIn && canUpdate && closed,
+ canReply: signedIn && !locked,
+ anchor: root.anchor,
+ comments: [root, ...replies],
+ };
+}
+
/** One comment of a thread, with its text and anchor decoded. */
export function comment(id, body, author, avatar, createdAt, url, mine) {
const { text, anchor } = decodeBody(body);
return { id, text, anchor, author: author ?? "ghost", avatar: avatar ?? null, createdAt, url, mine: !!mine };
}
-/**
- * One entry of a 422's `errors`: a string, or {resource, field, code} with a
- * `message` only for code "custom", so the others are spelt out
- * ("PullRequestReviewComment path invalid") instead of "[object Object]".
- * A message that doesn't name its field ("could not be resolved") gets it.
- */
-function validationError(e) {
- if (typeof e !== "object" || e === null) return String(e);
- if (e.message) return e.field && !e.message.includes(e.field) ? `${e.field} ${e.message}` : e.message;
- return [e.resource, e.field, e.code].filter(Boolean).join(" ") || JSON.stringify(e);
-}
-
-function githubError(status, data, headers, what = "pull requests") {
- let msg = data?.message || `HTTP ${status}`;
- if (status === 403 && headers?.get?.("x-ratelimit-remaining") === "0") msg = "API rate limit reached — sign in with GitHub for a higher limit";
- else if (status === 401) msg = "GitHub ended the sign-in; sign in again";
- else if (status === 403 || status === 404) msg += ` — the token needs write access to ${what}`;
- else if (status === 422 && data?.errors?.length) msg += `: ${data.errors.map(validationError).join("; ")}`;
- const err = new Error(`GitHub ${status}: ${msg}`);
- err.status = status;
- return err;
-}
-
/** Minimal, safe rendering of comment Markdown: code, bold, italics, links, line breaks. */
export function renderCommentText(text) {
const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
diff --git a/src/sources.js b/src/sources.js
index 338e6fa..caaaedf 100644
--- a/src/sources.js
+++ b/src/sources.js
@@ -1,168 +1,17 @@
-// File sources for projects: GitHub repositories (local folders are TauriSource
-// in src/desktop/tauri.js). Every source exposes: kind, label, list(),
+// What the pages share about project sources: forge sources come from the
+// forge adapters (src/forge/), local folders are TauriSource in
+// src/desktop/tauri.js. Every source exposes: kind, label, list(),
// readText(path), readBinary(path), url(path)?
+// Here: rebuilding a file's old text from a patch, and finding 3D models.
import { joinPath } from "./project.js";
+import { parseRepoSpec } from "./forge/index.js";
-const KICAD_EXT = /\.(kicad_pro|kicad_sch|kicad_pcb|kicad_wks|kicad_prl|wrl|step|stp|wrz)$/i;
-
-// ---- GitHub ----------------------------------------------------------------
-
-/**
- * Parse github.com URLs and shorthands:
- * owner/repo, owner/repo@ref, owner/repo@ref:path,
- * https://github.com/owner/repo[/tree|blob/[/]]
- * Refs containing "/" are resolved later against the API.
- */
-export function parseGitHubSpec(spec) {
- spec = spec.trim();
- let m = /^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/]+)\/([^/#?]+?)(?:\.git)?(?:\/(tree|blob)\/(.+?))?\/?(?:[?#].*)?$/.exec(spec);
- if (m) return { owner: m[1], repo: m[2], rest: m[4] ? decodeURIComponent(m[4]) : null, kind: m[3] ?? null };
- m = /^([\w.-]+)\/([\w.-]+)(?:@([^:]+))?(?::(.*))?$/.exec(spec);
- if (m) return { owner: m[1], repo: m[2], ref: m[3] ?? null, path: m[4] ?? "", rest: null };
- return null;
-}
-
-export class GitHubSource {
- constructor({ owner, repo, ref, path = "", token = null, sha = null }) {
- this.kind = "github";
- this.owner = owner;
- this.repo = repo;
- this.ref = ref;
- this.sha = sha;
- this.path = path; // sub-directory or file the user pointed at
- this.token = token;
- this.label = `${owner}/${repo}@${ref}${path ? `:${path}` : ""}`;
- this._list = null;
- }
-
- headers(extra = {}) {
- const h = { Accept: "application/vnd.github+json", ...extra };
- if (this.token) h.Authorization = `Bearer ${this.token}`;
- return h;
- }
-
- static async api(path, token) {
- const h = { Accept: "application/vnd.github+json" };
- if (token) h.Authorization = `Bearer ${token}`;
- const r = await fetch(`https://api.github.com${path}`, { headers: h });
- if (!r.ok) {
- const body = await r.json().catch(() => ({}));
- const msg = r.status === 403 && r.headers.get("x-ratelimit-remaining") === "0" ? "GitHub API rate limit reached — sign in with GitHub for a higher limit" : body.message || r.statusText;
- const err = new Error(`GitHub ${r.status}: ${msg}`);
- err.status = r.status;
- throw err;
- }
- return r.json();
- }
-
- /** Build a source from a spec, resolving the default branch and ambiguous refs. */
- static async open(spec, token = null) {
- const p = typeof spec === "string" ? parseGitHubSpec(spec) : spec;
- if (!p) throw new Error("Not a GitHub repository URL");
- let ref = p.ref, path = p.path ?? "";
- if (p.rest) {
- // "[/]" — try the longest ref that exists, shortest first is cheaper.
- const parts = p.rest.split("/");
- for (let i = 1; i <= parts.length; i++) {
- const cand = parts.slice(0, i).join("/");
- try {
- const c = await GitHubSource.api(`/repos/${p.owner}/${p.repo}/commits/${encodeURIComponent(cand)}`, token);
- ref = cand;
- path = parts.slice(i).join("/");
- return new GitHubSource({ owner: p.owner, repo: p.repo, ref, path, token, sha: c.sha });
- } catch (e) {
- if (e.status && e.status !== 404 && e.status !== 422) throw e;
- }
- }
- throw new Error(`Could not resolve branch/commit in "${p.rest}"`);
- }
- if (!ref) ref = (await GitHubSource.api(`/repos/${p.owner}/${p.repo}`, token)).default_branch;
- // "HEAD" is the default branch: show its name if
- // the API can tell (it can't for a private repository without a token, which still opens as HEAD).
- else if (ref === "HEAD") ref = (await GitHubSource.api(`/repos/${p.owner}/${p.repo}`, token).catch(() => null))?.default_branch ?? ref;
- return new GitHubSource({ owner: p.owner, repo: p.repo, ref, path, token });
- }
-
- /** Directory the listing is restricted to ("" = whole repository). */
- get dir() {
- const p = this.path.replace(/\/+$/, "");
- return KICAD_EXT.test(p) ? p.slice(0, Math.max(0, p.lastIndexOf("/"))) : p;
- }
-
- async list() {
- if (!this._list) {
- // "[:]" lists just a sub-tree, which keeps huge repositories manageable.
- const dir = this.dir;
- const rev = encodeURIComponent(this.sha ?? this.ref) + (dir ? ":" + dir.split("/").map(encodeURIComponent).join("/") : "");
- let tree;
- try {
- tree = await GitHubSource.api(`/repos/${this.owner}/${this.repo}/git/trees/${rev}?recursive=1`, this.token);
- } catch (e) {
- // The folder isn't in this commit (moved, or a mangled link): list the whole repository instead.
- if (!(dir && e.status === 404)) throw e;
- tree = await GitHubSource.api(`/repos/${this.owner}/${this.repo}/git/trees/${encodeURIComponent(this.sha ?? this.ref)}?recursive=1`, this.token);
- console.warn(`${dir} not found in ${this.ref}; listing the whole repository`);
- this.path = "";
- this.label = `${this.owner}/${this.repo}@${this.ref}`;
- }
- const listed = this.dir;
- this.truncated = !!tree.truncated;
- const paths = tree.tree.filter((e) => e.type === "blob").map((e) => (listed ? `${listed}/${e.path}` : e.path));
- this._list = paths.filter((p) => KICAD_EXT.test(p));
- }
- return this._list;
- }
-
- has(path) {
- return !!this._list?.includes(path);
- }
-
- rawUrl(path) {
- return `https://raw.githubusercontent.com/${this.owner}/${this.repo}/${encodeURIComponent(this.sha ?? this.ref)}/${path.split("/").map(encodeURIComponent).join("/")}`;
- }
-
- async fetchFile(path) {
- const rev = encodeURIComponent(this.sha ?? this.ref);
- const enc = path.split("/").map(encodeURIComponent).join("/");
- let r;
- if (this.token) {
- // Private with token: contents API with the raw media type.
- r = await fetch(`https://api.github.com/repos/${this.owner}/${this.repo}/contents/${enc}?ref=${rev}`, { headers: this.headers({ Accept: "application/vnd.github.raw" }) });
- } else {
- // Public: raw CDN (no API rate limit).
- r = await fetch(this.rawUrl(path));
- }
- if (!r.ok) throw new Error(`${path}: HTTP ${r.status}`);
- return r;
- }
-
- async readText(path) {
- const text = await (await this.fetchFile(path)).text();
- if (text.startsWith("version https://git-lfs")) throw new Error(`${path} is stored in Git LFS, which is not supported yet`);
- return text;
- }
-
- async readBinary(path) {
- return new Uint8Array(await (await this.fetchFile(path)).arrayBuffer());
- }
-
- url(path) {
- return this.token ? null : this.rawUrl(path);
- }
-}
-
-/** Files that the visual diff can show. */
-export const DIFFABLE = /\.kicad_(sch|pcb)$/i;
-/** Design rule files: the visual diff compares their rules (rules-diff.js) rather than drawing them. */
-export const RULE_FILES = /\.kicad_(pro|dru)$/i;
-const COMPARED = (path) => DIFFABLE.test(path) || RULE_FILES.test(path);
-
-const FULL_SHA = /^[0-9a-f]{40}$/i;
+export { DIFFABLE, RULE_FILES } from "./project.js";
/**
* A file's text before a change, rebuilt from its text after and the unified
- * diff GitHub lists for it (the `patch` of /pulls/N/files), so the old
+ * diff the forge lists for it (a ChangedFile's `patch`), so the old
* version needs no request of its own.
* @param {string} after
* @param {string} patch
@@ -197,79 +46,6 @@ export function textBeforePatch(after, patch) {
return out.join("\n") + (beforeNewline ? "\n" : "");
}
-/** Files that differ between two commits, from their trees (the compare API only measures from the merge base). */
-async function treeDiff(api, owner, repo, a, b) {
- const blobs = async (sha) => {
- const t = await api(`/repos/${owner}/${repo}/git/trees/${sha}?recursive=1`);
- if (t.truncated) throw new Error("Repository too large to compare these two commits directly; pick a branch as the base instead");
- return new Map(t.tree.filter((e) => e.type === "blob").map((e) => [e.path, e.sha]));
- };
- const [before, after] = await Promise.all([blobs(a), blobs(b)]);
- const files = [];
- for (const [path, sha] of after) if (before.get(path) !== sha) files.push({ filename: path, status: before.has(path) ? "modified" : "added" });
- for (const path of before.keys()) if (!after.has(path)) files.push({ filename: path, status: "removed" });
- return files;
-}
-
-/**
- * Resolve what to compare:
- * {owner, repo, pr: 42} pull request (base = merge base, like GitHub)
- * {owner, repo, commit: ""} commit against its first parent
- * {owner, repo, base: "main", head: "x"} any two refs: from where head left a base branch
- * (three-dot, like a pull request); a base commit
- * (full SHA) as it is; no base = the default branch
- * @returns {Promise<{base: object, head: object, files: object[], title: string, url: string}>}
- */
-export async function resolveComparison(spec, token = null) {
- const { owner, repo } = spec;
- const api = (p) => GitHubSource.api(p, token);
- let base, head, files, title, url;
- if (spec.pr) {
- const pr = await api(`/repos/${owner}/${repo}/pulls/${spec.pr}`);
- head = { owner: pr.head.repo?.owner.login ?? owner, repo: pr.head.repo?.name ?? repo, sha: pr.head.sha, ref: pr.head.ref };
- // Diff against the merge base so unrelated base-branch changes don't show up.
- const cmp = await api(`/repos/${owner}/${repo}/compare/${pr.base.sha}...${pr.head.sha}`).catch(() => null);
- base = { owner, repo, sha: cmp?.merge_base_commit?.sha ?? pr.base.sha, ref: pr.base.ref };
- files = [];
- for (let page = 1; page <= 30; page++) {
- const batch = await api(`/repos/${owner}/${repo}/pulls/${spec.pr}/files?per_page=100&page=${page}`);
- files.push(...batch);
- if (batch.length < 100) break;
- }
- title = `#${pr.number} ${pr.title}`;
- url = pr.html_url;
- } else if (spec.commit) {
- const c = await api(`/repos/${owner}/${repo}/commits/${encodeURIComponent(spec.commit)}`);
- head = { owner, repo, sha: c.sha, ref: c.sha.slice(0, 7) };
- const parent = c.parents[0]?.sha;
- base = { owner, repo, sha: parent ?? null, ref: parent ? parent.slice(0, 7) : "(none)" };
- files = c.files ?? [];
- title = c.commit.message.split("\n")[0];
- url = c.html_url;
- } else {
- const baseRef = spec.base || (await api(`/repos/${owner}/${repo}`)).default_branch;
- // The same branch on both sides (e.g. the viewer's Visual diff on the default branch): its latest commit.
- if (baseRef === spec.head) return resolveComparison({ owner, repo, commit: spec.head }, token);
- const cmp = await api(`/repos/${owner}/${repo}/compare/${encodeURIComponent(baseRef)}...${encodeURIComponent(spec.head)}`);
- const short = (r) => (FULL_SHA.test(r) ? r.slice(0, 7) : r);
- const headSha = cmp.commits.at(-1)?.sha ?? (FULL_SHA.test(spec.head) ? spec.head : (await api(`/repos/${owner}/${repo}/commits/${encodeURIComponent(spec.head)}`)).sha);
- base = { owner, repo, sha: cmp.merge_base_commit.sha, ref: short(baseRef) };
- head = { owner, repo, sha: headSha, ref: short(spec.head) };
- files = cmp.files ?? [];
- // A commit that isn't where the head left it (on another branch, or newer): compared as it is.
- if (FULL_SHA.test(baseRef) && cmp.merge_base_commit.sha !== baseRef) {
- base.sha = baseRef;
- files = await treeDiff(api, owner, repo, baseRef, headSha);
- }
- title = `${base.ref} → ${head.ref}`;
- url = cmp.html_url;
- }
- files = files
- .filter((f) => COMPARED(f.filename) || COMPARED(f.previous_filename ?? ""))
- .map((f) => ({ path: f.filename, previous: f.previous_filename ?? f.filename, status: f.status }));
- return { base, head, files, title, url };
-}
-
// ---- 3D model resolution -------------------------------------------------
const MODEL_EXT = /\.(wrl|step|stp)$/i;
@@ -289,15 +65,15 @@ const LOCAL_DIR = /^(\/|~([\\/]|$)|[a-z]:[\\/]|\\\\)/i;
/**
* A 3D model source from Settings: a URL prefix (e.g. a raw mirror of KiCad's
- * library), a GitHub repository (`owner/repo[@ref][:dir]` or a github.com URL),
+ * library), a forge repository (`owner/repo[@ref][:dir]` or its web address),
* or a folder on this computer such as KiCad's installed library (desktop app only).
*/
export function parseModelSource(spec) {
spec = spec.trim();
if (!spec || spec.startsWith("#")) return null;
if (LOCAL_DIR.test(spec)) return { kind: "dir", spec, path: spec };
- const gh = /^https?:\/\//i.test(spec) && !/^https?:\/\/(www\.)?github\.com\//i.test(spec) ? null : parseGitHubSpec(spec);
- if (gh) return { kind: "repo", spec, gh };
+ const repo = parseRepoSpec(spec);
+ if (repo) return { kind: "repo", spec, forge: repo.forge, repo: repo.spec };
if (/^https?:\/\//i.test(spec)) return { kind: "url", spec, base: spec.replace(/\/?$/, "/") };
return null;
}
@@ -338,7 +114,7 @@ function findByName(index, path) {
* Each candidate is `{url, format, alt}`; `alt` marks the same model in another
* format (a .step for a .wrl path), which KiCad itself wouldn't load.
* Always the project first, then folders on this computer, then web sources
- * (URL prefixes, GitHub repositories), each group in the order of the list:
+ * (URL prefixes, forge repositories), each group in the order of the list:
* ${KIPRJMOD}/x.step, relative/x.wrl → that path in the project, then by name as below
* ${KICADn_3DMODEL_DIR}/..., absolute paths from the designer's machine, other variables
* → a file with that name anywhere in the project,
@@ -347,7 +123,7 @@ function findByName(index, path) {
* path and the file name in each model source
* @param {object} source project source
* @param {string} projectDir
- * @param {string[]} modelSources URL prefixes, GitHub repositories and folders (folders go first)
+ * @param {string[]} modelSources URL prefixes, forge repositories and folders (folders go first)
* @param {{token?: string|null, onSourceError?: (spec: string, err: Error) => void,
* openDir?: (path: string) => object, pathVars?: Record}} [opts] `openDir` makes
* a source (list/readBinary) for a folder model source; without it (in a browser) folder sources
@@ -396,7 +172,7 @@ export function makeModelResolver(source, projectDir, modelSources = [], { token
const src = openDir(m.path);
return { source: src, dir: "", index: await modelIndex(src) };
}
- const src = await GitHubSource.open(m.gh, token);
+ const src = await m.forge.open(m.repo, token);
return { source: src, dir: src.dir, index: await modelIndex(src, src.dir) };
})().catch((e) => {
console.warn(`3D model source ${m.spec}: ${e.message}`);
diff --git a/tests/diff.js b/tests/diff.js
index 0ad309a..a190e57 100644
--- a/tests/diff.js
+++ b/tests/diff.js
@@ -11,6 +11,7 @@ import { diffPcb } from "../src/diff/pcb-diff.js";
import { diffRules } from "../src/diff/rules-diff.js";
import { textBeforePatch } from "../src/sources.js";
import { kicadFilesChanged } from "../src/desktop/pr-files.js";
+import { github } from "../src/forge/github.js";
import GLib from "gi://GLib";
let failures = 0;
@@ -254,13 +255,19 @@ const DEMO = kicadDemos("pic_programmer");
{ filename: "a/rules.kicad_dru", status: "modified" },
{ filename: "README.md", status: "modified" },
];
+ // Through the GitHub adapter, which turns /pulls/N/files entries into ChangedFiles (ref from contents_url).
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = async (url) => ({ ok: true, status: 200, json: async () => (/[?&]page=1(&|$)/.test(url) ? files : []) });
+ const changed = await github.pullFiles("o", "r", 1, null);
+ globalThis.fetch = realFetch;
+ check(changed[1].path === "a/rules.kicad_pro" && changed[1].ref === "c".repeat(40) && changed[0].previous === "a/x.kicad_sch", "GitHub's PR files become ChangedFiles");
const reads = [];
const read = async (path, ref) => {
reads.push([path, ref]);
if (!heads[path]) throw new Error("404");
return heads[path];
};
- const counted = (await kicadFilesChanged(files, read)).map((f) => f.filename);
+ const counted = (await kicadFilesChanged(changed, read)).map((f) => f.path);
check(counted.join() === "a/x.kicad_sch,a/rules.kicad_pro,c/big.kicad_pro,d/broken.kicad_pro,e/new.kicad_pro,a/rules.kicad_dru", `PR files counted: ${counted.join(", ")}`);
check(!counted.includes("b/cosmetic.kicad_pro"), "a .kicad_pro without rule changes doesn't count");
check(reads.every(([, ref]) => ref === "c".repeat(40)) && reads.length === 3, `only the changed .kicad_pro files are read, at the PR head (${reads.length})`);
diff --git a/tests/review.js b/tests/review.js
index e4a1e6b..8531c71 100644
--- a/tests/review.js
+++ b/tests/review.js
@@ -2,8 +2,9 @@
// comments and KiVi issues) against a mocked API, and anchor picking/relocation on demo files. gjs -m tests/review.js
import { readText, kicadDemos } from "./gjs-fs.js";
-import { encodeBody, decodeBody, anchorLabel, renderCommentText, ReviewComments, closingNumbers } from "../src/review.js";
-import { IssueComments } from "../src/issues.js";
+import { encodeBody, decodeBody, anchorLabel, renderCommentText, closingNumbers } from "../src/review.js";
+import { GitHubReviews as ReviewComments, GitHubIssues as IssueComments, github } from "../src/forge/github.js";
+import { FORGES, forge, parseRepoSpec } from "../src/forge/index.js";
import { pickPcb, locatePcb, pickSch, locateSch } from "../src/diff/anchors.js";
import { parsePcb } from "../src/pcb/model.js";
import { renderPcb } from "../src/pcb/render.js";
@@ -282,5 +283,40 @@ const DEMO = kicadDemos("pic_programmer");
check(msg === "GitHub 422: Validation Failed: pull_request_review_thread.path is missing; PullRequestReviewComment commit_id invalid; path could not be resolved; plain text reason", `422 lists every reason GitHub gave (${msg})`);
}
+// ---- the forge interface ----
+{
+ // Every member of the Forge typedef in src/forge/index.js, so an adapter can be checked against it.
+ const MEMBERS = ["id", "name", "host", "hashKey", "parseSpec", "ownsUrl", "open", "source", "repo", "listRepos", "tree", "branches", "commits", "compare", "pullRequest", "pullFiles", "searchPullRequests", "searchIssues", "reviews", "issues", "user", "gitAuthor", "avatar", "web"];
+ for (const f of FORGES) {
+ const missing = MEMBERS.filter((m) => f[m] === undefined);
+ check(!missing.length, `${f.id} implements the forge interface${missing.length ? ` (missing ${missing.join(", ")})` : ""}`);
+ check(["repo", "tree", "compare"].every((k) => typeof f.web[k] === "function") && typeof f.web.newRepo === "string", `${f.id} has its web pages`);
+ }
+ check(forge() === github && forge("github") === github, "GitHub is the default forge");
+ check(parseRepoSpec("me/models@main:3d")?.forge === github && parseRepoSpec("me/models@main:3d").spec.path === "3d", "a shorthand goes to the default forge");
+ check(parseRepoSpec("https://github.com/me/models/tree/main/3d")?.spec.rest === "main/3d", "a github.com address goes to GitHub");
+ check(parseRepoSpec("https://example.com/me/models") === null, "an address no forge owns isn't a repository");
+ check(github.source({ owner: "o", repo: "r", ref: "main" }).forge === github, "sources know their forge");
+ check(github.web.tree("o/r", "feat/x", "hw/board") === "https://github.com/o/r/tree/feat/x/hw/board" && github.web.tree("o/r") === "https://github.com/o/r", "folder pages");
+
+ // Searches: GitHub's query syntax and its 256-character limit stay in the adapter.
+ const queries = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = async (url) => {
+ queries.push(decodeURIComponent(/[?&]q=([^&]*)/.exec(url)[1]));
+ const item = { repository_url: "https://api.github.com/repos/O/R", number: queries.length, title: "t", user: { login: "u", avatar_url: "a?v=4" }, updated_at: "2026-11-01T00:00:00Z", html_url: `h${queries.length}` };
+ return { ok: true, status: 200, json: async () => ({ items: [item] }) };
+ };
+ const repos = Array.from({ length: 30 }, (_, i) => `owner${i}/repository-${i}`);
+ const found = await github.searchIssues({ label: "kivi", repos }, null);
+ const mine = await github.searchPullRequests({ reviewRequested: true }, "t");
+ globalThis.fetch = realFetch;
+ check(queries.length > 2 && queries.slice(0, -1).every((q) => q.length <= 256 && q.startsWith("is:issue is:open archived:false label:kivi repo:")), `issue searches split under GitHub's limit (${queries.length - 1} queries)`);
+ check(repos.every((r) => queries.some((q) => q.includes(` repo:${r}`))), "every repository is searched");
+ check(queries.at(-1) === "is:pr is:open archived:false review-requested:@me", "review requests query");
+ check(found[0].nwo === "O/R" && found[0].author === "u" && found[0].url === "h1" && mine[0].updatedAt === "2026-11-01T00:00:00Z", "search hits become SearchItems");
+ check(github.avatar("a?v=4", 48) === "a?v=4&s=48" && github.avatar("a", 48) === "a?s=48", "avatar sizes");
+}
+
print(failures ? `\n${failures} failure(s)` : "\nall review checks passed");
if (failures) imports.system.exit(1);