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.1
Permissions in 0.3.1
Files
actions.ts10.9 KB
// Repository commands and tab requests. Effects capture the host once in the layer.
// Diffs and files open through the divergence/tabs service when it runs.
// Command order, smart commit and the unborn-HEAD unstage fallback match the JS plugin.
import * as Effect from "effect/Effect";
import { absurd } from "effect/Function";
import { App, Host, Notify, Views } from "divergence/effect";
import type { GitStatus } from "divergence";
import { makeJob } from "./job.ts";
import { branchNames, discardPaths, groups, onBranch, pathsOf } from "./status.ts";
import type { Entry, GitState, Groups, MenuAction } from "./status.ts";
import type { makeWriter } from "./writer.ts";
export const makeActions = Effect.fn("Git.makeActions")(function* (
state: GitState,
writer: Effect.Success<ReturnType<typeof makeWriter>>,
refresh: () => Effect.Effect<void>,
redraw: () => void,
) {
const host = yield* Host;
const app = yield* App;
const notify = yield* Notify;
const views = yield* Views;
const scope = yield* Effect.scope;
// The commit message an agent writes; typing in the box stops it.
const messages = makeJob(scope, (running) => {
state.writing = running;
redraw();
});
// Repository actions are only rendered after show has set the workspace.
const workspaceId = () => state.workspaceId!;
// Commit, publish and sync are only exposed once a repository status is loaded.
const status = () => state.status!;
const git = Effect.fn("Git.run")(function* (args: readonly string[], label?: string) {
state.busy = label ?? `git ${args[0]}`;
state.confirm = null;
// An open menu would run a second command beside this one.
state.menuOpen = false;
redraw();
const success = yield* host.call("host/git.run", { workspaceId: workspaceId(), args }).pipe(
Effect.flatMap((result) =>
Effect.gen(function* () {
if (result.code !== 0)
yield* notify.error((result.stderr || result.stdout).trim() || `git ${args[0]} failed`);
return result.code === 0;
}),
),
Effect.catchTag(["HostCallFailed", "NeedsReview", "PermissionNotGranted"], (error) =>
notify.error(error.message).pipe(Effect.as(false)),
),
Effect.ensuring(
Effect.sync(() => {
state.busy = null;
}),
),
);
yield* refresh();
return success;
});
const openDiff = Effect.fn("Git.openDiff")(function* (entry: Entry) {
const staged = entry.side === "staged";
yield* host
.call("host/git.diff", {
workspaceId: workspaceId(),
path: entry.path,
origPath: staged ? entry.origPath : undefined,
staged,
// The diff tab reads the file whole and folds the unchanged lines;
// a host from before this ignores it and sends hunks.
wholeFile: true,
})
.pipe(
Effect.flatMap((result) => {
const client = state.tabs;
const id = state.workspaceId;
// Without the tabs plugin there is no detail pane; the shared
// request the baseline wrote would have had no reader either.
if (!client || !id) return Effect.void;
// Naming the side makes the tab follow the repository. A staged
// rename stays a snapshot: a later read by path alone would not
// know the old path and would show the file as added.
const live = staged && entry.origPath ? {} : { staged };
return client.open({ kind: "diff", workspaceId: id, path: entry.path, diff: result.diff, ...live }).pipe(
// A call that loses its provider on the way behaves like no
// reader, and the failure is logged.
Effect.ignore({ log: "Warn", message: "Could not open the diff in a tab" }),
);
}),
Effect.catchTag(["HostCallFailed", "NeedsReview", "PermissionNotGranted"], (error) =>
notify.error(error.message),
),
);
});
const openFile = Effect.fn("Git.openFile")((entry: Entry) => {
const client = state.tabs;
const id = state.workspaceId;
if (!client || !id) return Effect.void;
return client.open({ kind: "file", workspaceId: id, path: entry.path }).pipe(
// A call that loses its provider on the way behaves like no reader,
// and the failure is logged.
Effect.ignore({ log: "Warn", message: "Could not open the file in a tab" }),
);
});
const stage = Effect.fn("Git.stage")((entries: readonly Entry[]) =>
git(["add", "-A", "--", ...pathsOf(entries)], "Staging"),
);
const unstage = Effect.fn("Git.unstage")(function* (entries: readonly Entry[]) {
const paths = pathsOf(entries);
const result = yield* host.call("host/git.run", {
workspaceId: workspaceId(),
args: ["reset", "-q", "--", ...paths],
});
if (result.code === 0) return yield* refresh();
yield* git(["rm", "--cached", "-r", "-q", "--", ...paths], "Unstaging");
});
const discard = Effect.fn("Git.discard")(function* (entries: readonly Entry[]) {
const { tracked, untracked } = discardPaths(entries);
if (tracked.length && !(yield* git(["checkout", "--", ...tracked], "Discarding"))) return;
if (untracked.length) yield* git(["clean", "-fq", "--", ...untracked], "Discarding");
});
/** An agent writes a message for what a commit would take now; it goes into the box for the user to accept. */
const writeMessage = Effect.fn("Git.writeMessage")(function* () {
const current = status();
if (state.busy || messages.running || !current.entries.length) return;
const id = workspaceId();
yield* messages.start(
writer.commitMessage(id, current).pipe(
Effect.flatMap((message) =>
Effect.sync(() => {
state.message = message;
}),
),
Effect.catch((error) => notify.error(`Could not write a commit message: ${error.message}`)),
),
);
});
/** What the user types replaces what an agent was writing. */
const typed = (value: string) => {
state.message = value;
return messages.stop;
};
/** Commits with the message in the box; an empty box asks an agent for one instead. Resolves whether it committed. */
const commit = Effect.fn("Git.commit")(function* ({ amend = false }: { amend?: boolean } = {}) {
if (state.busy) return false;
const message = state.message.trim();
if (!message && !amend) {
yield* writeMessage();
return false;
}
const { merge, staged, changes } = groups(status());
// A clean tree has nothing to commit; Commit is disabled then, and Enter in the box does the same.
if (!amend && !merge.length && !staged.length && !changes.length) return false;
yield* messages.stop;
if (!amend && !staged.length && changes.length && !(yield* git(["add", "-A"], "Staging"))) return false;
const args = amend
? message
? ["commit", "-q", "--amend", "-m", message]
: ["commit", "-q", "--amend", "--no-edit"]
: ["commit", "-q", "-m", message];
const text = state.message;
state.message = "";
const committed = yield* git(args, "Committing");
// A failed commit gives its message back, unless the user typed a new one meanwhile.
if (!committed && !state.message) state.message = text;
redraw();
return committed;
});
const sync = Effect.fn("Git.sync")(function* () {
const current = status();
if (current.behind && !(yield* git(["pull", "--no-rebase", "--no-edit"], "Pulling"))) return;
if (current.ahead || current.behind) yield* git(["push"], "Pushing");
});
const publish = Effect.fn("Git.publish")(function* () {
if (!onBranch(status())) return yield* notify.warning("Check out a branch to push.");
const result = yield* host.call("host/git.run", { workspaceId: workspaceId(), args: ["remote"] });
const remotes = result.stdout
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
const remote = remotes.includes("origin") ? "origin" : remotes[0];
if (!remote) return yield* notify.warning("This repository has no remote to publish to.");
// onBranch has checked that git --branch named a branch.
yield* git(["push", "-u", remote, status().branch!], "Publishing");
});
const commitAndPush = Effect.fn("Git.commitAndPush")(function* () {
if (!(yield* commit())) return;
if (status().upstream) yield* git(["push"], "Pushing");
else yield* publish();
});
const openBranches = Effect.fn("Git.openBranches")(function* () {
state.branchOpen = !state.branchOpen;
state.branchQuery = "";
redraw();
if (!state.branchOpen) return;
yield* views.focus("git-branch-query");
const result = yield* host.call("host/git.run", {
workspaceId: workspaceId(),
args: ["branch", "-a", "--format=%(refname)"],
});
state.branches = result.code === 0 ? branchNames(result.stdout) : [];
redraw();
});
const checkout = Effect.fn("Git.checkout")(function* (name: string, create: boolean) {
state.branchOpen = false;
yield* git(create ? ["checkout", "-b", name] : ["checkout", name], create ? "Creating branch" : "Switching branch");
});
const menuAction = Effect.fn("Git.menuAction")(function* (action: MenuAction, current: GitStatus, grouped: Groups) {
switch (action) {
case "pull":
yield* git(["pull", "--no-rebase", "--no-edit"], "Pulling");
return;
case "push":
if (current.upstream) yield* git(["push"], "Pushing");
else yield* publish();
return;
case "fetch":
yield* git(["fetch", "--all", "--prune"], "Fetching");
return;
case "amend":
yield* commit({ amend: true });
return;
case "undo": {
// The first commit has no commit before it to go back to.
const parent = yield* host.call("host/git.run", {
workspaceId: workspaceId(),
args: ["rev-parse", "--verify", "-q", "HEAD~1"],
});
if (parent.code !== 0)
return yield* notify.warning(
"The last commit is the repository's first, so there is no commit to go back to.",
);
yield* git(["reset", "--soft", "HEAD~1"], "Undoing commit");
return;
}
case "stage-all":
yield* git(["add", "-A"], "Staging");
return;
case "unstage-all":
yield* unstage(grouped.staged);
return;
case "stash":
yield* git(["stash", "push", "--include-untracked"], "Stashing");
return;
case "pop":
yield* git(["stash", "pop"], "Popping stash");
return;
default:
return absurd(action);
}
});
const toggle = Effect.gen(function* () {
const current = yield* app.state;
yield* app.update({ shared: { rightPanel: current.shared?.rightPanel === "git" ? null : "git" } });
});
return {
git,
openDiff,
openFile,
stage,
unstage,
discard,
typed,
stopWriting: messages.stop,
commit,
commitAndPush,
sync,
publish,
openBranches,
checkout,
menuAction,
toggle,
close: app.update({ shared: { rightPanel: null } }),
};
});
No comments yet.