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>
This commit is contained in:
danny 2026-10-28 18:29:38 +01:00
parent 48b892a6d5
commit d097558ba5
36 changed files with 4426 additions and 45 deletions

View file

@ -2,13 +2,15 @@
/**
* Status bar along the bottom of the main window. Shows the product name and
* version, or the last engine error, and on the right the language server's
* progress (H3) and the Git branch (M4.5).
* progress (H3), a running fetch, pull, push or clone or the commits
* ahead and behind (M4.10), and the Git branch (M4.5).
*/
import { computed } from "vue";
import { t } from "../i18n";
import { useAppStore } from "../stores/app";
import LspProgressItem from "./problems/LspProgressItem.vue";
import BranchStatusItem from "./vcs/branches/BranchStatusItem.vue";
import RemoteStatusItem from "./vcs/remote/RemoteStatusItem.vue";
const app = useAppStore();
@ -29,6 +31,7 @@ const label = computed(() => {
>
<span>{{ label }}</span>
<LspProgressItem />
<RemoteStatusItem />
<BranchStatusItem />
</footer>
</template>

View file

@ -0,0 +1,223 @@
<script setup lang="ts">
/**
* "Clone Repository…" (M4.10): a URL field, a target folder field with
* "Browse…" (the shell's folder picker chooses the parent; the folder is
* the parent plus the repository's name, following URL edits), git's
* refusal under the fields, and Clone / Cancel. While the clone runs the
* status bar shows its progress; Cancel here stops it (`git.cancel`).
* Afterwards the cloned folder opens as the project.
*
* Any HTTPS or SSH URL works (GitHub, GitLab, Forgejo, Bitbucket, a
* self-hosted server) and so does a local path. The dialog never asks for
* a password: git's credential helper or the ssh agent signs in.
*
* Enter clones, Escape closes (a running clone goes on). The dialog is an
* exclusive modal (`commands/modals.ts`).
*/
import { computed, nextTick, ref, watch } from "vue";
import { useModalsStore } from "../../../commands/modals";
import { t } from "../../../i18n";
import { pickDir } from "../../../ipc";
import { useNotificationsStore } from "../../../stores/notifications";
import { joinPath, repoName, useRemoteStore } from "./remote";
const remote = useRemoteStore();
const modals = useModalsStore();
const notifications = useNotificationsStore();
/** The URL field. */
const urlInput = ref<HTMLInputElement | null>(null);
/** The parent folder chosen with Browse…, while the folder follows the URL. */
const parent = ref<string | null>(null);
/** The element that had the focus before the dialog opened. */
let returnFocus: HTMLElement | null = null;
/** The error under the fields, or null. */
const error = computed(() =>
remote.cloneError === null
? null
: remote.cloneError === "\u0000empty"
? t("vcs.clone.fieldsEmpty")
: remote.cloneError,
);
/** Closes the dialog. */
function close(): void {
remote.hideClone();
}
watch(
() => remote.cloneOpen,
async (isOpen) => {
if (isOpen) {
const active = document.activeElement;
returnFocus = active instanceof HTMLElement ? active : null;
parent.value = null;
modals.opened("clone", close);
await nextTick();
urlInput.value?.focus();
} else {
modals.closed("clone");
returnFocus?.focus();
returnFocus = null;
}
},
);
watch(
() => remote.cloneUrl,
(url) => {
if (parent.value !== null) {
const name = repoName(url);
remote.cloneDir = name === "" ? parent.value : joinPath(parent.value, name);
}
},
);
/** Asks the shell for the parent folder. */
async function browse(): Promise<void> {
const picked = await pickDir(t("vcs.clone.pickTitle"));
if (!picked.ok) {
notifications.notifyError("pick_dir", picked.error);
return;
}
if (picked.value === null) {
return;
}
parent.value = picked.value;
remote.chooseParent(picked.value);
}
/**
* Typing in the folder field stops it from following the URL.
*
* @param event - the input event.
*/
function onDirInput(event: Event): void {
parent.value = null;
remote.cloneDir = (event.target as HTMLInputElement).value;
}
/** Stops the running clone, or closes the dialog. */
async function cancelOrClose(): Promise<void> {
if (remote.cloning) {
await remote.cancel();
return;
}
close();
}
/**
* Enter clones, Escape closes.
*
* @param event - the key event.
*/
function onKeydown(event: KeyboardEvent): void {
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
close();
} else if (event.key === "Enter" && !event.isComposing && event.target instanceof HTMLInputElement) {
event.preventDefault();
void remote.clone();
}
}
</script>
<template>
<div
v-if="remote.cloneOpen"
class="remote-dialog"
data-test="clone-dialog"
@mousedown.self="close"
>
<div
class="remote-dialog__box"
role="dialog"
aria-modal="true"
aria-labelledby="lt-clone-title"
aria-describedby="lt-clone-hint"
@keydown="onKeydown"
>
<h2
id="lt-clone-title"
class="remote-dialog__title"
>
{{ t("vcs.clone.title") }}
</h2>
<label class="remote-dialog__field">
<span>{{ t("vcs.clone.url") }}</span>
<input
ref="urlInput"
v-model="remote.cloneUrl"
class="remote-dialog__input"
type="text"
spellcheck="false"
autocomplete="off"
:placeholder="t('vcs.clone.urlPlaceholder')"
:disabled="remote.cloning"
data-test="clone-url"
>
</label>
<label class="remote-dialog__field">
<span>{{ t("vcs.clone.dir") }}</span>
<span class="remote-dialog__row">
<input
class="remote-dialog__input"
type="text"
spellcheck="false"
autocomplete="off"
:value="remote.cloneDir"
:disabled="remote.cloning"
data-test="clone-dir"
@input="onDirInput"
>
<button
type="button"
class="remote-dialog__button"
:disabled="remote.cloning"
data-test="clone-browse"
@click="browse"
>
{{ t("vcs.clone.browse") }}
</button>
</span>
</label>
<p
id="lt-clone-hint"
class="remote-dialog__hint"
>
{{ t("vcs.clone.hint") }}
</p>
<p
v-if="error !== null"
class="remote-dialog__error"
role="alert"
data-test="clone-error"
>
{{ error }}
</p>
<div class="remote-dialog__buttons">
<button
type="button"
class="remote-dialog__button remote-dialog__button--primary"
:disabled="remote.cloning || remote.busy"
data-test="clone-run"
@click="remote.clone()"
>
{{ remote.cloning ? t("vcs.clone.running") : t("vcs.clone.run") }}
</button>
<button
type="button"
class="remote-dialog__button"
data-test="clone-cancel"
@click="cancelOrClose"
>
{{ t("common.cancel") }}
</button>
</div>
</div>
</div>
</template>
<style scoped src="./remoteDialog.css"></style>

View file

@ -0,0 +1,226 @@
<script setup lang="ts">
/**
* Status-bar item (M4.10): while a fetch, pull, push or clone runs, its
* phase and percentage from `gitProgress` and a Cancel button
* (`git.cancel`); otherwise the commits ahead of and behind the upstream
* (`↑2 ↓1`, from the shared status store), hidden when both are zero.
*
* The item supplies the UI commands of the remotes feature, so they work
* wherever the status bar is shown (none has a default shortcut):
* - `vcs.fetch`, `vcs.pull`, `vcs.push` run the engine's commands with
* toasts (see the Remotes store); enabled with a project and while no
* network call runs;
* - `vcs.clone` opens "Clone Repository…", also without a project;
* - `vcs.manageRemotes` opens "Manage Remotes…".
* It also mounts both dialogs.
*/
import { ArrowDown, ArrowUp, LoaderCircle, X } from "@lucide/vue";
import { computed, onBeforeUnmount, onMounted } from "vue";
import { useCommandsStore } from "../../../commands/store";
import { t } from "../../../i18n";
import { useVcsStatusStore } from "../../../stores/vcsStatus";
import CloneDialog from "./CloneDialog.vue";
import RemotesDialog from "./RemotesDialog.vue";
import { useRemoteStore, type Operation } from "./remote";
const remote = useRemoteStore();
const vcs = useVcsStatusStore();
const commands = useCommandsStore();
/**
* The name of a network operation for people.
*
* @param operation - the operation.
*/
function operationLabel(operation: Operation): string {
switch (operation) {
case "fetch":
return t("vcs.remote.operation.fetch");
case "pull":
return t("vcs.remote.operation.pull");
case "push":
return t("vcs.remote.operation.push");
case "clone":
return t("vcs.remote.operation.clone");
}
}
/** The running call's text, or null while none runs. */
const progressText = computed(() => {
const progress = remote.progress;
if (!progress) {
return null;
}
const operation = operationLabel(progress.operation);
if (progress.phase === "") {
return operation;
}
return progress.percent === null
? t("vcs.remote.progress", { operation, phase: progress.phase })
: t("vcs.remote.progressPercent", { operation, phase: progress.phase, percent: progress.percent });
});
/** Commits ahead of and behind the upstream, or null when in step. */
const sync = computed(() => {
const repo = vcs.snapshot?.available ? vcs.snapshot.repo : null;
if (!repo?.upstream) {
return null;
}
const ahead = repo.ahead ?? 0;
const behind = repo.behind ?? 0;
if (ahead === 0 && behind === 0) {
return null;
}
return { ahead, behind, label: t("vcs.remote.sync", { ahead, behind, upstream: repo.upstream }) };
});
/** Withdraws the command handlers; filled while mounted. */
let withdraw: (() => void)[] = [];
onMounted(() => {
remote.start();
const idle = (command: string) => (): boolean => commands.isEnabled(command) && !remote.busy;
withdraw = [
commands.provide("vcs.fetch", {
run: async () => {
await remote.fetch();
},
enabled: idle("git.fetch"),
}),
commands.provide("vcs.pull", {
run: async () => {
await remote.pull();
},
enabled: idle("git.pull"),
}),
commands.provide("vcs.push", {
run: async () => {
await remote.push();
},
enabled: idle("git.push"),
}),
commands.provide("vcs.clone", {
run: () => {
remote.showClone();
},
enabled: () => !remote.busy,
}),
commands.provide("vcs.manageRemotes", { run: () => remote.showRemotes(), enabled: idle("git.remotes") }),
];
});
onBeforeUnmount(() => {
for (const fn of withdraw) {
fn();
}
withdraw = [];
remote.stop();
});
</script>
<template>
<span
v-if="progressText !== null"
class="remote-item"
role="status"
:title="progressText"
data-test="remote-progress"
>
<LoaderCircle
class="remote-item__icon"
:size="12"
aria-hidden="true"
/>
<span class="remote-item__text">{{ progressText }}</span>
<button
type="button"
class="remote-item__cancel"
:title="t('vcs.remote.cancel')"
:aria-label="t('vcs.remote.cancel')"
data-test="remote-cancel"
@click="remote.cancel()"
>
<X
:size="12"
aria-hidden="true"
/>
</button>
</span>
<span
v-else-if="sync !== null"
class="remote-item"
:title="sync.label"
:aria-label="sync.label"
data-test="remote-sync"
>
<ArrowUp
:size="12"
aria-hidden="true"
/>{{ sync.ahead }}
<ArrowDown
:size="12"
aria-hidden="true"
/>{{ sync.behind }}
</span>
<CloneDialog />
<RemotesDialog />
</template>
<style scoped>
.remote-item {
display: inline-flex;
align-items: center;
gap: 4px;
margin-left: auto;
padding: 0 6px;
min-width: 0;
max-width: 40%;
white-space: nowrap;
}
.remote-item + :deep(.branch-item) {
margin-left: 0;
}
.remote-item__text {
overflow: hidden;
text-overflow: ellipsis;
}
.remote-item__icon {
flex: none;
animation: remote-item-spin 1.2s linear infinite;
}
@media (prefers-reduced-motion: reduce) {
.remote-item__icon {
animation: none;
}
}
@keyframes remote-item-spin {
to {
transform: rotate(360deg);
}
}
.remote-item__cancel {
display: inline-flex;
align-items: center;
padding: 0 2px;
font: inherit;
color: inherit;
background: transparent;
border: none;
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.remote-item__cancel:hover {
background: color-mix(in srgb, var(--lt-statusbar-fg) 12%, transparent);
}
.remote-item__cancel:focus-visible {
outline: 2px solid var(--lt-accent);
}
</style>

View file

@ -0,0 +1,324 @@
<script setup lang="ts">
/**
* "Manage Remotes…" (M4.10): the repository's remotes from `git.remotes`
* with their URLs (userinfo shown redacted, as the engine sends them; a
* separate push URL under it). Each row can change its URL ("Edit URL",
* then Save or Cancel) or be removed (asked once in the row). A form at the
* bottom adds a remote by name and URL. git's refusal (the name exists,
* no such remote, a bad name) shows above the buttons and the dialog
* stays.
*
* Escape cancels an open edit, else closes. The dialog is an exclusive
* modal (`commands/modals.ts`).
*/
import { nextTick, ref, watch } from "vue";
import { useModalsStore } from "../../../commands/modals";
import { t } from "../../../i18n";
import { useRemoteStore } from "./remote";
const remote = useRemoteStore();
const modals = useModalsStore();
/** The remote whose URL is edited, or null. */
const editing = ref<string | null>(null);
/** The URL typed while editing. */
const editUrl = ref("");
/** The remote asked about for removal, or null. */
const removing = ref<string | null>(null);
/** The new remote's name. */
const newName = ref("");
/** The new remote's URL. */
const newUrl = ref("");
/** The new remote's name field. */
const nameInput = ref<HTMLInputElement | null>(null);
/** The element that had the focus before the dialog opened. */
let returnFocus: HTMLElement | null = null;
/** Closes the dialog. */
function close(): void {
remote.hideRemotes();
}
watch(
() => remote.remotesOpen,
async (isOpen) => {
if (isOpen) {
const active = document.activeElement;
returnFocus = active instanceof HTMLElement ? active : null;
editing.value = null;
removing.value = null;
newName.value = "";
newUrl.value = "";
modals.opened("remotes", close);
await nextTick();
nameInput.value?.focus();
} else {
modals.closed("remotes");
returnFocus?.focus();
returnFocus = null;
}
},
);
/**
* Starts editing a remote's URL. A redacted URL is not offered as the
* starting text, so `***` never becomes the new URL by accident.
*
* @param name - the remote.
* @param url - its URL as shown.
*/
function startEdit(name: string, url: string): void {
removing.value = null;
editing.value = name;
editUrl.value = url.includes("***@") ? "" : url;
}
/** Saves the edited URL. */
async function saveEdit(): Promise<void> {
const name = editing.value;
if (name === null) {
return;
}
if (editUrl.value.trim() === "") {
remote.remotesError = t("vcs.remotes.urlEmpty");
return;
}
if ((await remote.setRemoteUrl(name, editUrl.value)) === null) {
editing.value = null;
}
}
/**
* Removes a remote after the row's question was answered.
*
* @param name - the remote.
*/
async function confirmRemove(name: string): Promise<void> {
if ((await remote.removeRemote(name)) === null) {
removing.value = null;
}
}
/** Adds the remote from the form. */
async function add(): Promise<void> {
if (newName.value.trim() === "" || newUrl.value.trim() === "") {
remote.remotesError = t("vcs.remotes.fieldsEmpty");
return;
}
if ((await remote.addRemote(newName.value, newUrl.value)) === null) {
newName.value = "";
newUrl.value = "";
}
}
/**
* Escape cancels an edit or a removal question, else closes; Enter in the
* edit field saves, in the form adds.
*
* @param event - the key event.
*/
function onKeydown(event: KeyboardEvent): void {
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
if (editing.value !== null || removing.value !== null) {
editing.value = null;
removing.value = null;
} else {
close();
}
}
}
</script>
<template>
<div
v-if="remote.remotesOpen"
class="remote-dialog"
data-test="remotes-dialog"
@mousedown.self="close"
>
<div
class="remote-dialog__box"
role="dialog"
aria-modal="true"
aria-labelledby="lt-remotes-title"
@keydown="onKeydown"
>
<h2
id="lt-remotes-title"
class="remote-dialog__title"
>
{{ t("vcs.remotes.title") }}
</h2>
<p
v-if="remote.loading && remote.remotes.length === 0"
class="remote-dialog__hint"
>
{{ t("vcs.remotes.loading") }}
</p>
<p
v-else-if="remote.remotes.length === 0"
class="remote-dialog__hint"
data-test="remotes-empty"
>
{{ t("vcs.remotes.none") }}
</p>
<ul
v-else
class="remote-dialog__list"
:aria-label="t('vcs.remotes.title')"
>
<li
v-for="r in remote.remotes"
:key="r.name"
class="remote-dialog__remote"
:data-test="`remote-${r.name}`"
>
<span class="remote-dialog__name">{{ r.name }}</span>
<template v-if="editing === r.name">
<input
v-model="editUrl"
class="remote-dialog__input"
type="text"
spellcheck="false"
autocomplete="off"
:aria-label="t('vcs.remotes.urlOf', { name: r.name })"
data-test="remote-edit-url"
@keydown.enter.prevent="saveEdit"
>
<span class="remote-dialog__actions">
<button
type="button"
class="remote-dialog__button remote-dialog__button--primary"
:disabled="remote.changing"
data-test="remote-save"
@click="saveEdit"
>
{{ t("common.save") }}
</button>
<button
type="button"
class="remote-dialog__button"
@click="editing = null"
>
{{ t("common.cancel") }}
</button>
</span>
</template>
<template v-else>
<span class="remote-dialog__urls">
<span class="remote-dialog__url">{{ r.fetchUrl }}</span>
<span
v-if="r.pushUrl !== null"
class="remote-dialog__url remote-dialog__url--push"
>{{ t("vcs.remotes.pushUrl", { url: r.pushUrl }) }}</span>
</span>
<span
v-if="removing === r.name"
class="remote-dialog__actions"
>
<span>{{ t("vcs.remotes.removeQuestion", { name: r.name }) }}</span>
<button
type="button"
class="remote-dialog__button remote-dialog__button--primary"
:disabled="remote.changing"
data-test="remote-remove-yes"
@click="confirmRemove(r.name)"
>
{{ t("vcs.remotes.remove") }}
</button>
<button
type="button"
class="remote-dialog__button"
@click="removing = null"
>
{{ t("common.cancel") }}
</button>
</span>
<span
v-else
class="remote-dialog__actions"
>
<button
type="button"
class="remote-dialog__button"
:disabled="remote.changing"
data-test="remote-edit"
@click="startEdit(r.name, r.fetchUrl)"
>
{{ t("vcs.remotes.editUrl") }}
</button>
<button
type="button"
class="remote-dialog__button"
:disabled="remote.changing"
data-test="remote-remove"
@click="removing = r.name"
>
{{ t("vcs.remotes.remove") }}
</button>
</span>
</template>
</li>
</ul>
<form
class="remote-dialog__form"
@submit.prevent="add"
>
<input
ref="nameInput"
v-model="newName"
class="remote-dialog__input remote-dialog__input--name"
type="text"
spellcheck="false"
autocomplete="off"
:placeholder="t('vcs.remotes.namePlaceholder')"
:aria-label="t('vcs.remotes.name')"
data-test="remote-new-name"
>
<input
v-model="newUrl"
class="remote-dialog__input"
type="text"
spellcheck="false"
autocomplete="off"
:placeholder="t('vcs.clone.urlPlaceholder')"
:aria-label="t('vcs.remotes.url')"
data-test="remote-new-url"
>
<button
type="submit"
class="remote-dialog__button"
:disabled="remote.changing"
data-test="remote-add"
>
{{ t("vcs.remotes.add") }}
</button>
</form>
<p class="remote-dialog__hint">
{{ t("vcs.clone.hint") }}
</p>
<p
v-if="remote.remotesError !== null"
class="remote-dialog__error"
role="alert"
data-test="remotes-error"
>
{{ remote.remotesError }}
</p>
<div class="remote-dialog__buttons">
<button
type="button"
class="remote-dialog__button remote-dialog__button--primary"
data-test="remotes-close"
@click="close"
>
{{ t("common.close") }}
</button>
</div>
</div>
</div>
</template>
<style scoped src="./remoteDialog.css"></style>

View file

@ -0,0 +1,486 @@
/**
* 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,
};
});

View file

@ -0,0 +1,149 @@
/* Shared look of the Clone Repository and Manage Remotes dialogs (M4.10). */
.remote-dialog {
position: fixed;
inset: 0;
display: flex;
align-items: flex-start;
justify-content: center;
padding-top: 10%;
background: color-mix(in srgb, var(--lt-bg) 50%, transparent);
z-index: 20;
}
.remote-dialog__box {
width: min(560px, 90vw);
display: flex;
flex-direction: column;
gap: 10px;
padding: 16px;
background: var(--lt-bg);
color: var(--lt-fg);
border: 1px solid var(--lt-border);
border-radius: 6px;
}
.remote-dialog__title {
margin: 0;
font-size: var(--lt-font-size-ui);
font-weight: 600;
}
.remote-dialog__field {
display: flex;
flex-direction: column;
gap: 4px;
}
.remote-dialog__row {
display: flex;
gap: 8px;
}
.remote-dialog__input {
flex: 1;
min-width: 0;
padding: 4px 6px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
}
.remote-dialog__hint {
margin: 0;
color: var(--lt-fg-muted);
font-size: var(--lt-font-size-small);
}
.remote-dialog__error {
margin: 0;
color: var(--lt-error);
white-space: pre-wrap;
overflow-wrap: anywhere;
max-height: 30vh;
overflow-y: auto;
}
.remote-dialog__buttons {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.remote-dialog__button {
padding: 4px 12px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
}
.remote-dialog__button--primary {
border-color: var(--lt-accent);
}
.remote-dialog__button:disabled {
color: var(--lt-fg-muted);
}
.remote-dialog__input:focus-visible,
.remote-dialog__button:focus-visible {
outline: 1px solid var(--lt-accent);
}
.remote-dialog__list {
margin: 0;
padding: 0;
list-style: none;
max-height: 40vh;
overflow-y: auto;
}
.remote-dialog__remote {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 12px;
padding: 6px 0;
border-bottom: 1px solid var(--lt-border);
}
.remote-dialog__name {
font-weight: 600;
min-width: 8ch;
}
.remote-dialog__urls {
display: flex;
flex: 1;
flex-direction: column;
min-width: 0;
}
.remote-dialog__url {
overflow-wrap: anywhere;
}
.remote-dialog__url--push {
color: var(--lt-fg-muted);
font-size: var(--lt-font-size-small);
}
.remote-dialog__actions {
display: inline-flex;
align-items: center;
gap: 6px;
margin-left: auto;
}
.remote-dialog__form {
display: flex;
gap: 8px;
}
.remote-dialog__input--name {
flex: 0 0 12ch;
}