Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

feat(vcs): select the branch name and offer to unset its upstream when renaming (#2398)

HandsomeXi38b56e724eed
diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs
index df307d746..96fb3ab7b 100644
--- a/crates/ide-host/src/ops/vcs/commands.rs
+++ b/crates/ide-host/src/ops/vcs/commands.rs
@@ -673,10 +673,11 @@ pub async fn vcs_rename_branch(
repo: Option<PathBuf>,
from: String,
to: String,
+ unset_upstream: bool,
) -> IdeResult<()> {
host.require_trust(window)?;
let project = host.project(window)?;
- blocking(move || project.with_repo_at(repo.as_deref(), |r| r.rename_branch(&from, &to))).await
+ blocking(move || project.with_repo_at(repo.as_deref(), |r| r.rename_branch(&from, &to, unset_upstream))).await
}
pub async fn vcs_merge(host: &Host, window: &str, repo: Option<PathBuf>, branch: String) -> IdeResult<()> {
@@ -1379,7 +1380,8 @@ pub(crate) fn register(d: &mut Dispatcher) {
vcs_restore_branch(&c.host, &c.window, c.arg("repo")?, c.arg("deleted")?).await
});
d.add("vcs_rename_branch", |c| async move {
- vcs_rename_branch(&c.host, &c.window, c.arg("repo")?, c.arg("from")?, c.arg("to")?).await
+ vcs_rename_branch(&c.host, &c.window, c.arg("repo")?, c.arg("from")?, c.arg("to")?, c.arg("unset_upstream")?)
+ .await
});
d.add("vcs_merge", |c| async move { vcs_merge(&c.host, &c.window, c.arg("repo")?, c.arg("branch")?).await });
d.add("vcs_rebase", |c| async move { vcs_rebase(&c.host, &c.window, c.arg("repo")?, c.arg("onto")?).await });
diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs
index 9c1c12106..522bfe39e 100644
--- a/crates/ide-vcs/src/lib.rs
+++ b/crates/ide-vcs/src/lib.rs
@@ -1172,10 +1172,11 @@ impl Repo {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
write::restore_branch(self, deleted)
}
- /// Renames a local branch (`git branch -m`); its upstream configuration moves with it.
- pub fn rename_branch(&self, from: &str, to: &str) -> IdeResult<()> {
+ /// Renames a local branch (`git branch -m`); its upstream configuration moves with it,
+ /// unless `unset_upstream` drops the tracking instead.
+ pub fn rename_branch(&self, from: &str, to: &str, unset_upstream: bool) -> IdeResult<()> {
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
- write::rename_branch(self, from, to)
+ write::rename_branch(self, from, to, unset_upstream)
}
/// Merges `branch` into HEAD; local changes are stashed and restored around it. On
/// conflicts an error is returned and the repository is left mid-merge
diff --git a/crates/ide-vcs/src/write.rs b/crates/ide-vcs/src/write.rs
index 21ae5f937..4cc35c8b8 100644
--- a/crates/ide-vcs/src/write.rs
+++ b/crates/ide-vcs/src/write.rs
@@ -947,17 +947,20 @@ pub(crate) fn delete_branch(r: &Repo, branch: &str, force: bool) -> IdeResult<()
run(r.root(), &["branch", if force { "-D" } else { "-d" }, "--", branch], None).map(|_| ())
}
+/// The short name (`origin/main`) of the branch a local branch tracks, as the branch list shows it.
+fn upstream_name(r: &Repo, branch: &str) -> IdeResult<Option<String>> {
+ let out = run(r.root(), &["for-each-ref", "--format=%(upstream:short)", &format!("refs/heads/{branch}")], None)?;
+ let upstream = out.stdout_str().trim().to_string();
+ Ok((!upstream.is_empty()).then_some(upstream))
+}
+
pub(crate) fn delete_branch_restorable(r: &Repo, branch: &str) -> IdeResult<DeletedBranch> {
check_local_branch(r, branch)?;
let tip = run(r.root(), &["rev-parse", "--verify", "-q", &format!("refs/heads/{branch}^{{commit}}")], None)?
.stdout_str()
.trim()
.to_string();
- let upstream =
- cli::run_raw(r.root(), &["for-each-ref", "--format=%(upstream:short)", &format!("refs/heads/{branch}")], None)?
- .stdout_str()
- .trim()
- .to_string();
+ let upstream = upstream_name(r, branch)?;
let out = cli::run_raw(r.root(), &["branch", "-d", "--", branch], None)?;
let unmerged = match out.code {
Some(0) => false,
@@ -967,7 +970,7 @@ pub(crate) fn delete_branch_restorable(r: &Repo, branch: &str) -> IdeResult<Dele
}
code => return Err(cli::failure(&["branch"], &out.stderr, &out.stdout, code)),
};
- Ok(DeletedBranch { name: branch.to_string(), tip, upstream: (!upstream.is_empty()).then_some(upstream), unmerged })
+ Ok(DeletedBranch { name: branch.to_string(), tip, upstream, unmerged })
}
pub(crate) fn restore_branch(r: &Repo, deleted: &DeletedBranch) -> IdeResult<()> {
@@ -980,12 +983,22 @@ pub(crate) fn restore_branch(r: &Repo, deleted: &DeletedBranch) -> IdeResult<()>
Ok(())
}
-pub(crate) fn rename_branch(r: &Repo, from: &str, to: &str) -> IdeResult<()> {
+/// `unset_upstream` drops the tracking that `git branch -m` moves to the new name.
+pub(crate) fn rename_branch(r: &Repo, from: &str, to: &str, unset_upstream: bool) -> IdeResult<()> {
let to = to.trim();
if to.is_empty() {
return Err(IdeError::invalid("branch name is empty"));
}
- run(r.root(), &["branch", "-m", "--", from, to], None).map(|_| ())
+ let has_upstream = unset_upstream && upstream_name(r, from)?.is_some();
+ run(r.root(), &["branch", "-m", "--", from, to], None)?;
+ if has_upstream {
+ run(r.root(), &["branch", "--unset-upstream", "--", to], None).map_err(|mut error| {
+ error.message =
+ format!("Renamed branch '{from}' to '{to}', but could not unset its upstream: {}", error.message);
+ error
+ })?;
+ }
+ Ok(())
}
fn check_rev(rev: &str) -> IdeResult<&str> {
diff --git a/crates/ide-vcs/tests/repo.rs b/crates/ide-vcs/tests/repo.rs
index e1e85ec1e..c6d9f1e4b 100644
--- a/crates/ide-vcs/tests/repo.rs
+++ b/crates/ide-vcs/tests/repo.rs
@@ -980,17 +980,82 @@ fn checkout_create_detached_delete_rebase() {
);
repo.checkout("main", false).unwrap();
- repo.rename_branch("topic", "topic2").unwrap();
+ repo.rename_branch("topic", "topic2", false).unwrap();
assert!(repo.branches().unwrap().iter().any(|b| b.name == "topic2"));
- assert!(repo.rename_branch("topic2", "main").is_err(), "existing name must be refused");
- assert!(repo.rename_branch("topic2", " ").is_err());
- repo.rename_branch("topic2", "topic").unwrap();
+ assert!(repo.rename_branch("topic2", "main", false).is_err(), "existing name must be refused");
+ assert!(repo.rename_branch("topic2", " ", false).is_err());
+ repo.rename_branch("topic2", "topic", false).unwrap();
assert!(repo.delete_branch("topic", false).is_err(), "unmerged branch must need force");
repo.delete_branch("topic", true).unwrap();
assert!(!repo.branches().unwrap().iter().any(|b| b.name == "topic"));
assert!(repo.checkout("does-not-exist", false).is_err());
}
+#[test]
+fn renaming_a_branch_keeps_or_drops_its_upstream() {
+ let (fx, _bare) = with_remote();
+ let repo = fx.repo();
+ fx.git(&["branch", "--track", "topic", "origin/main"]);
+
+ let upstream = |name: &str| {
+ repo.branches().unwrap().into_iter().find(|b| b.name == name && !b.remote).and_then(|b| b.upstream)
+ };
+ assert_eq!(upstream("topic").as_deref(), Some("origin/main"));
+
+ // `git branch -m` moves the tracking with the name.
+ repo.rename_branch("topic", "topic2", false).unwrap();
+ assert_eq!(upstream("topic2").as_deref(), Some("origin/main"));
+
+ // Asked to drop it, the new branch tracks nothing.
+ repo.rename_branch("topic2", "topic3", true).unwrap();
+ assert_eq!(upstream("topic3"), None);
+
+ // A branch that tracks nothing has no upstream to drop; that is not an error.
+ fx.git(&["branch", "plain"]);
+ repo.rename_branch("plain", "plain2", true).unwrap();
+ assert!(repo.branches().unwrap().iter().any(|b| b.name == "plain2" && !b.remote));
+}
+
+#[test]
+fn renaming_the_current_branch_keeps_or_drops_its_upstream() {
+ for unset_upstream in [false, true] {
+ let (fx, _bare) = with_remote();
+ let repo = fx.repo();
+ repo.rename_branch("main", "renamed", unset_upstream).unwrap();
+ let branch = repo.branch_info().unwrap();
+ assert_eq!(branch.head.as_deref(), Some("renamed"));
+ assert_eq!(branch.upstream.as_deref(), if unset_upstream { None } else { Some("origin/main") });
+ }
+}
+
+#[test]
+fn failed_branch_rename_does_not_unset_upstream() {
+ let (fx, _bare) = with_remote();
+ let repo = fx.repo();
+ fx.git(&["branch", "occupied"]);
+ assert!(repo.rename_branch("main", "occupied", true).is_err());
+ let branch = repo.branch_info().unwrap();
+ assert_eq!(branch.head.as_deref(), Some("main"));
+ assert_eq!(branch.upstream.as_deref(), Some("origin/main"));
+}
+
+#[test]
+fn branch_rename_reports_when_only_unsetting_upstream_fails() {
+ let (fx, _bare) = with_remote();
+ let repo = fx.repo();
+ // The new branch activates a broken config only after the rename has succeeded.
+ fx.write(".git/broken-config", "[broken\n");
+ fx.git(&["config", "includeIf.onbranch:renamed.path", "broken-config"]);
+ let error = repo.rename_branch("main", "renamed", true).unwrap_err();
+ assert!(error.message.contains("Renamed branch 'main' to 'renamed'"), "{error}");
+ assert!(error.message.contains("could not unset its upstream"), "{error}");
+ assert!(error.message.contains("bad config"), "{error}");
+ std::fs::remove_file(fx.path(".git/broken-config")).unwrap();
+ let branch = repo.branch_info().unwrap();
+ assert_eq!(branch.head.as_deref(), Some("renamed"));
+ assert_eq!(branch.upstream.as_deref(), Some("origin/main"));
+}
+
#[test]
fn smart_and_force_checkout_with_local_changes_in_the_way() {
let fx = Fixture::new();
diff --git a/src-tauri/src/commands/vcs.rs b/src-tauri/src/commands/vcs.rs
index cef9f7eb7..b559eeb31 100644
--- a/src-tauri/src/commands/vcs.rs
+++ b/src-tauri/src/commands/vcs.rs
@@ -368,8 +368,9 @@ pub async fn vcs_rename_branch(
repo: Option<PathBuf>,
from: String,
to: String,
+ unset_upstream: bool,
) -> IdeResult<()> {
- ide_host::ops::vcs::vcs_rename_branch(&state.host, window.label(), repo, from, to).await
+ ide_host::ops::vcs::vcs_rename_branch(&state.host, window.label(), repo, from, to, unset_upstream).await
}
#[tauri::command]
diff --git a/src/bindings.ts b/src/bindings.ts
index e81452648..f503dfdb9 100644
--- a/src/bindings.ts
+++ b/src/bindings.ts
@@ -575,7 +575,7 @@ export const commands = {
vcsReword: (repo: string | null, commit: string, message: string) => typedError<HeadChange, IdeError>(__TAURI_INVOKE("vcs_reword", { repo, commit, message })),
/** Undo of a history rewrite (Edit Commit Message, Drop, Squash). */
vcsRestoreHead: (repo: string | null, before: string, after: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_restore_head", { repo, before, after })),
- vcsRenameBranch: (repo: string | null, from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rename_branch", { repo, from, to })),
+ vcsRenameBranch: (repo: string | null, from: string, to: string, unsetUpstream: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rename_branch", { repo, from, to, unsetUpstream })),
vcsMerge: (repo: string | null, branch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_merge", { repo, branch })),
vcsRebase: (repo: string | null, onto: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rebase", { repo, onto })),
vcsStashPush: (repo: string | null, message: string | null, includeUntracked: boolean, keepIndex: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_push", { repo, message, includeUntracked, keepIndex })),
diff --git a/src/features/vcs/__tests__/branchOps.test.ts b/src/features/vcs/__tests__/branchOps.test.ts
index 6acb3865e..bfc11c247 100644
--- a/src/features/vcs/__tests__/branchOps.test.ts
+++ b/src/features/vcs/__tests__/branchOps.test.ts
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
worktrees: vi.fn(),
restoreBranch: vi.fn(),
branches: vi.fn(),
+ rename: vi.fn(),
}));
vi.mock("../dialogs", async (original) => ({
...(await original<typeof import("../dialogs")>()),
@@ -27,6 +28,7 @@ vi.mock("@/platform/ipc", async (original) => {
vcsDeleteBranch: mocks.deleteBranch,
vcsRestoreBranch: mocks.restoreBranch,
vcsBranches: mocks.branches,
+ vcsRenameBranch: mocks.rename,
},
};
});
@@ -95,7 +97,7 @@ it.each([
["New Branch", () => newBranch()],
["New Branch from a revision", () => newBranch("origin/main")],
["New Branch in several repositories", () => newBranchInRepos(["/p/front", "/p/back"])],
- ["Rename Branch", () => renameBranch("main")],
+ ["Rename Branch", () => renameBranch(local("main"))],
])("%s turns a typed space into a separator, as IDEA does", async (_name, open) => {
await open();
const { sanitize, validate } = mocks.prompt.mock.calls[0]![0];
@@ -104,6 +106,45 @@ it.each([
expect(validate(typed)).toBeNull();
});
+const tracked = (name: string, upstream: string, current = false): Branch => ({ ...local(name, current), upstream });
+
+it("offers to drop the upstream only for a branch that tracks one", async () => {
+ await renameBranch(tracked("topic", "origin/topic"));
+ expect(mocks.prompt.mock.calls[0]?.[0]).toMatchObject({
+ initial: "topic",
+ checkbox: { label: "Unset upstream branch", initial: false },
+ });
+ await renameBranch(local("plain"));
+ expect(mocks.prompt.mock.calls[1]?.[0].checkbox).toBeUndefined();
+});
+
+it("renames with the tracking kept, or dropped when the box is ticked", async () => {
+ mocks.prompt.mockResolvedValue({ value: "renamed", checked: false });
+ await renameBranch(tracked("topic", "origin/topic"));
+ expect(mocks.rename).toHaveBeenLastCalledWith("/p/front", "topic", "renamed", false);
+
+ mocks.prompt.mockResolvedValue({ value: "renamed", checked: true });
+ await renameBranch(tracked("topic", "origin/topic"));
+ expect(mocks.rename).toHaveBeenLastCalledWith("/p/front", "topic", "renamed", true);
+
+ // Nothing to drop on a branch without an upstream, whatever the box says.
+ await renameBranch(local("plain"));
+ expect(mocks.rename).toHaveBeenLastCalledWith("/p/front", "plain", "renamed", false);
+});
+
+it("shows a partial failure without claiming that the rename failed", async () => {
+ const message = "Renamed branch 'topic' to 'renamed', but could not unset its upstream: config is locked";
+ mocks.prompt.mockResolvedValue({ value: "renamed", checked: true });
+ mocks.rename.mockResolvedValue({ status: "error", error: { kind: "io", message } });
+ await renameBranch(tracked("topic", "origin/topic"));
+ expect(mocks.notify).toHaveBeenCalledExactlyOnceWith({
+ group: "vcs",
+ level: "error",
+ title: "Rename branch topic",
+ body: message,
+ });
+});
+
const worktree = (path: string, branchName: string | null, main = false): Worktree => ({
path,
head: "abc1234567890",
diff --git a/src/features/vcs/__tests__/promptDialog.test.tsx b/src/features/vcs/__tests__/promptDialog.test.tsx
index 4a5e0ef92..126d3b9ea 100644
--- a/src/features/vcs/__tests__/promptDialog.test.tsx
+++ b/src/features/vcs/__tests__/promptDialog.test.tsx
@@ -62,3 +62,74 @@ describe("prompt dialog with a sanitizer (branch name)", () => {
expect(input).toHaveValue("a-xb");
});
});
+
+describe("prompt dialog prefilled for replacement", () => {
+ it("selects the prefilled value so typing replaces it", async () => {
+ const user = userEvent.setup();
+ render(<VcsDialogHost />);
+ act(() => void open("feature/ui"));
+ const input = await screen.findByRole<HTMLInputElement>("textbox", { name: "New branch name:" });
+ await waitFor(() => expect(input.selectionEnd).toBe("feature/ui".length));
+ expect(input.selectionStart).toBe(0);
+ await user.keyboard("fix");
+ expect(input).toHaveValue("fix");
+ });
+
+ it("leaves an empty field alone", async () => {
+ render(<VcsDialogHost />);
+ act(() => void open());
+ const input = await screen.findByRole<HTMLInputElement>("textbox", { name: "New branch name:" });
+ expect(input.selectionStart).toBe(0);
+ expect(input.selectionEnd).toBe(0);
+ });
+
+ it("keeps the caret when an edited field is programmatically focused again", async () => {
+ const user = userEvent.setup();
+ render(<VcsDialogHost />);
+ act(() => void open("feature/ui"));
+ const input = await screen.findByRole<HTMLInputElement>("textbox", { name: "New branch name:" });
+ await waitFor(() => expect(input).toHaveFocus());
+ await user.keyboard("fix");
+ input.setSelectionRange(1, 1);
+ act(() => {
+ input.blur();
+ input.focus();
+ });
+ expect(input.selectionStart).toBe(1);
+ expect(input.selectionEnd).toBe(1);
+ await user.keyboard("x");
+ expect(input).toHaveValue("fxix");
+ });
+});
+
+describe("prompt dialog checkbox", () => {
+ const openWithUpstream = (checkbox: boolean) =>
+ promptText({
+ title: "Rename Branch topic",
+ label: "New branch name:",
+ initial: "topic",
+ okLabel: "Rename",
+ checkbox: checkbox ? { label: "Unset upstream branch", initial: false } : undefined,
+ });
+
+ it("is offered unchecked and reported back", async () => {
+ const user = userEvent.setup();
+ render(<VcsDialogHost />);
+ let result: ReturnType<typeof openWithUpstream> | undefined;
+ act(() => {
+ result = openWithUpstream(true);
+ });
+ const box = await screen.findByRole("checkbox", { name: "Unset upstream branch" });
+ expect(box).not.toBeChecked();
+ await user.click(box);
+ await user.click(screen.getByRole("button", { name: "Rename" }));
+ await expect(result).resolves.toEqual({ value: "topic", checked: true });
+ });
+
+ it("is missing when the branch tracks nothing", async () => {
+ render(<VcsDialogHost />);
+ act(() => void openWithUpstream(false));
+ await screen.findByRole("textbox", { name: "New branch name:" });
+ expect(screen.queryByRole("checkbox")).toBeNull();
+ });
+});
diff --git a/src/features/vcs/branchMenu.ts b/src/features/vcs/branchMenu.ts
index b0f23fe94..9093569e1 100644
--- a/src/features/vcs/branchMenu.ts
+++ b/src/features/vcs/branchMenu.ts
@@ -78,7 +78,7 @@ export function branchMenu(
{ label: "Update", icon: "git-pull", run: run(() => executeAction("vcs.update")) },
{ label: "Push…", icon: "git-push", run: run(() => executeAction("vcs.push")) },
{ kind: "separator" },
- { label: "Rename…", run: run(() => renameBranch(b.name)) },
+ { label: "Rename…", run: run(() => renameBranch(b)) },
favoriteItem,
history,
];
@@ -111,7 +111,7 @@ export function branchMenu(
);
items.push(
{ kind: "separator" },
- ...(b.remote ? [] : [{ label: "Rename…", run: run(() => renameBranch(b.name)) }]),
+ ...(b.remote ? [] : [{ label: "Rename…", run: run(() => renameBranch(b)) }]),
favoriteItem,
{
label: "Delete",
diff --git a/src/features/vcs/branchOps.ts b/src/features/vcs/branchOps.ts
index 27b142e5e..362f411cc 100644
--- a/src/features/vcs/branchOps.ts
+++ b/src/features/vcs/branchOps.ts
@@ -255,7 +255,12 @@ export async function rebaseOnto(branch: string, ref = branch) {
});
}
-export async function renameBranch(name: string) {
+/**
+ * Renames a local branch. `git branch -m` carries the upstream tracking to the new name;
+ * a branch that has one also offers to drop it, since the remote branch keeps its old name.
+ */
+export async function renameBranch(branch: Branch) {
+ const name = branch.name;
const repo = currentRepo();
const r = await promptText({
title: tx`Rename Branch ${name}`,
@@ -265,12 +270,23 @@ export async function renameBranch(name: string) {
okLabel: "Rename",
sanitize: cleanUpBranchNameOnTyping,
validate: (v) => (v.trim() === name ? "Enter a new name" : validateBranchName(v)),
+ checkbox: branch.upstream ? { label: "Unset upstream branch", initial: false } : undefined,
});
if (!r) return;
const to = r.value.trim();
- const ok = await runOp(tx`Rename branch ${name}`, () => call(commands.vcsRenameBranch(repo, name, to)), {
- success: tx`Renamed branch ${name} to ${to}`,
- });
+ const unsetUpstream = !!branch.upstream && r.checked;
+ const ok = await runOp(
+ tx`Rename branch ${name}`,
+ () => call(commands.vcsRenameBranch(repo, name, to, unsetUpstream)),
+ {
+ success: tx`Renamed branch ${name} to ${to}`,
+ onError: (message) => {
+ // Unsetting the upstream can fail after the rename has succeeded.
+ notifications().notify({ group: "vcs", level: "error", title: tx`Rename branch ${name}`, body: message });
+ return true;
+ },
+ },
+ );
if (ok !== undefined) {
try {
localStorage.setItem(recentKey(), JSON.stringify(recentBranches().map((b) => (b === name ? to : b))));
diff --git a/src/features/vcs/dialogs.tsx b/src/features/vcs/dialogs.tsx
index b2089679f..267f99ccc 100644
--- a/src/features/vcs/dialogs.tsx
+++ b/src/features/vcs/dialogs.tsx
@@ -116,6 +116,7 @@ function PromptDialog(props: PromptOptions & { onDone: (r: PromptResult | null)
mono={mono}
placeholder={placeholder}
invalid={touched && !!error}
+ autoSelect={initial !== ""}
onChange={(e) => {
setTouched(true);
const next = clean(e);
diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json
index e3e364c27..35e7e1c88 100644
--- a/src/platform/locales/text/en.json
+++ b/src/platform/locales/text/en.json
@@ -133,6 +133,7 @@
"Current color scheme": "Current color scheme",
"No settings OpenIDEA can import were found in this archive": "No settings OpenIDEA can import were found in this archive",
"Overwrite existing branch": "Overwrite existing branch",
+ "Unset upstream branch": "Unset upstream branch",
"Branch '{n}' already exists": "Branch '{n}' already exists",
"Cannot copy reference": "Cannot copy reference",
"Decompiled assembly (read-only).": "Decompiled assembly (read-only).",
diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json
index 3c95124ea..6c568ce7f 100644
--- a/src/platform/locales/text/zh.json
+++ b/src/platform/locales/text/zh.json
@@ -551,6 +551,7 @@
"Checkout Tag or Revision…": "签出标签或修订…",
"Checkout branch": "签出分支",
"Overwrite existing branch": "覆盖现有分支",
+ "Unset upstream branch": "取消设置上游分支",
"Branch '{n}' already exists": "分支 '{n}' 已存在",
"Checks out the selected pull request, a number given as argument, or asks for one.": "签出所选拉取请求或参数指定编号的拉取请求,否则询问编号。",
"Cherry-Pick": "拣选",
diff --git a/src/ui/Input.tsx b/src/ui/Input.tsx
index c1940bf23..90ef32597 100644
--- a/src/ui/Input.tsx
+++ b/src/ui/Input.tsx
@@ -22,6 +22,8 @@ export interface InputProps extends Omit<InputHTMLAttributes<HTMLInputElement>,
mono?: boolean;
/** `bare` drops the frame (for inputs embedded in popups / headers). */
variant?: "framed" | "bare";
+ /** Select the prefilled value the first time the field takes focus, so typing replaces it. */
+ autoSelect?: boolean;
}
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
@@ -29,16 +31,19 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
invalid,
mono,
variant = "framed",
+ autoSelect,
className,
spellCheck = false,
autoComplete = "off",
placeholder,
+ onFocus,
"aria-label": ariaLabel,
...rest
},
ref,
) {
const tx = useGivenTx();
+ const selected = useRef(false);
return (
<input
ref={ref}
@@ -49,6 +54,14 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
aria-invalid={invalid || undefined}
placeholder={tx(placeholder)}
aria-label={tx(ariaLabel)}
+ // First focus only: coming back to a field the user already edited keeps its caret.
+ onFocus={(e) => {
+ if (autoSelect && !selected.current) {
+ selected.current = true;
+ e.currentTarget.select();
+ }
+ onFocus?.(e);
+ }}
className={clsx(styles.input, variant === "bare" ? styles.bare : styles.framed, mono && styles.mono, className)}
{...rest}
/>