Lutra/ui/src/components/vcs/remote/remote.ts
danny d097558ba5 M4.10: remotes: fetch, pull, push, clone and manage remotes
Owner decision D23: Lutra runs fetch, pull (merge or rebase per the new
git.pull.mode setting), push (upstream set on the first push) and clone
through the user's git. Any HTTPS or SSH server works; sign-in stays with
git's credential helper (its own window is allowed for network calls only)
and the ssh agent. Terminal prompts stay off, ext:: is refused, and URL
userinfo is redacted in every message, progress line and remote listing.

- vcs: Call::network with a 30 min timeout, a stderr progress sink and a
  Cancel flag that kills git's process group; remote.rs with clone_repo,
  fetch, pull, push (--porcelain rejections), remotes and add/set-url/
  remove; explained refusals (rejected push, sign-in, host key, not found,
  unreachable, no upstream, local changes, conflicts).
- engine: git.fetch/pull/push/clone/cancel/remotes/remoteAdd/remoteSetUrl/
  remoteRemove, one network call at a time, gitProgress events,
  gitChanged after changes.
- ui: status-bar progress with Cancel and ahead/behind, vcs.fetch/pull/
  push/clone/manageRemotes (Git menu, no default shortcuts), Clone
  Repository and Manage Remotes dialogs; desktop pick_dir IPC.
- Tests against local bare repositories only (vcs 8, engine 3, Vitest 11)
  plus unit and property tests; docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:50:26 +01:00

486 lines
14 KiB
TypeScript

/**
* Remotes (M4.10): fetch, pull, push, clone and the list of remotes,
* through the engine's `git.*` commands (owner decision D23).
*
* - **Credentials stay with git.** Lutra never asks for a password or a
* key: HTTPS sign-in is git's credential helper's (it may open its own
* window), SSH uses the ssh agent. A failed sign-in comes back as git's
* explained message, shown in a toast.
* - **Progress:** the running call's `gitProgress` events ({@link progress})
* for the status-bar item, which offers Cancel (`git.cancel`). One
* network call runs at a time; the engine refuses a second.
* - **Fetch / pull / push:** each is a pending outcome (`runWaiting`) and
* ends in a toast: done, cancelled, or git's explained refusal. Pull
* saves every dirty buffer first, so git sees what the editor shows; a
* failed save cancels it. Push names the remote and branch, and says
* when it set the upstream.
* - **Clone:** the dialog's URL and folder go to `git.clone`; the folder
* is proposed as the chosen parent plus the repository's name from the
* URL. After the clone the project opens (`project.open`).
* - **Manage remotes:** `git.remotes` (URLs come redacted), add, change
* URL and remove; refusals stay in the dialog.
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { onEngineEvent, run, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
import { useAutosaveStore } from "../../../stores/autosave";
import { useNotificationsStore } from "../../../stores/notifications";
/** The engine's text for a cancelled call (`VcsError::Cancelled`). */
export const CANCELLED = "the Git operation was cancelled";
/** Most remotes kept from one answer. */
export const MAX_REMOTES = 1000;
/** A network operation. */
export type Operation = "fetch" | "pull" | "push" | "clone";
/** The running network call, as `gitProgress` reports it. */
export interface Progress {
/** Which call runs. */
operation: Operation;
/** The phase of git's latest line (`Receiving objects`), or "". */
phase: string;
/** Its percentage, or null. */
percent: number | null;
}
/** A configured remote, as `git.remotes` reports it. */
export interface Remote {
/** Its name. */
name: string;
/** Its URL (userinfo redacted), or "". */
fetchUrl: string;
/** Its push URL when it differs, else null. */
pushUrl: string | null;
}
/**
* Reads a `gitProgress` event; null when nothing runs or it is malformed.
*
* @param event - the untrusted event.
*/
export function toProgress(event: EngineEventPayload): Progress | null {
if (event.kind !== "gitProgress" || event.active !== true) {
return null;
}
const operation = event.operation;
if (operation !== "fetch" && operation !== "pull" && operation !== "push" && operation !== "clone") {
return null;
}
const percent =
typeof event.percent === "number" && Number.isFinite(event.percent)
? Math.min(100, Math.max(0, Math.round(event.percent)))
: null;
return {
operation,
phase: typeof event.phase === "string" ? event.phase.slice(0, 200) : "",
percent,
};
}
/**
* Reads the result of `git.remotes`; malformed entries are dropped.
*
* @param raw - untrusted.
*/
export function toRemotes(raw: unknown): Remote[] {
if (typeof raw !== "object" || raw === null) {
return [];
}
const list = (raw as Record<string, unknown>).remotes;
if (!Array.isArray(list)) {
return [];
}
const out: Remote[] = [];
for (const entry of list as unknown[]) {
if (out.length >= MAX_REMOTES) {
break;
}
if (typeof entry !== "object" || entry === null) {
continue;
}
const r = entry as Record<string, unknown>;
if (typeof r.name !== "string" || r.name === "") {
continue;
}
out.push({
name: r.name,
fetchUrl: typeof r.fetchUrl === "string" ? r.fetchUrl : "",
pushUrl: typeof r.pushUrl === "string" && r.pushUrl !== "" ? r.pushUrl : null,
});
}
return out;
}
/**
* The repository's name from a clone URL or path: the last segment
* without `.git`, or "" when there is none.
*
* @param url - `https://host/a/b.git`, `git@host:a/b.git`, `C:\repos\b`.
*/
export function repoName(url: string): string {
const trimmed = url.trim().replace(/[\\/]+$/, "");
const last = trimmed.split(/[\\/:]/).pop() ?? "";
return last.replace(/\.git$/i, "");
}
/**
* Joins a folder and a name with the folder's own separator.
*
* @param parent - an absolute folder.
* @param name - the new folder's name.
*/
export function joinPath(parent: string, name: string): string {
const sep = parent.includes("\\") && !parent.includes("/") ? "\\" : "/";
return parent.endsWith(sep) ? `${parent}${name}` : `${parent}${sep}${name}`;
}
/**
* The text of an engine error for people: the message as it is.
*
* @param message - the error message.
*/
function reasonOf(message: string): string {
return message.trim() === "" ? "?" : message.trim();
}
/** The Remotes store. */
export const useRemoteStore = defineStore("remote", () => {
const notifications = useNotificationsStore();
/** The running network call, or null. */
const progress = shallowRef<Progress | null>(null);
/** A fetch, pull, push or clone was started here and has not answered. */
const starting = ref(false);
/** Whether a network call runs. */
const busy = computed(() => starting.value || progress.value !== null);
/** Whether the clone dialog is open. */
const cloneOpen = ref(false);
/** The clone dialog's URL. */
const cloneUrl = ref("");
/** The clone dialog's target folder. */
const cloneDir = ref("");
/** Why the last clone failed, shown in the dialog. */
const cloneError = ref<string | null>(null);
/** Whether a clone runs. */
const cloning = ref(false);
/** Whether the Manage Remotes dialog is open. */
const remotesOpen = ref(false);
/** The remotes last read. */
const remotes = shallowRef<Remote[]>([]);
/** Whether `git.remotes` runs. */
const loading = ref(false);
/** Why the last remote change or read failed, shown in the dialog. */
const remotesError = ref<string | null>(null);
/** Whether a remote change runs. */
const changing = ref(false);
/** Stops listening; set while started. */
let unsubscribe: (() => void) | null = null;
/** How many holders called {@link start}. */
let holders = 0;
/**
* Follows `gitProgress`. Counted: every `start` needs a `stop`.
*/
function start(): void {
holders += 1;
if (unsubscribe === null) {
unsubscribe = onEngineEvent((event) => {
if (event.kind === "gitProgress") {
progress.value = toProgress(event);
} else if (event.kind === "projectClosed") {
remotes.value = [];
}
});
}
}
/** Stops following `gitProgress` when the last holder stops. */
function stop(): void {
holders = Math.max(0, holders - 1);
if (holders === 0) {
unsubscribe?.();
unsubscribe = null;
}
}
/**
* Runs one network command and reports its end.
*
* @param command - `git.fetch`, `git.pull`, `git.push` or `git.clone`.
* @param params - its params.
* @param failedKey - the catalog key of the failure toast.
* @returns the value, or null when it failed or was cancelled.
*/
async function network(command: string, params: JsonValue, failedKey: string): Promise<JsonValue | null> {
starting.value = true;
try {
const result = await runWaiting(command, params);
if (result.ok) {
return result.value;
}
const reason = reasonOf(result.error.message);
if (reason.toLowerCase().includes(CANCELLED.toLowerCase())) {
notifications.notify({ level: "info", messageKey: "notification.vcs.remoteCancelled" });
} else {
notifications.notify({ level: "error", messageKey: failedKey, message: reason, params: { reason } });
}
return null;
} finally {
starting.value = false;
}
}
/**
* Fetches every remote.
*
* @returns whether it succeeded.
*/
async function fetch(): Promise<boolean> {
const value = await network("git.fetch", {}, "notification.vcs.fetchFailed");
if (value === null) {
return false;
}
notifications.notify({ level: "info", messageKey: "notification.vcs.fetched" });
return true;
}
/**
* Saves every dirty buffer, then pulls the current branch's upstream
* (merge or rebase per the `git.pull.mode` setting).
*
* @returns whether it succeeded.
*/
async function pull(): Promise<boolean> {
const flushed = await useAutosaveStore().flushDirty();
if (flushed.error !== null || flushed.failed.length > 0) {
notifications.notify({ level: "warning", messageKey: "notification.vcs.pullNotSaved" });
return false;
}
const value = await network("git.pull", {}, "notification.vcs.pullFailed");
if (value === null) {
return false;
}
notifications.notify({ level: "info", messageKey: "notification.vcs.pulled" });
return true;
}
/**
* Pushes the current branch (setting its upstream on the first push).
*
* @returns whether it succeeded.
*/
async function push(): Promise<boolean> {
const value = await network("git.push", {}, "notification.vcs.pushFailed");
if (value === null) {
return false;
}
const v = typeof value === "object" && !Array.isArray(value) ? value : {};
const branch = typeof v.branch === "string" ? v.branch : "";
const remote = typeof v.remote === "string" ? v.remote : "";
notifications.notify({
level: "info",
messageKey: v.upstreamSet === true ? "notification.vcs.pushedUpstream" : "notification.vcs.pushed",
params: { branch, remote },
});
return true;
}
/**
* Stops the running network call.
*
* @returns whether one was stopped.
*/
async function cancel(): Promise<boolean> {
const result = await run("git.cancel");
return result.ok;
}
/** Opens the clone dialog with empty fields. */
function showClone(): void {
cloneUrl.value = "";
cloneDir.value = "";
cloneError.value = null;
cloneOpen.value = true;
}
/** Closes the clone dialog (a running clone goes on). */
function hideClone(): void {
cloneOpen.value = false;
}
/**
* Proposes the target folder: `parent` plus the repository's name.
*
* @param parent - the chosen parent folder.
*/
function chooseParent(parent: string): void {
const name = repoName(cloneUrl.value);
cloneDir.value = name === "" ? parent : joinPath(parent, name);
}
/**
* Clones {@link cloneUrl} into {@link cloneDir} and opens the project.
*
* @returns whether the clone succeeded.
*/
async function clone(): Promise<boolean> {
const url = cloneUrl.value.trim();
const dir = cloneDir.value.trim();
if (url === "" || dir === "") {
cloneError.value = "\u0000empty";
return false;
}
if (cloning.value || busy.value) {
return false;
}
cloning.value = true;
cloneError.value = null;
starting.value = true;
try {
const result = await runWaiting("git.clone", { url, dir });
if (!result.ok) {
const reason = reasonOf(result.error.message);
if (reason.toLowerCase().includes(CANCELLED.toLowerCase())) {
notifications.notify({ level: "info", messageKey: "notification.vcs.remoteCancelled" });
} else {
cloneError.value = reason;
}
return false;
}
const value = result.value;
const root =
typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.root === "string"
? value.root
: dir;
cloneOpen.value = false;
notifications.notify({ level: "info", messageKey: "notification.vcs.cloned", params: { dir: root } });
const opened = await run("project.open", { path: root });
if (!opened.ok) {
notifications.notifyError("project.open", opened.error);
}
return true;
} finally {
cloning.value = false;
starting.value = false;
}
}
/** Reads the remotes. */
async function loadRemotes(): Promise<void> {
loading.value = true;
const result = await runWaiting("git.remotes");
loading.value = false;
if (!result.ok) {
remotesError.value = reasonOf(result.error.message);
return;
}
remotes.value = toRemotes(result.value);
}
/**
* Opens the Manage Remotes dialog and reads the remotes.
*
* @returns when the list arrived.
*/
function showRemotes(): Promise<void> {
remotesError.value = null;
remotesOpen.value = true;
return loadRemotes();
}
/** Closes the Manage Remotes dialog. */
function hideRemotes(): void {
remotesOpen.value = false;
}
/**
* Runs one remote change and reads the list again.
*
* @param command - `git.remoteAdd`, `git.remoteSetUrl` or `git.remoteRemove`.
* @param params - its params.
* @returns null when done, else why not (also kept in {@link remotesError}).
*/
async function change(command: string, params: JsonValue): Promise<string | null> {
if (changing.value) {
return "busy";
}
changing.value = true;
try {
const result = await runWaiting(command, params);
if (!result.ok) {
remotesError.value = reasonOf(result.error.message);
return remotesError.value;
}
remotesError.value = null;
await loadRemotes();
return null;
} finally {
changing.value = false;
}
}
/**
* Adds a remote.
*
* @param name - its name; surrounding blanks are dropped.
* @param url - its URL; surrounding blanks are dropped.
*/
function addRemote(name: string, url: string): Promise<string | null> {
return change("git.remoteAdd", { name: name.trim(), url: url.trim() });
}
/**
* Changes a remote's URL.
*
* @param name - the remote.
* @param url - the new URL; surrounding blanks are dropped.
*/
function setRemoteUrl(name: string, url: string): Promise<string | null> {
return change("git.remoteSetUrl", { name, url: url.trim() });
}
/**
* Removes a remote.
*
* @param name - the remote.
*/
function removeRemote(name: string): Promise<string | null> {
return change("git.remoteRemove", { name });
}
return {
progress,
busy,
cloneOpen,
cloneUrl,
cloneDir,
cloneError,
cloning,
remotesOpen,
remotes,
loading,
remotesError,
changing,
start,
stop,
fetch,
pull,
push,
cancel,
showClone,
hideClone,
chooseParent,
clone,
loadRemotes,
showRemotes,
hideRemotes,
addRemote,
setRemoteUrl,
removeRemote,
};
});