Files
orca/src/shared/git-remote-error.ts
T
Jinjing 527c692b71 Improve git pull on remote (#8524)
* Fall back to a merge when a divergent pull has no reconciliation strateg

- Git 2.27+ refuses `git pull` on divergent branches unless pull.rebase or
  pull.ff is configured. Retry with `--no-rebase` (Git's historical default)
  so pulls succeed out of the box on fresh hosts.
- Skip the fallback whenever the caller already specified a reconciliation
  strategy (e.g. --ff-only, --rebase) so explicit policies still fail as
  expected on divergence.
- Applied identically in the local git pull path and the relay/SSH git
  handler so both surfaces behave the same way.

* Refactor divergent-pull merge fallback into shared helper

Extracts the retry-as-merge logic (duplicated between local git and
relay SSH pull paths) into `runPullWithDivergenceFallback` in
git-remote-error.ts, so both callers share one implementation and
test coverage.
2026-07-13 12:42:55 -07:00

231 lines
11 KiB
TypeScript

import { isPushHookFailure } from './source-control-push-failure'
// Why: git's stderr often embeds the full remote URL, which can include a
// credential. Redact carefully: classic `user:password@` forms always carry
// a credential on any scheme (HTTPS, ssh://, git://, git+ssh://), but a
// lone `user@` is a credential ONLY for HTTP(S) (e.g. token-only PATs like
// `https://ghp_xxx@host`). For `ssh://git@host/...` the `git` login is
// required by the SSH remote — stripping it would produce a broken URL in
// the surfaced error and hide which remote actually failed. The two
// scheme-scoped patterns below keep SSH user-info intact while still
// scrubbing passwords on any scheme and HTTPS token-only forms.
const USERPASS_URL_PATTERN = /([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi
const HTTPS_TOKEN_URL_PATTERN = /(https?:\/\/)[^\s/@:]+@/gi
const SUBMODULE_PUSH_FAILURE_PATTERN = /Unable to push submodule ['"](.+?)['"]/i
const SUBMODULE_PUSH_FAILURE_SENTINEL_PATTERN =
/failed to push all needed submodules|Unable to push submodule/i
const SUBMODULE_REMOTE_CHANGED_PATTERN =
/non-fast-forward|fetch first|updates were rejected|remote contains work that you do not have/i
const NORMALIZED_SUBMODULE_PUSH_FAILURE_PATTERN =
/(?:^|:\s)((?:Submodule '[^'\n]+'|A submodule) (?:has remote changes\. Pull inside the submodule, then try again\.|could not be pushed\. Resolve the submodule push error, then try again\.))(?:$|\s)/i
const DIVERGENT_PULL_RECONCILIATION_PATTERN =
/Need to specify how to reconcile divergent branches|divergent branches and need to specify how to reconcile them/i
// Why: any of these already pin a reconciliation strategy, so the merge
// fallback must not override an explicit caller/user choice (e.g. --ff-only).
const RECONCILIATION_PULL_ARG_PATTERN =
/^(--rebase|--no-rebase|--ff-only|--ff|--no-ff|--merge|-r)(=|$)/
// Why: merge is Git's historical pre-2.27 default. Falling back to it lets
// divergent pulls reconcile on fresh hosts that never configured pull.rebase
// or pull.ff, instead of failing outright. `--no-rebase` predates the 2.25
// baseline, so it is safe across all supported Git binaries.
export const MERGE_RECONCILIATION_PULL_ARGS = ['--no-rebase']
export function stripCredentialsFromMessage(message: string): string {
return message.replace(USERPASS_URL_PATTERN, '$1').replace(HTTPS_TOKEN_URL_PATTERN, '$1')
}
export function formatSubmodulePushFailureDetail(message: string): string | null {
const raw = stripCredentialsFromMessage(message)
const trimmed = raw.trim()
const normalizedMatch = trimmed.match(NORMALIZED_SUBMODULE_PUSH_FAILURE_PATTERN)
if (normalizedMatch) {
return normalizedMatch[1]
}
if (!SUBMODULE_PUSH_FAILURE_SENTINEL_PATTERN.test(trimmed)) {
return null
}
// Why: recursive push can hide the actionable nested rejection behind a
// top-level "failed to push all needed submodules" fatal line.
const submoduleName = trimmed.match(SUBMODULE_PUSH_FAILURE_PATTERN)?.[1]?.trim()
const subject = submoduleName ? `Submodule '${submoduleName}'` : 'A submodule'
if (SUBMODULE_REMOTE_CHANGED_PATTERN.test(trimmed)) {
return `${subject} has remote changes. Pull inside the submodule, then try again.`
}
return `${subject} could not be pushed. Resolve the submodule push error, then try again.`
}
function extractTailLine(message: string): string {
// Why: execFile rejections prefix the message with "Command failed: git ..."
// followed by the full stderr. The meaningful diagnostic is typically the
// last non-empty line; surfacing the full blob risks leaking local paths or
// environment details to the UI.
for (const rawLine of iterateLinesFromEnd(message)) {
const line = rawLine.trim()
if (line.length > 0) {
return line
}
}
return message
}
function* iterateLinesFromEnd(value: string): Generator<string> {
let lineEnd = value.length
let index = value.length - 1
while (index >= 0) {
const code = value.charCodeAt(index)
if (code !== 10 && code !== 13) {
index--
continue
}
const delimiterStart =
code === 10 && index > 0 && value.charCodeAt(index - 1) === 13 ? index - 1 : index
yield value.slice(index + 1, lineEnd)
lineEnd = delimiterStart
index = delimiterStart - 1
}
yield value.slice(0, lineEnd)
}
// Why: a fresh host may lack any pull.rebase/pull.ff policy, so Git 2.27+
// refuses to reconcile divergent branches. Detect that specific failure so the
// caller can retry with an explicit merge instead of surfacing a config error.
export function isDivergentPullReconciliationError(error: unknown): boolean {
if (!(error instanceof Error)) {
return false
}
return DIVERGENT_PULL_RECONCILIATION_PATTERN.test(stripCredentialsFromMessage(error.message))
}
// Whether the pull already specifies how to reconcile (rebase/merge/ff-only),
// in which case the caller's choice must win over the merge fallback.
export function pullArgsSpecifyReconciliation(pullArgs: string[]): boolean {
return pullArgs.some((arg) => RECONCILIATION_PULL_ARG_PATTERN.test(arg))
}
// Why: on hosts with no pull.rebase/pull.ff policy, Git 2.27+ refuses to
// reconcile divergent branches. Retry as a merge (Git's historical default) so
// pulls succeed out of the box; callers that already forced a strategy — or
// users who configured rebase — never reach this fallback.
// Not routed through GitCapabilityCache: this is per-repo config/branch state,
// not a stable host capability, and only fires on an actual divergence error,
// so there is nothing host-scoped to cache.
export async function runPullWithDivergenceFallback(
pullArgs: string[],
runPull: (effectiveArgs: string[]) => Promise<void>
): Promise<void> {
try {
await runPull(pullArgs)
} catch (error) {
if (!pullArgsSpecifyReconciliation(pullArgs) && isDivergentPullReconciliationError(error)) {
await runPull([...MERGE_RECONCILIATION_PULL_ARGS, ...pullArgs])
return
}
throw error
}
}
export type GitRemoteOperation = 'push' | 'pull' | 'fetch' | 'upstream'
export function normalizeGitErrorMessage(error: unknown, operation?: GitRemoteOperation): string {
if (!(error instanceof Error)) {
return 'Git remote operation failed.'
}
// Why: scrub credentials up-front so every downstream branch — including
// any future refactor that returns a substring of `raw` — operates on
// already-redacted text. The fast-path branches below return fixed
// literals today, but this hardens against accidental leakage later.
const raw = stripCredentialsFromMessage(error.message)
const submodulePushFailureDetail = formatSubmodulePushFailureDetail(raw)
if ((operation === 'push' || operation === undefined) && submodulePushFailureDetail) {
return submodulePushFailureDetail
}
// Why: `non-fast-forward` / `fetch first` can appear on fetch (after a
// remote force-push updating a tracking ref) and on pull (with
// `pull.ff=only`), so the "pull or sync first" guidance only makes sense
// when the user was actually pushing. For other operations, fall through
// to the generic tail-line path. `operation === undefined` keeps the
// legacy push-shaped message for any caller that hasn't been updated yet.
if (
(operation === 'push' || operation === undefined) &&
(raw.includes('non-fast-forward') || raw.includes('fetch first'))
) {
return 'Push rejected: remote has newer commits (non-fast-forward). Please pull or sync first.'
}
if (operation === 'push' && isPushHookFailure(raw)) {
// Why: local pre-push hooks put the actionable lint/hook output before
// git's generic "failed to push some refs" tail line.
return raw.trim()
}
if (raw.includes('could not read Username') || raw.includes('Authentication failed')) {
return 'Authentication failed. Check your remote credentials.'
}
if (raw.includes('Could not resolve host') || raw.includes('Network is unreachable')) {
return 'Network error. Check your connection.'
}
if (raw.includes('no tracking information') || raw.includes('no upstream')) {
return 'Branch has no upstream. Publish the branch first.'
}
if (operation === 'pull' && DIVERGENT_PULL_RECONCILIATION_PATTERN.test(raw)) {
return (
'Pull needs a Git pull policy for divergent branches. Configure one for this repository ' +
'or host, then try again: git config pull.rebase false (merge), ' +
'git config pull.rebase true (rebase), or git config pull.ff only (fast-forward only).'
)
}
if (
raw.includes('Your local changes to the following files would be overwritten') ||
raw.includes('Your local changes would be overwritten')
) {
return 'Pull would overwrite local changes. Commit, stash, or discard them before pulling.'
}
if (raw.includes('untracked working tree files would be overwritten')) {
return 'Pull would overwrite untracked files. Move, remove, or add them before pulling.'
}
// Fallthrough: extract only the tail stderr line. `raw` was already
// credential-scrubbed at the top of the function, so no further scrub needed.
return extractTailLine(raw)
}
// Why: we only swallow clearly-no-upstream signals — an expected state, not a
// failure. Other errors ('not a git repository', 'corrupt', auth failures,
// sparse-checkout errors, etc.) must fall through to the caller so users can
// act on them. We explicitly avoid matching `HEAD@{u}` alone because execFile
// wraps errors with "Command failed: git rev-parse --abbrev-ref HEAD@{u}…",
// which would cause every non-repo/corrupt failure to spuriously look like
// no-upstream. We also do NOT match 'no such branch' — that phrase is too
// broad and can mask real errors on corrupt refs or sparse-checkout failures.
// Additionally gate the phrase match on a `fatal:` prefix: git always
// prefixes these diagnostics with `fatal:`, so requiring it prevents
// `HEAD does not point` / `Needed a single revision` from matching unrelated
// output (e.g. hook stdout, progress lines) and silently hiding real
// corrupt-repo / unborn-HEAD / ambiguous-ref failures behind a spurious
// "0 ahead / 0 behind, no upstream" UI state. The one ambiguous-ref
// exception is HEAD@{u}: git emits it when branch config points at a
// tracking ref that is missing locally, which is the same expected UX state.
const NO_UPSTREAM_PHRASE_PATTERN =
/no upstream configured|no tracking information|HEAD does not point|Needed a single revision|ambiguous argument 'HEAD@\{u\}'/i
const FATAL_PREFIX_PATTERN = /(^|\n)fatal:/i
export function isNoUpstreamError(error: unknown): boolean {
if (!(error instanceof Error)) {
return false
}
const message = error.message
return FATAL_PREFIX_PATTERN.test(message) && NO_UPSTREAM_PHRASE_PATTERN.test(message)
}