Official
git
Built-in git UI (JavaScript UI plugin).
The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/git@0.3.2
Permissions in 0.3.2
Files
pulls.ts8.3 KB
// The branch's pull request on GitHub. When the branch's upstream is on GitHub and gh is installed, gh says whether the
// branch has an open pull request (its link shows) and which branch is the default (no pull request is offered from
// it). Create Pull Request opens a form at once while an agent writes its title and description from the branch's
// commits; typing in the form stops the writing, and Open Pull Request pushes what is not pushed yet and runs
// `gh pr create`. Errors from git and gh show in their own words.
import * as Effect from "effect/Effect";
import { Notify, Plugin, Process, parse, promise } from "divergence/effect";
import type { GitStatus } from "divergence";
import { runProcess } from "../sdk/effect.ts";
import { createdPull, onGitHub, PullList, upstreamRemote } from "./github.ts";
import { makeJob } from "./job.ts";
import type { GitState, Pull, PullTarget } from "./status.ts";
import { ActionFailed } from "./writer.ts";
import type { makeWriter } from "./writer.ts";
type Writer = Effect.Success<ReturnType<typeof makeWriter>>;
// gh talks to GitHub; a call that hangs on the network ends after this long.
const GH_TIMEOUT = 60_000;
const NONE: Pull = { kind: "none" };
const offer = ({ root, remote, head, base }: PullTarget): Pull => ({ kind: "offer", root, remote, head, base });
export const makePulls = Effect.fn("Git.makePulls")(function* (
state: GitState,
writer: Writer,
git: (args: readonly string[], label?: string) => Effect.Effect<boolean>,
redraw: () => void,
) {
const process = yield* Process;
const notify = yield* Notify;
const { api } = yield* Plugin;
const scope = yield* Effect.scope;
const lookups = makeJob(scope, () => {});
const writing = makeJob(scope, (running) => {
if (state.pull.kind === "draft") state.pull = { ...state.pull, writing: running };
redraw();
});
// The workspace, branch and upstream the pull state belongs to.
let target: { readonly key: string; readonly workspaceId: string; readonly upstream: string } | null = null;
const gh = Effect.fn("Git.gh")(function* (root: string, args: readonly string[]) {
const command = `gh ${args.slice(0, 2).join(" ")}`;
const result = yield* runProcess("gh", args, { cwd: root, timeout: GH_TIMEOUT }).pipe(
Effect.scoped,
Effect.provideService(Process, process),
Effect.catchTag("TransportFailed", (error) => Effect.fail(new ActionFailed({ message: error.message }))),
);
if (result.timedOut) return yield* new ActionFailed({ message: `${command} did not answer within a minute` });
if (result.code !== 0)
return yield* new ActionFailed({ message: (result.stderr || result.stdout).trim() || `${command} failed` });
return result.stdout;
});
const lookup = Effect.fn("Git.lookupPull")(function* (workspaceId: string, upstream: string) {
const remote = upstreamRemote(upstream, yield* writer.read(workspaceId, ["remote", "-v"]));
if (!remote || !onGitHub(remote.url) || !(yield* process.which("gh")).path) return NONE;
const root = (yield* writer.read(workspaceId, ["rev-parse", "--show-toplevel"])).trim();
const [base, listed] = yield* Effect.all(
[
gh(root, ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"]),
gh(root, ["pr", "list", "--head", remote.branch, "--state", "open", "--json", "url,number", "--limit", "1"]),
],
{ concurrency: "unbounded" },
);
const json = yield* Effect.try({
try: (): unknown => JSON.parse(listed),
catch: () =>
new ActionFailed({ message: `gh pr list printed something that is not JSON: ${listed.slice(0, 200)}` }),
});
const open = (yield* parse("gh pr list", PullList, json))[0];
if (open) return { kind: "link", ...open } satisfies Pull;
const name = base.trim();
return remote.branch === name ? NONE : offer({ root, remote: remote.name, head: remote.branch, base: name });
});
const startLookup = (workspaceId: string, upstream: string) =>
lookups.start(
lookup(workspaceId, upstream).pipe(
Effect.catch((error) => Effect.succeed<Pull>({ kind: "failed", message: error.message })),
Effect.flatMap((pull) =>
Effect.sync(() => {
state.pull = pull;
redraw();
}),
),
),
);
const reset = Effect.gen(function* () {
target = null;
state.pull = NONE;
yield* lookups.stop;
yield* writing.stop;
});
/** Follows each status: a new workspace, branch or upstream drops what was shown and looks again. */
const follow = Effect.fn("Git.followPull")(function* (workspaceId: string, status: GitStatus) {
const { branch, upstream } = status;
if (!branch || !upstream) {
if (target) yield* reset;
return;
}
const key = [workspaceId, branch, upstream].join("\n");
if (key === target?.key) return;
yield* reset;
target = { key, workspaceId, upstream };
yield* startLookup(workspaceId, upstream);
});
/** Looks again for the branch on screen, keeping what shows until gh answers; a form being filled in stays. */
const recheck = Effect.suspend(() =>
target && state.pull.kind !== "draft" ? startLookup(target.workspaceId, target.upstream) : Effect.void,
);
const create = Effect.fn("Git.createPull")(function* () {
const pull = state.pull;
if (pull.kind !== "offer" || !target) return;
// The form takes over from a lookup that Refresh started, which would put the offer back over it.
yield* lookups.stop;
state.pull = { ...pull, kind: "draft", title: "", body: "", writing: false };
const written = writer.pullRequest(target.workspaceId, pull).pipe(
Effect.flatMap((text) =>
Effect.gen(function* () {
const draft = state.pull;
if (draft.kind !== "draft") return;
if (text) {
state.pull = { ...draft, ...text };
return;
}
state.pull = offer(draft);
yield* notify.warning(`The branch "${draft.head}" has no commits that are not on "${draft.base}".`);
}),
),
Effect.catch((error) => notify.error(`Could not write the pull request: ${error.message}`)),
);
yield* writing.start(written);
});
/** Typing in the form takes over from the agent. */
const edit = (field: "title" | "body", value: string) => {
const pull = state.pull;
if (pull.kind === "draft") state.pull = field === "title" ? { ...pull, title: value } : { ...pull, body: value };
return writing.stop;
};
const cancel = Effect.suspend(() => {
if (state.pull.kind === "draft") state.pull = offer(state.pull);
redraw();
return writing.stop;
});
const open = Effect.fn("Git.openPull")(function* (status: GitStatus) {
if (state.pull.kind !== "draft" || state.busy || !state.pull.title.trim()) return;
// The branch the form belongs to. When another branch comes on screen meanwhile, the form is gone and gh's link
// belongs to the branch that left, so it does not show.
const owner = target;
yield* writing.stop;
if (status.ahead && !(yield* git(["push"], "Pushing"))) return;
// The form stays editable during the push, so what goes to gh is checked again.
const draft = state.pull;
if (target !== owner || draft.kind !== "draft" || !draft.title.trim()) return;
state.busy = "Opening pull request";
redraw();
const args = ["pr", "create", "--base", draft.base, "--title", draft.title.trim(), "--body", draft.body.trim()];
const created = yield* gh(draft.root, args).pipe(
Effect.flatMap((stdout) => {
const link = createdPull(stdout);
return link
? Effect.succeed(link)
: Effect.fail(new ActionFailed({ message: `gh pr create printed no link: ${stdout.trim()}` }));
}),
Effect.catch((error) => notify.error(error.message).pipe(Effect.as(null))),
Effect.ensuring(
Effect.sync(() => {
state.busy = null;
}),
),
);
if (created && target === owner) state.pull = { kind: "link", ...created };
redraw();
});
const openLink = Effect.suspend(() => {
const pull = state.pull;
if (pull.kind !== "link") return Effect.void;
return promise("openUrl", () => api.openUrl(pull.url)).pipe(Effect.catch((error) => notify.error(error.message)));
});
return { follow, reset, recheck, create, edit, cancel, open, openLink };
});
No comments yet.