fix(settings): normalize and validate branch prefixes (#7772)

* Normalize branch prefixes and flag invalid ones in settings

A custom branch prefix ending in a slash (e.g. "team/") produced a
double-slashed branch name like "team//feature" that git rejects, and
the raw check-ref-format error gave no hint that the prefix caused it.

- Normalize the configured prefix (trim whitespace, strip leading/
  trailing and duplicate slashes) in the shared branch-name builder so
  the common trailing-slash case just works, for local and SSH worktrees.
- Validate the prefix on the worktree-create path (computeValidatedBranchName)
  so a genuinely invalid prefix fails fast with a clear
  "update it in Settings -> Git" message instead of an opaque git error.
- Add a live BranchPrefixFeedback under the Branch Prefix setting: previews
  the resulting branch name, warns on invalid characters, and notes when a
  prefix collapses to none.
- Keep the background first-work rename on the non-throwing builder since the
  prefix is already validated at create time.

* Keep caret in place when editing the branch prefix

The custom branch prefix input was directly controlled by settings, but
updateSettings persists through an async IPC round-trip, so the value
updated a tick late and React re-assigned it, snapping the caret to the
end on mid-string edits. Drive the input from a local draft and only
adopt genuine external settings changes so the caret stays put (and fast
typing survives slow SSH round-trips).

Co-authored-by: Cursor <cursoragent@cursor.com>

* Return ReactNode from BranchPrefixFeedback

JSX.Element needlessly excludes null/string/number returns; ReactNode
keeps the component's return type from over-constraining future changes.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yoel
2026-07-24 00:39:32 -07:00
committed by GitHub
co-authored by Cursor
parent 662d23f9b3
commit d1ccfcff40
18 changed files with 566 additions and 25 deletions
+145
View File
@@ -0,0 +1,145 @@
import { describe, expect, it } from 'vitest'
import {
assertBranchPrefixValid,
getBranchPrefixIssue,
normalizeBranchPrefix,
selectBranchPrefixInput
} from './branch-prefix'
describe('normalizeBranchPrefix', () => {
it('strips a trailing slash so the join does not double it', () => {
expect(normalizeBranchPrefix('team/')).toBe('team')
})
it('strips a leading slash', () => {
expect(normalizeBranchPrefix('/team')).toBe('team')
})
it('collapses internal double slashes', () => {
expect(normalizeBranchPrefix('team//frontend')).toBe('team/frontend')
})
it('trims surrounding whitespace', () => {
expect(normalizeBranchPrefix(' team ')).toBe('team')
})
it('preserves a legitimate multi-segment prefix', () => {
expect(normalizeBranchPrefix('team/frontend')).toBe('team/frontend')
})
it('returns empty when the value is only slashes/whitespace', () => {
expect(normalizeBranchPrefix(' // ')).toBe('')
})
it('leaves a plain prefix untouched', () => {
expect(normalizeBranchPrefix('feature')).toBe('feature')
})
})
describe('getBranchPrefixIssue', () => {
it('accepts a normal prefix', () => {
expect(getBranchPrefixIssue('team')).toBeNull()
})
it('accepts a prefix that only needs trailing-slash normalization', () => {
expect(getBranchPrefixIssue('team/')).toBeNull()
})
it('accepts a hyphenated prefix', () => {
expect(getBranchPrefixIssue('feat-x')).toBeNull()
})
it('accepts a multi-segment prefix', () => {
expect(getBranchPrefixIssue('team/frontend')).toBeNull()
})
it('accepts a mid-ref segment that ends with a dot (git allows it)', () => {
expect(getBranchPrefixIssue('team./frontend')).toBeNull()
})
it('accepts a non-leading segment that starts with a dash (git allows it)', () => {
expect(getBranchPrefixIssue('team/-frontend')).toBeNull()
})
it('treats an empty prefix as valid (no prefix)', () => {
expect(getBranchPrefixIssue('')).toBeNull()
})
it('flags whitespace inside the prefix', () => {
expect(getBranchPrefixIssue('team x')).toBe('invalid-characters')
})
it('flags git ref-reserved characters', () => {
expect(getBranchPrefixIssue('team~')).toBe('invalid-characters')
expect(getBranchPrefixIssue('team:x')).toBe('invalid-characters')
expect(getBranchPrefixIssue('team[')).toBe('invalid-characters')
expect(getBranchPrefixIssue('team\\')).toBe('invalid-characters')
})
it('flags ASCII control characters', () => {
expect(getBranchPrefixIssue('team\x01')).toBe('invalid-characters')
})
it('flags a `..` sequence', () => {
expect(getBranchPrefixIssue('team..x')).toBe('invalid-characters')
})
it('flags a `@{` sequence', () => {
expect(getBranchPrefixIssue('team@{x')).toBe('invalid-characters')
})
it('flags a leading dash on the whole prefix', () => {
expect(getBranchPrefixIssue('-team')).toBe('invalid-characters')
})
it('flags a segment starting with a dot', () => {
expect(getBranchPrefixIssue('.team')).toBe('invalid-characters')
expect(getBranchPrefixIssue('team/.frontend')).toBe('invalid-characters')
})
it('flags the whole prefix ending with a dot', () => {
expect(getBranchPrefixIssue('team.')).toBe('invalid-characters')
expect(getBranchPrefixIssue('team/frontend.')).toBe('invalid-characters')
})
it('flags a `.lock` suffix on any segment', () => {
expect(getBranchPrefixIssue('team.lock')).toBe('invalid-characters')
expect(getBranchPrefixIssue('team.lock/x')).toBe('invalid-characters')
})
})
describe('selectBranchPrefixInput', () => {
it('returns the git username for the git-username strategy', () => {
expect(selectBranchPrefixInput({ branchPrefix: 'git-username' }, 'jdoe')).toBe('jdoe')
})
it('returns null for git-username when no username is available', () => {
expect(selectBranchPrefixInput({ branchPrefix: 'git-username' }, null)).toBeNull()
})
it('returns the raw custom value for the custom strategy', () => {
expect(
selectBranchPrefixInput({ branchPrefix: 'custom', branchPrefixCustom: 'team/' }, null)
).toBe('team/')
})
it('returns null for custom when no value is set', () => {
expect(selectBranchPrefixInput({ branchPrefix: 'custom' }, null)).toBeNull()
})
it('returns null for the none strategy', () => {
expect(selectBranchPrefixInput({ branchPrefix: 'none' }, 'jdoe')).toBeNull()
})
})
describe('assertBranchPrefixValid', () => {
it('does not throw for a valid prefix', () => {
expect(() => assertBranchPrefixValid('team')).not.toThrow()
})
it('throws with a settings hint for an invalid prefix', () => {
expect(() => assertBranchPrefixValid('team x')).toThrow(
'Branch prefix "team x" contains characters git rejects — update it in Settings → Git'
)
})
})
+104
View File
@@ -0,0 +1,104 @@
import type { BranchPrefixStrategy } from './types'
/** The branch-prefix settings slice the prefix helpers read. */
export type BranchPrefixSettings = {
branchPrefix: BranchPrefixStrategy
branchPrefixCustom?: string
}
/**
* Pick the raw, un-normalized value the configured strategy contributes, or
* null when no prefix applies. Shared so the main-process branch builder and
* the renderer's live settings feedback agree on which field each strategy uses.
*/
export function selectBranchPrefixInput(
settings: BranchPrefixSettings,
gitUsername: string | null
): string | null {
switch (settings.branchPrefix) {
case 'git-username':
return gitUsername
case 'custom':
return settings.branchPrefixCustom ?? null
case 'none':
return null
}
}
/**
* Normalize a configured branch prefix into the segment that gets prepended
* before the `/` separator when building a branch name.
*
* Why: the branch-name join (`${prefix}/${leaf}`) already inserts a single `/`,
* so a user-typed prefix like `team/` would otherwise yield `team//name`, which
* git check-ref-format rejects. Strip surrounding whitespace and slashes and
* collapse internal runs so the join always produces exactly one separator.
* Legitimate multi-segment prefixes (e.g. `team/frontend`) are preserved.
*/
export function normalizeBranchPrefix(rawPrefix: string): string {
return rawPrefix
.trim()
.replace(/^\/+|\/+$/g, '')
.replace(/\/{2,}/g, '/')
}
// Ref-reserved characters git check-ref-format rejects inside a branch name.
const INVALID_BRANCH_PREFIX_CHARS = /[~^:?*[\\]/
/**
* Whether the value contains an ASCII control character or space, both of which
* git rejects. Checked by code point (like `sanitizeWorktreeDisplayName`) to
* avoid a control-character regex that the linter forbids.
*/
function hasControlOrSpace(value: string): boolean {
return [...value].some((char) => {
const code = char.charCodeAt(0)
return code <= 0x20 || code === 0x7f
})
}
/**
* Detect whether a branch prefix, after normalization, still contains characters
* git check-ref-format rejects. Returns a reason code (not a UI string, so the
* renderer owns translation) or null when the prefix is usable.
*
* This is a lightweight mirror of the relevant check-ref-format rules for live
* settings feedback; git remains the source of truth at worktree-create time.
*/
export function getBranchPrefixIssue(rawPrefix: string): 'invalid-characters' | null {
const normalized = normalizeBranchPrefix(rawPrefix)
if (!normalized) {
// Empty after normalization means "no prefix" — valid.
return null
}
// Mirror git check-ref-format exactly so we don't reject prefixes git accepts:
// control chars/space, the ref-reserved set, `..`, and `@{` are forbidden
// anywhere; the whole ref may not start with `-` (arg-injection / leading-dash)
// nor end with `.`; and each `/`-segment may not start with `.` nor end with
// `.lock`. Hyphens and mid-segment dots elsewhere are fine (e.g. `team./x`).
if (
hasControlOrSpace(normalized) ||
INVALID_BRANCH_PREFIX_CHARS.test(normalized) ||
normalized.includes('..') ||
normalized.includes('@{') ||
normalized.startsWith('-') ||
normalized.endsWith('.') ||
normalized.split('/').some((seg) => seg.startsWith('.') || seg.endsWith('.lock'))
) {
return 'invalid-characters'
}
return null
}
/**
* Fail fast when a configured prefix would produce a branch name git rejects.
* Used on the main-process worktree-create path so users get a clear error
* instead of an opaque check-ref-format failure later.
*/
export function assertBranchPrefixValid(prefix: string): void {
if (getBranchPrefixIssue(prefix) !== null) {
throw new Error(
`Branch prefix "${prefix}" contains characters git rejects — update it in Settings → Git`
)
}
}
+4 -1
View File
@@ -2577,6 +2577,9 @@ export type SourceControlGroupOrder = 'changes-first' | 'staged-first' | 'untrac
export type LeftSidebarAppearanceMode = 'default' | 'match-terminal' | 'tinted'
/** Strategy for the prefix prepended to worktree branch names. */
export type BranchPrefixStrategy = 'git-username' | 'custom' | 'none'
export type FloatingTerminalCwdRequest = {
path?: string
requireTrusted?: boolean
@@ -2612,7 +2615,7 @@ export type GlobalSettings = {
/** One-shot migration guard for the default-on rollout. Existing profiles
* without the guard are flipped on once; later explicit opt-outs stick. */
autoRenameBranchFromWorkDefaultedOn?: boolean
branchPrefix: 'git-username' | 'custom' | 'none'
branchPrefix: BranchPrefixStrategy
branchPrefixCustom: string
enableGitHubAttribution: boolean
theme: 'system' | 'dark' | 'light'