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)}${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)}${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(`

Add a remote project

@@ -70,7 +71,7 @@ export function addRemoteProject({ inGallery, hasProjects }) { settings().token ? "" : " Signed out, only public repositories can be added." }

- +
`); @@ -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(it.title)}${it.draft ? ' draft' : ""}
    -
    ${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(`

    Link to GitHub

    -

    Adds the repository as a git remote of ${escapeHtml(p.folder)}. Nothing is uploaded until you commit and push from the project's branch menu. Use an empty repository: create one on GitHub.

    +

    Adds the repository as a git remote of ${escapeHtml(p.folder)}. Nothing is uploaded until you commit and push from the project's branch menu. Use an empty repository: create one on GitHub.

    - +
    `); @@ -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 ? `PCB3D view` : ""} Bill of materials - View on GitHub + View on ${escapeHtml(host.name)}
    ${localItems} @@ -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)}` : ``; const link = p.git ? "" : ``; 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