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

@ -18,14 +18,25 @@
* but the go-to open commands closes it. So is the app menu (M3.9): any
* command but `menu.open` closes it.
* - **Navigation (M3.5):** the definition picker and the inline rename field
* are exclusive modals too. So is the branches popup (M4.5).
* are exclusive modals too. So is the branches popup (M4.5), and so are
* "Clone Repository…" and "Manage Remotes…" (M4.10).
*/
import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { useEditorStore } from "../stores/editor";
/** The exclusive modals. */
export type ModalId = "palette" | "goto" | "menu" | "settings" | "closePrompt" | "navPicker" | "rename" | "branches";
export type ModalId =
| "palette"
| "goto"
| "menu"
| "settings"
| "closePrompt"
| "navPicker"
| "rename"
| "branches"
| "clone"
| "remotes";
/** Store of the open exclusive modal. */
export const useModalsStore = defineStore("modals", () => {

View file

@ -37,9 +37,14 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", menuPath: "View/Project", defaultShortcut: "Mod+1" },
{ id: "vcs.branches", labelKey: "command.vcs.branches", menuPath: "Git/Branches…" },
{ id: "vcs.checkout", labelKey: "command.vcs.checkout" },
{ id: "vcs.clone", labelKey: "command.vcs.clone", menuPath: "Git/Clone Repository…" },
{ id: "vcs.commit", labelKey: "command.vcs.commit", menuPath: "Git/Commit…", defaultShortcut: "Mod+Alt+Shift+M" },
{ id: "vcs.fetch", labelKey: "command.vcs.fetch", menuPath: "Git/Fetch" },
{ id: "vcs.manageRemotes", labelKey: "command.vcs.manageRemotes", menuPath: "Git/Manage Remotes…" },
{ id: "vcs.newBranch", labelKey: "command.vcs.newBranch", menuPath: "Git/New Branch…" },
{ id: "vcs.openChanges", labelKey: "command.vcs.openChanges", menuPath: "Git/Changes", defaultShortcut: "Mod+Alt+Shift+G" },
{ id: "vcs.pull", labelKey: "command.vcs.pull", menuPath: "Git/Pull" },
{ id: "vcs.push", labelKey: "command.vcs.push", menuPath: "Git/Push" },
{ id: "vcs.refresh", labelKey: "command.vcs.refresh", menuPath: "Git/Refresh Changes" },
{ id: "vcs.showLog", labelKey: "command.vcs.showLog", menuPath: "Git/Log" },
{ id: "vcs.showHistory", labelKey: "command.vcs.showHistory", menuPath: "Git/Show History" },

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;
}

View file

@ -21,11 +21,16 @@
"command.unavailable": "{command} cannot run right now",
"command.vcs.branches": "Branches…",
"command.vcs.checkout": "Check Out Branch",
"command.vcs.clone": "Clone Repository…",
"command.vcs.commit": "Commit…",
"command.vcs.fetch": "Fetch",
"command.vcs.manageRemotes": "Manage Remotes…",
"command.vcs.newBranch": "New Branch…",
"command.vcs.nextChange": "Next Change",
"command.vcs.openChanges": "Changes",
"command.vcs.previousChange": "Previous Change",
"command.vcs.pull": "Pull",
"command.vcs.push": "Push",
"command.vcs.refresh": "Refresh Changes",
"command.vcs.showDiff": "Show Diff",
"command.vcs.showHistory": "Show History",
@ -161,10 +166,20 @@
"notification.vcs.checkedOut": "Checked out {branch}",
"notification.vcs.checkoutFailed": "Git did not check out {branch}: {reason}",
"notification.vcs.checkoutNotSaved": "Checkout of {branch} cancelled: not every file could be saved first.",
"notification.vcs.cloned": "Cloned into {dir}",
"notification.vcs.commitNotSaved": "Commit cancelled: not every file could be saved first.",
"notification.vcs.committed": "Committed {hash}: {summary}",
"notification.vcs.fetchFailed": "Fetch failed: {reason}",
"notification.vcs.fetched": "Fetched from every remote",
"notification.vcs.historyNoFile": "Open a file or pass a path to show its history",
"notification.vcs.newBranchFailed": "Branch {branch} was not created: {reason}",
"notification.vcs.pullFailed": "Pull failed: {reason}",
"notification.vcs.pullNotSaved": "Pull cancelled: not every file could be saved first.",
"notification.vcs.pulled": "Pulled the current branch",
"notification.vcs.pushFailed": "Push failed: {reason}",
"notification.vcs.pushed": "Pushed {branch} to {remote}",
"notification.vcs.pushedUpstream": "Pushed {branch} to {remote} and set it as the upstream",
"notification.vcs.remoteCancelled": "Git operation cancelled",
"notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}",
"notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}",
"palette.label": "Command palette",
@ -242,6 +257,10 @@
"settings.error.stringTooLong": "Enter at most {max} bytes",
"settings.git.executable.description": "Path to the git program (2.30 or newer) that Lutra runs for version control. Leave empty to use git from PATH.",
"settings.git.executable.label": "Git executable",
"settings.git.pull.mode.description": "How Pull joins the commits it fetched with your local commits: a merge (fast-forward when possible) or a rebase of your local commits on top.",
"settings.git.pull.mode.label": "Pull mode",
"settings.git.pull.mode.value.merge": "Merge",
"settings.git.pull.mode.value.rebase": "Rebase",
"settings.hint.pathAuto": "Detected automatically",
"settings.php.executable.description": "Path to the PHP executable (8.2 or newer) that runs Phpactor. Leave empty to use php from PATH.",
"settings.php.executable.label": "PHP executable",
@ -320,6 +339,16 @@
"vcs.changes.unstageAll": "Unstage all",
"vcs.changes.unstageFile": "Unstage {path}",
"vcs.checkout.invalidParams": "vcs.checkout needs a branch name (params: branch).",
"vcs.clone.browse": "Browse…",
"vcs.clone.dir": "Folder",
"vcs.clone.fieldsEmpty": "Enter a URL and a folder.",
"vcs.clone.hint": "Any HTTPS or SSH URL, or a local path. Sign-in goes through Git: its credential helper (which may open its own window) or your SSH agent. Lutra never sees your password or keys.",
"vcs.clone.pickTitle": "Choose the folder to clone into",
"vcs.clone.run": "Clone",
"vcs.clone.running": "Cloning…",
"vcs.clone.title": "Clone Repository",
"vcs.clone.url": "Repository URL",
"vcs.clone.urlPlaceholder": "https://host/owner/repo.git or git@host:owner/repo.git",
"vcs.commit.amend": "Amend",
"vcs.commit.amendButton": "Amend Commit",
"vcs.commit.button": "Commit",
@ -359,6 +388,28 @@
"vcs.log.refresh": "Reload the history",
"vcs.log.toolWindow.title": "Log",
"vcs.log.truncated": "More files changed than are listed here.",
"vcs.remote.cancel": "Cancel the Git operation",
"vcs.remote.operation.clone": "Cloning",
"vcs.remote.operation.fetch": "Fetching",
"vcs.remote.operation.pull": "Pulling",
"vcs.remote.operation.push": "Pushing",
"vcs.remote.progress": "{operation}: {phase}",
"vcs.remote.progressPercent": "{operation}: {phase} {percent}%",
"vcs.remote.sync": "{ahead} commits to push and {behind} to pull ({upstream})",
"vcs.remotes.add": "Add",
"vcs.remotes.editUrl": "Edit URL",
"vcs.remotes.fieldsEmpty": "Enter a name and a URL for the new remote.",
"vcs.remotes.loading": "Reading remotes…",
"vcs.remotes.name": "Name of the new remote",
"vcs.remotes.namePlaceholder": "Name",
"vcs.remotes.none": "This repository has no remotes yet.",
"vcs.remotes.pushUrl": "push: {url}",
"vcs.remotes.remove": "Remove",
"vcs.remotes.removeQuestion": "Remove {name}?",
"vcs.remotes.title": "Manage Remotes",
"vcs.remotes.url": "URL of the new remote",
"vcs.remotes.urlEmpty": "Enter the new URL.",
"vcs.remotes.urlOf": "URL of {name}",
"vcs.state.added": "added",
"vcs.state.conflicted": "conflicted",
"vcs.state.copied": "copied",

View file

@ -154,6 +154,17 @@ export type EngineEventPayload =
repo: unknown;
/** Always true: re-query `git.status`. */
filesChanged: unknown;
}
| {
kind: "gitProgress";
/** Whether a fetch, pull, push or clone runs; unchecked. */
active: unknown;
/** `fetch`, `pull`, `push` or `clone`; unchecked. */
operation?: unknown;
/** The phase of git's latest progress line, or the line; unchecked. */
phase?: unknown;
/** 0–100; unchecked. */
percent?: unknown;
};
/** Callback receiving engine events. */
@ -355,3 +366,20 @@ export async function pickFile(title: string): Promise<RunResult<string | null>>
return { ok: false, error: toEngineError(reason) };
}
}
/**
* Shows the native folder picker of the desktop shell (the "Browse…"
* button of "Clone Repository…").
*
* @param title - the picker's title, from the catalog.
* @returns the chosen folder's absolute path, null when the user cancelled,
* or the error the call failed with (for example outside the shell).
*/
export async function pickDir(title: string): Promise<RunResult<string | null>> {
try {
const value = await invoke<string | null>("pick_dir", { title });
return { ok: true, value: typeof value === "string" ? value : null };
} catch (reason: unknown) {
return { ok: false, error: toEngineError(reason) };
}
}

View file

@ -45,7 +45,8 @@ const usedKeys = sourceFiles(SRC).flatMap((file) =>
* `settings.list`, the `messageKey` of
* `notification` events (engine and desktop host), the keys the
* notifications store passes through a constant, and the Changes
* window's commit toasts (M4.2) and the branch toasts (M4.5), passed as
* window's commit toasts (M4.2), the branch toasts (M4.5) and the remote
* toasts (M4.10), passed as
* `messageKey`.
*/
const RUNTIME_KEYS = new Set([
@ -68,6 +69,16 @@ const RUNTIME_KEYS = new Set([
"notification.vcs.commitNotSaved",
"notification.vcs.committed",
"notification.vcs.newBranchFailed",
"notification.vcs.cloned",
"notification.vcs.fetchFailed",
"notification.vcs.fetched",
"notification.vcs.pullFailed",
"notification.vcs.pullNotSaved",
"notification.vcs.pulled",
"notification.vcs.pushFailed",
"notification.vcs.pushed",
"notification.vcs.pushedUpstream",
"notification.vcs.remoteCancelled",
"notification.settings.corrupt",
"notification.settings.corruptNotMoved",
"notification.settings.unavailable",
@ -98,6 +109,10 @@ const RUNTIME_KEYS = new Set([
"settings.editor.hover.delayMs.label",
"settings.git.executable.description",
"settings.git.executable.label",
"settings.git.pull.mode.description",
"settings.git.pull.mode.label",
"settings.git.pull.mode.value.merge",
"settings.git.pull.mode.value.rebase",
"settings.php.executable.description",
"settings.php.executable.label",
"settings.phpactor.autoDownload.description",

View file

@ -277,11 +277,16 @@ describe("AppMenu", () => {
"goto.symbolOpen",
"vcs.branches",
"vcs.openChanges",
"vcs.clone",
"vcs.commit",
"vcs.fetch",
"vcs.showLog",
"vcs.manageRemotes",
"vcs.newBranch",
"vcs.nextChange",
"vcs.previousChange",
"vcs.pull",
"vcs.push",
"vcs.refresh",
"vcs.showDiff",
"vcs.showHistory",

View file

@ -261,15 +261,18 @@ describe("CommandPalette", () => {
"vcs.branches",
"vcs.openChanges",
"vcs.checkout",
"vcs.clone",
"project.close",
"palette.open",
"vcs.commit",
"editor.complete",
"vcs.fetch",
"find.open",
"goto.classOpen",
"goto.fileOpen",
"goto.symbolOpen",
"vcs.showLog",
"vcs.manageRemotes",
"vcs.newBranch",
"vcs.nextChange",
"project.openDialog",
@ -277,6 +280,8 @@ describe("CommandPalette", () => {
"editor.parameterInfo",
"vcs.previousChange",
"problems.open",
"vcs.pull",
"vcs.push",
"editor.quickDocumentation",
"app.quit",
"vcs.refresh",

372
ui/tests/vcs/Remote.test.ts Normal file
View file

@ -0,0 +1,372 @@
/**
* Tests of the remotes feature (M4.10): reading untrusted `gitProgress`
* and `git.remotes`, the repository name and folder of a clone, the
* status-bar item (progress with Cancel, ahead/behind, hidden when in
* step), fetch / pull / push through the UI commands with their toasts
* (pull saves first, a failed save cancels it, git's explained refusal,
* a cancelled call), the Clone dialog (Browse…, the folder following the
* URL, the clone then `project.open`, git's refusal in the dialog), the
* Manage Remotes dialog (list, add, edit without the redacted URL, remove
* after asking), and the registration of the UI commands. The engine is a
* fake behind the mocked Tauri `invoke` and `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
import { useCommandsStore } from "../../src/commands/store";
import { UI_COMMANDS } from "../../src/commands/uiCommands";
import RemoteStatusItem from "../../src/components/vcs/remote/RemoteStatusItem.vue";
import { joinPath, repoName, toProgress, toRemotes, useRemoteStore } from "../../src/components/vcs/remote/remote";
import { useNotificationsStore } from "../../src/stores/notifications";
import { useVcsStatusStore } from "../../src/stores/vcsStatus";
/** A recorded engine call. */
interface Call {
/** `engine_execute` or `engine_execute_waiting`. */
via: string;
/** Command id. */
command: string;
/** Its params. */
params: Record<string, unknown>;
}
/** Every engine call, in order. */
let calls: Call[];
/** What `git.status` answers. */
let gitStatus: unknown;
/** What `git.remotes` answers. */
let gitRemotes: unknown;
/** Errors to throw, by command id. */
let failures: Record<string, { code: string; message: string }>;
/** What `file.saveAll` answers. */
let saveAll: unknown;
/** What `pick_dir` answers. */
let picked: string | null;
/** Event listeners registered through `listen`. */
let listeners: ((event: { payload: unknown }) => void)[];
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components, unmounted after each test. */
let mounted: VueWrapper[];
/**
* The calls of a command.
*
* @param command - the command id.
*/
function callsOf(command: string): Call[] {
return calls.filter((c) => c.command === command);
}
/**
* Sends an engine event to every listener.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of listeners) {
listener({ payload });
}
await flushPromises();
}
/** The texts of the toasts shown. */
function toasts(): string[] {
return useNotificationsStore(pinia).toasts.map((toast) => toast.text);
}
/** Mounts the status-bar item with started stores. */
async function mountItem(): Promise<VueWrapper> {
useVcsStatusStore(pinia).start();
const wrapper = mount(RemoteStatusItem, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await useCommandsStore(pinia).start();
await flushPromises();
return wrapper;
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
calls = [];
mounted = [];
failures = {};
listeners = [];
picked = null;
gitStatus = {
available: true,
repo: { root: "C:/p", branch: "main", detached: false, head: "0123", upstream: "origin/main", ahead: 0, behind: 0 },
files: [],
};
gitRemotes = {
remotes: [
{ name: "origin", fetchUrl: "https://***@github.com/a/b.git", pushUrl: "git@github.com:a/b.git" },
{ name: "fork", fetchUrl: "git@forgejo.example:me/b.git" },
],
};
saveAll = { saved: [], failed: [], skipped: [] };
invoke.mockReset();
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push(callback);
return Promise.resolve(() => {
listeners = listeners.filter((l) => l !== callback);
});
});
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve(
["git.status", "git.fetch", "git.pull", "git.push", "git.remotes", "git.clone"].map((id) => ({
id,
label: id,
enabled: true,
})),
);
}
if (cmd === "pick_dir") {
return Promise.resolve(picked);
}
if ((cmd !== "engine_execute" && cmd !== "engine_execute_waiting") || !args) {
return Promise.resolve(null);
}
calls.push({ via: cmd, command: args.command, params: args.params });
const failure = failures[args.command];
if (failure) {
return Promise.reject(Object.assign(new Error(failure.message), failure));
}
switch (args.command) {
case "git.status":
return Promise.resolve(gitStatus);
case "git.remotes":
return Promise.resolve(gitRemotes);
case "git.push":
return Promise.resolve({ remote: "origin", branch: "feature", upstreamSet: true });
case "git.clone":
return Promise.resolve({ root: String(args.params.dir) });
case "git.cancel":
return Promise.resolve({ cancelled: true });
case "file.saveAll":
return Promise.resolve(saveAll);
default:
return Promise.resolve({});
}
});
});
afterEach(() => {
for (const wrapper of mounted) {
wrapper.unmount();
}
useVcsStatusStore(pinia).stop();
document.body.innerHTML = "";
});
describe("reading the engine's answers", () => {
it("reads gitProgress and drops what is not running or malformed", () => {
expect(
toProgress({ kind: "gitProgress", active: true, operation: "push", phase: "Writing objects", percent: 42.4 }),
).toEqual({ operation: "push", phase: "Writing objects", percent: 42 });
expect(toProgress({ kind: "gitProgress", active: true, operation: "clone", percent: 300 })).toEqual({
operation: "clone",
phase: "",
percent: 100,
});
expect(toProgress({ kind: "gitProgress", active: false, operation: "fetch" })).toBeNull();
expect(toProgress({ kind: "gitProgress", active: true, operation: "rm -rf" })).toBeNull();
expect(toProgress({ kind: "projectClosed" })).toBeNull();
});
it("reads git.remotes and drops malformed entries", () => {
expect(
toRemotes({ remotes: [{ name: "o", fetchUrl: "u", pushUrl: "" }, { name: "" }, null, "x", { name: "p", fetchUrl: 3 }] }),
).toEqual([
{ name: "o", fetchUrl: "u", pushUrl: null },
{ name: "p", fetchUrl: "", pushUrl: null },
]);
expect(toRemotes(null)).toEqual([]);
expect(toRemotes({ remotes: "no" })).toEqual([]);
});
it("names the clone folder after the repository", () => {
expect(repoName("https://github.com/owner/lutra.git")).toBe("lutra");
expect(repoName("git@forgejo.example:me/site.GIT/")).toBe("site");
expect(repoName("C:\\repos\\tool")).toBe("tool");
expect(repoName("")).toBe("");
expect(joinPath("C:\\src", "lutra")).toBe("C:\\src\\lutra");
expect(joinPath("/home/me/", "lutra")).toBe("/home/me/lutra");
expect(joinPath("C:/src", "lutra")).toBe("C:/src/lutra");
});
});
describe("the status-bar item", () => {
it("shows the running call with Cancel, then ahead and behind", async () => {
const wrapper = await mountItem();
expect(wrapper.find("[data-test=remote-progress]").exists()).toBe(false);
expect(wrapper.find("[data-test=remote-sync]").exists()).toBe(false);
await emit({ kind: "gitProgress", active: true, operation: "fetch", phase: "Receiving objects", percent: 45 });
expect(wrapper.get("[data-test=remote-progress]").text()).toBe("Fetching: Receiving objects 45%");
expect(useRemoteStore(pinia).busy).toBe(true);
expect(useCommandsStore(pinia).isEnabled("vcs.push")).toBe(false);
await wrapper.get("[data-test=remote-cancel]").trigger("click");
await flushPromises();
expect(callsOf("git.cancel")).toHaveLength(1);
expect(callsOf("git.cancel")[0]?.via).toBe("engine_execute");
await emit({ kind: "gitProgress", active: false, operation: "fetch" });
expect(wrapper.find("[data-test=remote-progress]").exists()).toBe(false);
expect(useCommandsStore(pinia).isEnabled("vcs.push")).toBe(true);
gitStatus = {
available: true,
repo: { root: "C:/p", branch: "main", detached: false, upstream: "origin/main", ahead: 2, behind: 1 },
files: [],
};
await useVcsStatusStore(pinia).refresh();
await flushPromises();
expect(wrapper.get("[data-test=remote-sync]").text().replace(/\s+/g, "")).toBe("21");
expect(wrapper.get("[data-test=remote-sync]").attributes("aria-label")).toBe(
"2 commits to push and 1 to pull (origin/main)",
);
});
});
describe("fetch, pull and push", () => {
it("pushes and says when the upstream was set", async () => {
await mountItem();
await useCommandsStore(pinia).execute("vcs.push");
await flushPromises();
expect(callsOf("git.push")).toEqual([{ via: "engine_execute_waiting", command: "git.push", params: {} }]);
expect(toasts()).toContain("Pushed feature to origin and set it as the upstream");
});
it("saves before a pull and cancels it when a save fails", async () => {
await mountItem();
await useCommandsStore(pinia).execute("vcs.pull");
await flushPromises();
const order = calls.map((c) => c.command).filter((c) => c === "file.saveAll" || c === "git.pull");
expect(order).toEqual(["file.saveAll", "git.pull"]);
expect(toasts()).toContain("Pulled the current branch");
saveAll = { saved: [], failed: [{ id: 3, path: "a.php", message: "denied" }], skipped: [] };
calls = [];
await useCommandsStore(pinia).execute("vcs.pull");
await flushPromises();
expect(callsOf("git.pull")).toHaveLength(0);
expect(toasts()).toContain("Pull cancelled: not every file could be saved first.");
});
it("shows git's explained refusal, and a cancelled call as information", async () => {
await mountItem();
failures["git.push"] = {
code: "failed",
message: "The push was rejected: the remote branch has commits that your branch does not have.",
};
await useCommandsStore(pinia).execute("vcs.push");
await flushPromises();
expect(toasts().at(-1)).toBe(
"Push failed: The push was rejected: the remote branch has commits that your branch does not have.",
);
expect(useNotificationsStore(pinia).toasts.at(-1)?.level).toBe("error");
failures["git.fetch"] = { code: "failed", message: "the Git operation was cancelled" };
await useCommandsStore(pinia).execute("vcs.fetch");
await flushPromises();
expect(toasts().at(-1)).toBe("Git operation cancelled");
expect(useNotificationsStore(pinia).toasts.at(-1)?.level).toBe("info");
});
});
describe("Clone Repository", () => {
it("proposes the folder from Browse… and the URL, clones and opens the project", async () => {
const wrapper = await mountItem();
await useCommandsStore(pinia).execute("vcs.clone");
await flushPromises();
const dialog = wrapper.get("[data-test=clone-dialog]");
expect(document.activeElement).toBe(dialog.get("[data-test=clone-url]").element);
await dialog.get("[data-test=clone-url]").setValue("https://github.com/owner/lutra.git");
picked = "C:\\src";
await dialog.get("[data-test=clone-browse]").trigger("click");
await flushPromises();
expect((dialog.get("[data-test=clone-dir]").element as HTMLInputElement).value).toBe("C:\\src\\lutra");
await dialog.get("[data-test=clone-url]").setValue("git@forgejo.example:me/site.git");
await flushPromises();
expect((dialog.get("[data-test=clone-dir]").element as HTMLInputElement).value).toBe("C:\\src\\site");
await dialog.get("[data-test=clone-run]").trigger("click");
await flushPromises();
expect(callsOf("git.clone")[0]?.params).toEqual({ url: "git@forgejo.example:me/site.git", dir: "C:\\src\\site" });
expect(callsOf("project.open")[0]?.params).toEqual({ path: "C:\\src\\site" });
expect(wrapper.find("[data-test=clone-dialog]").exists()).toBe(false);
expect(toasts()).toContain("Cloned into C:\\src\\site");
});
it("keeps the dialog with git's refusal and asks for both fields", async () => {
const wrapper = await mountItem();
await useCommandsStore(pinia).execute("vcs.clone");
await flushPromises();
await wrapper.get("[data-test=clone-run]").trigger("click");
await flushPromises();
expect(wrapper.get("[data-test=clone-error]").text()).toBe("Enter a URL and a folder.");
expect(callsOf("git.clone")).toHaveLength(0);
failures["git.clone"] = {
code: "failed",
message: "The remote repository was not found. Check the URL and that you have access to it.",
};
await wrapper.get("[data-test=clone-url]").setValue("https://github.com/nope/nope.git");
await wrapper.get("[data-test=clone-dir]").setValue("C:/src/nope");
await wrapper.get("[data-test=clone-url]").trigger("keydown", { key: "Enter" });
await flushPromises();
expect(wrapper.get("[data-test=clone-error]").text()).toContain("was not found");
expect(callsOf("project.open")).toHaveLength(0);
await wrapper.get("[data-test=clone-url]").trigger("keydown", { key: "Escape" });
expect(wrapper.find("[data-test=clone-dialog]").exists()).toBe(false);
});
});
describe("Manage Remotes", () => {
it("lists, adds, edits and removes remotes", async () => {
const wrapper = await mountItem();
await useCommandsStore(pinia).execute("vcs.manageRemotes");
await flushPromises();
const origin = wrapper.get("[data-test=remote-origin]");
expect(origin.text()).toContain("https://***@github.com/a/b.git");
expect(origin.text()).toContain("push: git@github.com:a/b.git");
expect(wrapper.get("[data-test=remote-fork]").text()).toContain("git@forgejo.example:me/b.git");
await wrapper.get("[data-test=remote-new-name]").setValue("upstream");
await wrapper.get("[data-test=remote-new-url]").setValue(" https://gitlab.com/x/b.git ");
await wrapper.get("[data-test=remote-add]").trigger("submit");
await flushPromises();
expect(callsOf("git.remoteAdd")[0]?.params).toEqual({ name: "upstream", url: "https://gitlab.com/x/b.git" });
expect(callsOf("git.remotes")).toHaveLength(2);
await origin.get("[data-test=remote-edit]").trigger("click");
const field = wrapper.get("[data-test=remote-edit-url]");
expect((field.element as HTMLInputElement).value).toBe("");
await field.setValue("https://bitbucket.org/a/b.git");
await wrapper.get("[data-test=remote-save]").trigger("click");
await flushPromises();
expect(callsOf("git.remoteSetUrl")[0]?.params).toEqual({ name: "origin", url: "https://bitbucket.org/a/b.git" });
failures["git.remoteRemove"] = { code: "failed", message: "error: No such remote: 'fork'" };
await wrapper.get("[data-test=remote-fork]").get("[data-test=remote-remove]").trigger("click");
await wrapper.get("[data-test=remote-remove-yes]").trigger("click");
await flushPromises();
expect(callsOf("git.remoteRemove")[0]?.params).toEqual({ name: "fork" });
expect(wrapper.get("[data-test=remotes-error]").text()).toBe("error: No such remote: 'fork'");
});
});
describe("registration", () => {
it("adds the remote commands to the Git menu without default shortcuts", () => {
const ids = ["vcs.clone", "vcs.fetch", "vcs.manageRemotes", "vcs.pull", "vcs.push"];
for (const id of ids) {
const spec = UI_COMMANDS.find((c) => c.id === id);
expect(spec?.menuPath?.startsWith("Git/")).toBe(true);
expect(spec?.defaultShortcut).toBeUndefined();
}
});
});