Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -12,8 +12,6 @@
|
||||
* the github rate-limit prober can use it without an import cycle.
|
||||
*/
|
||||
|
||||
import { cacheIdentityDigest } from '../cache-identity-digest'
|
||||
|
||||
export type GhRateLimitBucket = 'core' | 'search' | 'graphql'
|
||||
|
||||
// Why: a primary 403 does not carry the reset time. The search window resets
|
||||
@@ -64,7 +62,7 @@ const blockedUntilMsByScopeAndBucket = new Map<string, number>()
|
||||
let resetProbe: ((bucket: GhRateLimitBucket, scope: string) => void) | null = null
|
||||
|
||||
function breakerKey(bucket: GhRateLimitBucket, scope = DEFAULT_SCOPE): string {
|
||||
return cacheIdentityDigest([scope, bucket])
|
||||
return `${scope}\0${bucket}`
|
||||
}
|
||||
|
||||
// gh api flags that take a separate value, so the endpoint arg can be found.
|
||||
|
||||
@@ -2,9 +2,7 @@ import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
clearGitCapabilityStateForTests,
|
||||
getLocalGitCapabilityCache,
|
||||
getSshGitCapabilityCache,
|
||||
LOCAL_GIT_CAPABILITY_HOST_KEY_MAX_BYTES,
|
||||
LOCAL_GIT_CAPABILITY_HOST_MAX_ENTRIES
|
||||
getSshGitCapabilityCache
|
||||
} from './git-capability-state'
|
||||
|
||||
describe('Git capability execution-host state', () => {
|
||||
@@ -36,27 +34,4 @@ describe('Git capability execution-host state', () => {
|
||||
getSshGitCapabilityCache(replacementProvider)
|
||||
)
|
||||
})
|
||||
|
||||
it('evicts the oldest local execution host after the host ceiling', () => {
|
||||
const oldest = getLocalGitCapabilityCache({ wslDistro: 'Distro-0' })
|
||||
let newest = oldest
|
||||
for (let index = 1; index <= LOCAL_GIT_CAPABILITY_HOST_MAX_ENTRIES; index++) {
|
||||
newest = getLocalGitCapabilityCache({ wslDistro: `Distro-${index}` })
|
||||
}
|
||||
|
||||
expect(getLocalGitCapabilityCache({ wslDistro: 'Distro-0' })).not.toBe(oldest)
|
||||
expect(
|
||||
getLocalGitCapabilityCache({
|
||||
wslDistro: `Distro-${LOCAL_GIT_CAPABILITY_HOST_MAX_ENTRIES}`
|
||||
})
|
||||
).toBe(newest)
|
||||
})
|
||||
|
||||
it('does not retain oversized execution-host keys', () => {
|
||||
const oversizedDistro = 'x'.repeat(LOCAL_GIT_CAPABILITY_HOST_KEY_MAX_BYTES + 1)
|
||||
|
||||
expect(getLocalGitCapabilityCache({ wslDistro: oversizedDistro })).not.toBe(
|
||||
getLocalGitCapabilityCache({ wslDistro: oversizedDistro })
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { GitCapabilityCache } from '../../shared/git-capability-cache'
|
||||
import { measureUtf8ByteLength } from '../../shared/utf8-byte-limits'
|
||||
import { parseWslUncPath } from '../../shared/wsl-paths'
|
||||
|
||||
type LocalGitCapabilityTarget = {
|
||||
@@ -7,8 +6,6 @@ type LocalGitCapabilityTarget = {
|
||||
wslDistro?: string
|
||||
}
|
||||
|
||||
export const LOCAL_GIT_CAPABILITY_HOST_MAX_ENTRIES = 64
|
||||
export const LOCAL_GIT_CAPABILITY_HOST_KEY_MAX_BYTES = 4 * 1024
|
||||
const localCapabilitiesByExecutionHost = new Map<string, GitCapabilityCache>()
|
||||
// Why: reconnecting creates a new provider, while concurrent IPC/runtime users
|
||||
// of one SSH connection must share the same remote Git capability results.
|
||||
@@ -24,24 +21,10 @@ export function getLocalGitCapabilityCache(
|
||||
target: LocalGitCapabilityTarget = {}
|
||||
): GitCapabilityCache {
|
||||
const executionHost = getLocalGitExecutionHostKey(target)
|
||||
if (
|
||||
measureUtf8ByteLength(executionHost, {
|
||||
stopAfterBytes: LOCAL_GIT_CAPABILITY_HOST_KEY_MAX_BYTES
|
||||
}).exceededLimit
|
||||
) {
|
||||
return new GitCapabilityCache()
|
||||
}
|
||||
let cache = localCapabilitiesByExecutionHost.get(executionHost)
|
||||
if (!cache) {
|
||||
cache = new GitCapabilityCache()
|
||||
localCapabilitiesByExecutionHost.set(executionHost, cache)
|
||||
while (localCapabilitiesByExecutionHost.size > LOCAL_GIT_CAPABILITY_HOST_MAX_ENTRIES) {
|
||||
const oldestHost = localCapabilitiesByExecutionHost.keys().next().value
|
||||
if (oldestHost === undefined) {
|
||||
break
|
||||
}
|
||||
localCapabilitiesByExecutionHost.delete(oldestHost)
|
||||
}
|
||||
}
|
||||
return cache
|
||||
}
|
||||
|
||||
@@ -84,35 +84,6 @@ describe('appendFolderToGitignore', () => {
|
||||
expect(wrote).toBe(false)
|
||||
})
|
||||
|
||||
it('streams a large single-line file while preserving append semantics', async () => {
|
||||
const gitignorePath = path.join(dir, '.gitignore')
|
||||
await fs.writeFile(gitignorePath, 'x')
|
||||
await fs.truncate(gitignorePath, 8 * 1024 * 1024)
|
||||
|
||||
expect(await appendFolderToGitignore(dir, 'dist')).toBe(true)
|
||||
|
||||
const handle = await fs.open(gitignorePath, 'r')
|
||||
try {
|
||||
const info = await handle.stat()
|
||||
const tail = Buffer.alloc(7)
|
||||
await handle.read(tail, 0, tail.length, info.size - tail.length)
|
||||
expect(tail.toString('utf8')).toBe('\ndist/\n')
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves trimmed-line matching across streamed chunks', async () => {
|
||||
const gitignorePath = path.join(dir, '.gitignore')
|
||||
await fs.writeFile(gitignorePath, 'x')
|
||||
await fs.truncate(gitignorePath, 8 * 1024 * 1024)
|
||||
await fs.appendFile(gitignorePath, '\n\u00a0node_modules/\u00a0\n')
|
||||
const sizeBefore = (await fs.stat(gitignorePath)).size
|
||||
|
||||
expect(await appendFolderToGitignore(dir, 'node_modules')).toBe(false)
|
||||
expect((await fs.stat(gitignorePath)).size).toBe(sizeBefore)
|
||||
})
|
||||
|
||||
it('rejects folder names outside the known allowlist (injection guard)', async () => {
|
||||
await expect(appendFolderToGitignore(dir, 'node_modules\n/etc/passwd')).rejects.toThrow(
|
||||
/Refusing to add/
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { createReadStream, existsSync } from 'node:fs'
|
||||
import { appendFile, stat } from 'node:fs/promises'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { appendFile, readFile, stat } from 'node:fs/promises'
|
||||
import * as path from 'node:path'
|
||||
import { StringDecoder } from 'node:string_decoder'
|
||||
import { checkIgnoredPaths } from './check-ignored-paths'
|
||||
import type { GitRuntimeOptions } from './git-runtime-options'
|
||||
|
||||
@@ -10,78 +9,6 @@ import type { GitRuntimeOptions } from './git-runtime-options'
|
||||
// to ignore these by name (matching the well-known offenders) the way a mature
|
||||
// SCM does, rather than asking the user to hand-edit .gitignore.
|
||||
const KNOWN_HUGE_FOLDER_NAMES = ['node_modules', '.next', 'dist', 'build', 'target', 'vendor']
|
||||
const GITIGNORE_SCAN_CHUNK_BYTES = 64 * 1024
|
||||
|
||||
type GitignoreScanResult = {
|
||||
alreadyListed: boolean
|
||||
hasContent: boolean
|
||||
endsWithNewline: boolean
|
||||
}
|
||||
|
||||
async function scanGitignoreForFolder(
|
||||
gitignorePath: string,
|
||||
folderName: string
|
||||
): Promise<GitignoreScanResult> {
|
||||
const targets = [folderName, `${folderName}/`]
|
||||
const decoder = new StringDecoder('utf8')
|
||||
const input = createReadStream(gitignorePath, { highWaterMark: GITIGNORE_SCAN_CHUNK_BYTES })
|
||||
let phase: 'leading' | 'candidate' | 'trailing' | 'rejected' = 'leading'
|
||||
let candidate = ''
|
||||
let alreadyListed = false
|
||||
let hasContent = false
|
||||
let endsWithNewline = false
|
||||
|
||||
const finishLine = (): void => {
|
||||
if (phase === 'trailing' || (phase === 'candidate' && targets.includes(candidate))) {
|
||||
alreadyListed = true
|
||||
}
|
||||
phase = 'leading'
|
||||
candidate = ''
|
||||
}
|
||||
const acceptText = (text: string): void => {
|
||||
for (const character of text) {
|
||||
if (character === '\n') {
|
||||
finishLine()
|
||||
continue
|
||||
}
|
||||
const whitespace = character.trim().length === 0
|
||||
if (phase === 'leading') {
|
||||
if (whitespace) {
|
||||
continue
|
||||
}
|
||||
candidate = character
|
||||
phase = targets.some((target) => target.startsWith(candidate)) ? 'candidate' : 'rejected'
|
||||
continue
|
||||
}
|
||||
if (phase === 'candidate') {
|
||||
if (whitespace) {
|
||||
phase = targets.includes(candidate) ? 'trailing' : 'rejected'
|
||||
continue
|
||||
}
|
||||
candidate += character
|
||||
if (!targets.some((target) => target.startsWith(candidate))) {
|
||||
phase = 'rejected'
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (phase === 'trailing' && !whitespace) {
|
||||
phase = 'rejected'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of input) {
|
||||
const buffer = chunk as Buffer
|
||||
hasContent ||= buffer.length > 0
|
||||
if (buffer.length > 0) {
|
||||
endsWithNewline = buffer.at(-1) === 0x0a
|
||||
}
|
||||
acceptText(decoder.write(buffer))
|
||||
}
|
||||
acceptText(decoder.end())
|
||||
finishLine()
|
||||
return { alreadyListed, hasContent, endsWithNewline }
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the relative names of known-huge folders that exist in the worktree and
|
||||
@@ -131,21 +58,21 @@ export async function appendFolderToGitignore(
|
||||
}
|
||||
const gitignorePath = path.join(worktreePath, '.gitignore')
|
||||
const line = `${safeFolderName}/`
|
||||
let scan: GitignoreScanResult = {
|
||||
alreadyListed: false,
|
||||
hasContent: false,
|
||||
endsWithNewline: false
|
||||
}
|
||||
let existingContent = ''
|
||||
try {
|
||||
scan = await scanGitignoreForFolder(gitignorePath, safeFolderName)
|
||||
existingContent = await readFile(gitignorePath, 'utf-8')
|
||||
} catch {
|
||||
// .gitignore doesn't exist yet — we'll create it below
|
||||
}
|
||||
if (scan.alreadyListed) {
|
||||
const alreadyListed = existingContent
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.some((l) => l === safeFolderName || l === line)
|
||||
if (alreadyListed) {
|
||||
return false
|
||||
}
|
||||
// Why: keep a clean trailing newline whether or not the file ended with one.
|
||||
const needsLeadingNewline = scan.hasContent && !scan.endsWithNewline
|
||||
const needsLeadingNewline = existingContent.length > 0 && !existingContent.endsWith('\n')
|
||||
await appendFile(gitignorePath, `${needsLeadingNewline ? '\n' : ''}${line}\n`, 'utf-8')
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { mkdirSync, mkdtempSync, truncateSync, writeFileSync } from 'node:fs'
|
||||
import { rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { isGitRepo, MAX_GIT_MARKER_FILE_BYTES } from './repo'
|
||||
|
||||
describe.sequential('Git marker fallback metadata bounds', () => {
|
||||
let root: string
|
||||
let originalPath: string | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
root = mkdtempSync(join(tmpdir(), 'orca-git-marker-bounds-'))
|
||||
originalPath = process.env.PATH
|
||||
process.env.PATH = ''
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (originalPath === undefined) {
|
||||
delete process.env.PATH
|
||||
} else {
|
||||
process.env.PATH = originalPath
|
||||
}
|
||||
await rm(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function writeOversizedSparseFile(filePath: string): void {
|
||||
writeFileSync(filePath, 'x')
|
||||
truncateSync(filePath, MAX_GIT_MARKER_FILE_BYTES + 1)
|
||||
}
|
||||
|
||||
it('rejects an oversized .git pointer without loading it', () => {
|
||||
const checkout = join(root, 'checkout')
|
||||
mkdirSync(checkout)
|
||||
writeOversizedSparseFile(join(checkout, '.git'))
|
||||
|
||||
expect(isGitRepo(checkout)).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects an oversized linked-worktree commondir pointer', () => {
|
||||
const checkout = join(root, 'checkout')
|
||||
const adminDir = join(root, 'admin')
|
||||
mkdirSync(checkout)
|
||||
mkdirSync(adminDir)
|
||||
writeFileSync(join(checkout, '.git'), `gitdir: ${adminDir}\n`)
|
||||
writeFileSync(join(adminDir, 'HEAD'), 'ref: refs/heads/main\n')
|
||||
writeOversizedSparseFile(join(adminDir, 'commondir'))
|
||||
|
||||
expect(isGitRepo(checkout)).toBe(false)
|
||||
})
|
||||
|
||||
it('checks a bare marker without retaining an oversized config', () => {
|
||||
const bareRepo = join(root, 'bare.git')
|
||||
mkdirSync(join(bareRepo, 'objects'), { recursive: true })
|
||||
mkdirSync(join(bareRepo, 'refs'))
|
||||
writeFileSync(join(bareRepo, 'HEAD'), 'ref: refs/heads/main\n')
|
||||
writeOversizedSparseFile(join(bareRepo, 'config'))
|
||||
|
||||
expect(isGitRepo(bareRepo)).toBe(true)
|
||||
})
|
||||
})
|
||||
+4
-15
@@ -1,5 +1,5 @@
|
||||
/* oxlint-disable max-lines */
|
||||
import { existsSync, realpathSync, statSync } from 'node:fs'
|
||||
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
||||
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
||||
import { gitExecFileSync, gitExecFileAsync } from './runner'
|
||||
import type { BaseRefSearchResult } from '../../shared/types'
|
||||
@@ -10,7 +10,6 @@ import { parseWslUncPath } from '../../shared/wsl-paths'
|
||||
import { toWindowsWslPath } from '../wsl'
|
||||
import { buildHostedRemoteCommitUrl, buildHostedRemoteFileUrl } from './hosted-remote-url'
|
||||
import { getLocalGitCapabilityCache } from './git-capability-state'
|
||||
import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader'
|
||||
|
||||
type LocalGitExecOptions = {
|
||||
wslDistro?: string
|
||||
@@ -22,7 +21,6 @@ type LocalDefaultBaseRefGitOptions = {
|
||||
}
|
||||
|
||||
const DEFAULT_BASE_REF_PROBE_TIMEOUT_MS = 15_000
|
||||
export const MAX_GIT_MARKER_FILE_BYTES = 64 * 1024
|
||||
|
||||
type GitRepoProbeResult = 'repo' | 'not-repo' | 'indeterminate'
|
||||
type GitMarkerScanResult = { status: 'valid'; rootPath: string } | { status: 'absent' | 'invalid' }
|
||||
@@ -278,10 +276,7 @@ function scanWorktreeMarkerSync(worktreePath: string): GitMarkerScanResult {
|
||||
if (marker.isFile()) {
|
||||
let gitDir: string | null
|
||||
try {
|
||||
gitDir = parseGitdirFile(
|
||||
worktreePath,
|
||||
readNodeFileSyncWithinLimit(dotGit, MAX_GIT_MARKER_FILE_BYTES).buffer.toString('utf8')
|
||||
)
|
||||
gitDir = parseGitdirFile(worktreePath, readFileSync(dotGit, 'utf8'))
|
||||
} catch {
|
||||
return { status: 'invalid' }
|
||||
}
|
||||
@@ -336,10 +331,7 @@ function hasValidLinkedWorktreeGitDirectorySync(gitDir: string): boolean {
|
||||
}
|
||||
const commonDir = resolveGitMetadataPath(
|
||||
gitDir,
|
||||
readNodeFileSyncWithinLimit(
|
||||
join(gitDir, 'commondir'),
|
||||
MAX_GIT_MARKER_FILE_BYTES
|
||||
).buffer.toString('utf8')
|
||||
readFileSync(join(gitDir, 'commondir'), 'utf8')
|
||||
)
|
||||
return commonDir !== null && hasValidCommonGitDirectorySync(commonDir)
|
||||
} catch {
|
||||
@@ -353,10 +345,7 @@ function hasValidBareRepoMarkerSync(path: string): boolean {
|
||||
|
||||
function gitConfigDeclaresNonBare(gitDir: string): boolean {
|
||||
try {
|
||||
const config = readNodeFileSyncWithinLimit(
|
||||
join(gitDir, 'config'),
|
||||
MAX_GIT_MARKER_FILE_BYTES
|
||||
).buffer.toString('utf8')
|
||||
const config = readFileSync(join(gitDir, 'config'), 'utf8')
|
||||
let inCoreSection = false
|
||||
for (const line of config.split(/\r?\n/)) {
|
||||
const section = line.match(/^\s*\[([^\]]+)\]/)
|
||||
|
||||
@@ -15,7 +15,6 @@ vi.mock('node:child_process', () => ({
|
||||
|
||||
import {
|
||||
commandExecFileAsync,
|
||||
DEFAULT_GIT_MAX_BUFFER,
|
||||
ghExecFileAsync,
|
||||
gitExecFileAsync,
|
||||
gitStreamStdout,
|
||||
@@ -156,35 +155,6 @@ describe('commandExecFileAsync Windows command shims', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('applies the default output cap to Windows .cmd shim executions', async () => {
|
||||
await withPlatform('win32', async () => {
|
||||
const command = createMockChildProcess(1234)
|
||||
const taskkill = createMockTaskkillProcess()
|
||||
spawnMock.mockImplementation((cmd: string) => (cmd === 'taskkill' ? taskkill : command))
|
||||
const toString = vi.fn(() => 'should not decode')
|
||||
const oversizedChunk = {
|
||||
byteLength: DEFAULT_GIT_MAX_BUFFER + 1,
|
||||
toString
|
||||
} as unknown as Buffer
|
||||
|
||||
const promise = commandExecFileAsync('C:\\tools\\pnpm.cmd', ['store', 'prune'], {
|
||||
cwd: 'C:\\repo'
|
||||
})
|
||||
const rejection = expect(promise).rejects.toThrow(
|
||||
'C:\\tools\\pnpm.cmd stdout exceeded maxBuffer.'
|
||||
)
|
||||
command.stdout.emit('data', oversizedChunk)
|
||||
|
||||
await rejection
|
||||
expect(toString).not.toHaveBeenCalled()
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
'taskkill',
|
||||
['/pid', '1234', '/t', '/f'],
|
||||
expect.objectContaining({ stdio: 'ignore', windowsHide: true })
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('removes listeners after successful Windows .cmd shim executions', async () => {
|
||||
await withPlatform('win32', async () => {
|
||||
const command = createMockChildProcess(1234)
|
||||
@@ -204,26 +174,6 @@ describe('commandExecFileAsync Windows command shims', () => {
|
||||
expect(command.listenerCount('close')).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
it('captures 100,000 one-byte fragments from a Windows command shim', async () => {
|
||||
await withPlatform('win32', async () => {
|
||||
const command = createMockChildProcess(1234)
|
||||
spawnMock.mockReturnValue(command)
|
||||
const promise = commandExecFileAsync('C:\\tools\\pnpm.cmd', ['--version'], {
|
||||
cwd: 'C:\\repo'
|
||||
})
|
||||
const fragment = Buffer.from('x')
|
||||
|
||||
for (let index = 0; index < 100_000; index += 1) {
|
||||
command.stdout.emit('data', fragment)
|
||||
}
|
||||
command.emit('close', 0)
|
||||
|
||||
const result = await promise
|
||||
expect(result.stdout).toHaveLength(100_000)
|
||||
expect(result.stdout.slice(-4)).toBe('xxxx')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('runner execFile timeout handling', () => {
|
||||
@@ -695,21 +645,6 @@ describe('gitStreamStdout', () => {
|
||||
await rejection
|
||||
})
|
||||
|
||||
it('captures streamed stderr delivered as 100,000 one-byte fragments', async () => {
|
||||
const child = createMockChildProcess(1234)
|
||||
spawnMock.mockReturnValue(child)
|
||||
const promise = gitStreamStdout(['status'], { cwd: '/repo', onStdout: () => {} })
|
||||
const fragment = Buffer.from(' ')
|
||||
|
||||
for (let index = 0; index < 100_000; index += 1) {
|
||||
child.stderr.emit('data', fragment)
|
||||
}
|
||||
child.stderr.emit('data', Buffer.from('fatal: fragmented'))
|
||||
child.emit('close', 128)
|
||||
|
||||
await expect(promise).rejects.toThrow(/fatal: fragmented$/)
|
||||
})
|
||||
|
||||
it('rejects (not crashes) when the onStdout callback throws', async () => {
|
||||
const child = createMockChildProcess(1234)
|
||||
spawnMock.mockReturnValue(child)
|
||||
|
||||
+21
-21
@@ -33,7 +33,6 @@ import {
|
||||
appendGitConfigEnv,
|
||||
gitCredentialPromptGuardEnv
|
||||
} from '../../shared/git-credential-prompt-env'
|
||||
import { GrowingByteBuffer } from '../../shared/growing-byte-buffer'
|
||||
import { getSpawnArgsForWindows, isWindowsBatchScript, resolveWindowsCommand } from '../win32-utils'
|
||||
import {
|
||||
buildWslLoginShellCommand,
|
||||
@@ -498,7 +497,6 @@ async function spawnCommandCapture(
|
||||
args: string[],
|
||||
options: CommandExecOptions
|
||||
): Promise<{ stdout: string; stderr: string }> {
|
||||
const maxBuffer = options.maxBuffer ?? DEFAULT_GIT_MAX_BUFFER
|
||||
const { spawnCmd, spawnArgs } = getSpawnArgsForWindows(command, args)
|
||||
return new Promise((resolve, reject) => {
|
||||
if (options.signal?.aborted) {
|
||||
@@ -506,8 +504,10 @@ async function spawnCommandCapture(
|
||||
return
|
||||
}
|
||||
let settled = false
|
||||
const stdout = new GrowingByteBuffer()
|
||||
const stderr = new GrowingByteBuffer()
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
let stdoutBytes = 0
|
||||
let stderrBytes = 0
|
||||
const spawnStartedAt = performance.now()
|
||||
const child = spawn(spawnCmd, spawnArgs, {
|
||||
cwd: options.cwd,
|
||||
@@ -538,15 +538,11 @@ async function spawnCommandCapture(
|
||||
}
|
||||
settled = true
|
||||
cleanupListeners()
|
||||
const stdoutText = stdout.toString(options.encoding ?? 'utf-8')
|
||||
const stderrText = stderr.toString(options.encoding ?? 'utf-8')
|
||||
stdout.clear()
|
||||
stderr.clear()
|
||||
if (error) {
|
||||
reject(Object.assign(error, { stdout: stdoutText, stderr: stderrText }))
|
||||
reject(Object.assign(error, { stdout, stderr }))
|
||||
return
|
||||
}
|
||||
resolve({ stdout: stdoutText, stderr: stderrText })
|
||||
resolve({ stdout, stderr })
|
||||
}
|
||||
timer = options.timeout
|
||||
? setTimeout(() => {
|
||||
@@ -556,20 +552,22 @@ async function spawnCommandCapture(
|
||||
: null
|
||||
options.signal?.addEventListener('abort', onAbort, { once: true })
|
||||
function onStdoutData(chunk: Buffer): void {
|
||||
if (stdout.byteLength + chunk.byteLength > maxBuffer) {
|
||||
stdoutBytes += chunk.byteLength
|
||||
if (options.maxBuffer && stdoutBytes > options.maxBuffer) {
|
||||
void killSpawnedCommandTree(child)
|
||||
finish(new Error(`${command} stdout exceeded maxBuffer.`))
|
||||
return
|
||||
}
|
||||
stdout.append(chunk)
|
||||
stdout += chunk.toString(options.encoding ?? 'utf-8')
|
||||
}
|
||||
function onStderrData(chunk: Buffer): void {
|
||||
if (stderr.byteLength + chunk.byteLength > maxBuffer) {
|
||||
stderrBytes += chunk.byteLength
|
||||
if (options.maxBuffer && stderrBytes > options.maxBuffer) {
|
||||
void killSpawnedCommandTree(child)
|
||||
finish(new Error(`${command} stderr exceeded maxBuffer.`))
|
||||
return
|
||||
}
|
||||
stderr.append(chunk)
|
||||
stderr += chunk.toString(options.encoding ?? 'utf-8')
|
||||
}
|
||||
function onError(error: Error): void {
|
||||
finish(error)
|
||||
@@ -974,9 +972,11 @@ export async function gitStreamStdout(
|
||||
let settled = false
|
||||
let stoppedEarly = false
|
||||
let stdoutBytes = 0
|
||||
const stderr = new GrowingByteBuffer()
|
||||
let stderr = ''
|
||||
let stderrBytes = 0
|
||||
// Why: decode statefully so a multibyte UTF-8 char split across chunks isn't corrupted into replacement chars.
|
||||
const stdoutDecoder = new StringDecoder('utf8')
|
||||
const stderrDecoder = new StringDecoder('utf8')
|
||||
|
||||
const cleanup = (): void => {
|
||||
child.stdout?.off('data', onStdoutData)
|
||||
@@ -986,6 +986,7 @@ export async function gitStreamStdout(
|
||||
options.signal?.removeEventListener('abort', onAbort)
|
||||
// Flush any bytes the decoders were holding for an incomplete sequence.
|
||||
stdoutDecoder.end()
|
||||
stderrDecoder.end()
|
||||
}
|
||||
const finish = (error: Error | null): void => {
|
||||
if (settled) {
|
||||
@@ -993,10 +994,8 @@ export async function gitStreamStdout(
|
||||
}
|
||||
settled = true
|
||||
cleanup()
|
||||
const stderrText = stderr.toString()
|
||||
stderr.clear()
|
||||
if (error) {
|
||||
reject(Object.assign(error, { stderr: stderrText }))
|
||||
reject(Object.assign(error, { stderr }))
|
||||
return
|
||||
}
|
||||
resolve({ stoppedEarly })
|
||||
@@ -1030,12 +1029,13 @@ export async function gitStreamStdout(
|
||||
}
|
||||
}
|
||||
function onStderrData(chunk: Buffer): void {
|
||||
if (stderr.byteLength + chunk.byteLength > maxBuffer) {
|
||||
stderrBytes += chunk.byteLength
|
||||
if (stderrBytes > maxBuffer) {
|
||||
void killSpawnedCommandTree(child)
|
||||
finish(new Error('git stderr exceeded maxBuffer.'))
|
||||
return
|
||||
}
|
||||
stderr.append(chunk)
|
||||
stderr += stderrDecoder.write(chunk)
|
||||
}
|
||||
function onError(error: Error): void {
|
||||
finish(error)
|
||||
@@ -1045,7 +1045,7 @@ export async function gitStreamStdout(
|
||||
finish(null)
|
||||
return
|
||||
}
|
||||
finish(new Error(`git exited with ${code}: ${stderr.toString()}`))
|
||||
finish(new Error(`git exited with ${code}: ${stderr}`))
|
||||
}
|
||||
function onAbort(): void {
|
||||
if (!child.pid) {
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { mkdir, mkdtemp, rm, truncate, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { resolveGitDir } from './status'
|
||||
|
||||
describe('resolveGitDir metadata bounds', () => {
|
||||
const roots: string[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
|
||||
})
|
||||
|
||||
async function makeWorktree(): Promise<string> {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-resolve-git-dir-'))
|
||||
roots.push(root)
|
||||
const worktreePath = join(root, 'checkout')
|
||||
await mkdir(worktreePath)
|
||||
return worktreePath
|
||||
}
|
||||
|
||||
it('preserves a normal linked-worktree pointer', async () => {
|
||||
const worktreePath = await makeWorktree()
|
||||
await writeFile(join(worktreePath, '.git'), 'gitdir: ../common/.git/worktrees/checkout\n')
|
||||
|
||||
await expect(resolveGitDir(worktreePath)).resolves.toBe(
|
||||
join(worktreePath, '..', 'common', '.git', 'worktrees', 'checkout')
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to the .git path for an oversized sparse pointer', async () => {
|
||||
const worktreePath = await makeWorktree()
|
||||
const dotGitPath = join(worktreePath, '.git')
|
||||
await writeFile(dotGitPath, 'x')
|
||||
await truncate(dotGitPath, 64 * 1024 + 1)
|
||||
|
||||
await expect(resolveGitDir(worktreePath)).resolves.toBe(dotGitPath)
|
||||
})
|
||||
})
|
||||
@@ -1,87 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { gitExecFileAsyncMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: vi.fn() }))
|
||||
|
||||
vi.mock('./runner', () => ({
|
||||
gitExecFileAsync: gitExecFileAsyncMock,
|
||||
gitOptionalLocksDisabledEnv: (env: NodeJS.ProcessEnv = process.env) => ({
|
||||
...env,
|
||||
GIT_OPTIONAL_LOCKS: '0'
|
||||
})
|
||||
}))
|
||||
|
||||
import {
|
||||
clearSubmodulePathsCacheForTests,
|
||||
getSubmodulePathsCacheCodeUnitsForTests,
|
||||
getSubmodulePathsCacheCountForTests,
|
||||
listSubmodulePaths,
|
||||
MAX_SUBMODULE_PATH_CODE_UNITS,
|
||||
MAX_SUBMODULE_PATHS_CACHE_CODE_UNITS,
|
||||
MAX_SUBMODULE_PATHS_PER_REPO
|
||||
} from './status'
|
||||
|
||||
describe('submodule path payload bounds', () => {
|
||||
beforeEach(() => {
|
||||
clearSubmodulePathsCacheForTests()
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
})
|
||||
|
||||
it('preserves under-limit path order and cache reuse', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValue({
|
||||
stdout: 'submodule.one.path packages/one\nsubmodule.two.path packages/two/\n'
|
||||
})
|
||||
|
||||
await expect(listSubmodulePaths('/repo')).resolves.toEqual(['packages/one', 'packages/two'])
|
||||
await expect(listSubmodulePaths('/repo')).resolves.toEqual(['packages/one', 'packages/two'])
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('fails closed above the per-repository path count', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValue({
|
||||
stdout: Array.from(
|
||||
{ length: MAX_SUBMODULE_PATHS_PER_REPO + 1 },
|
||||
(_, index) => `submodule.s${index}.path modules/${index}\n`
|
||||
).join('')
|
||||
})
|
||||
|
||||
await expect(listSubmodulePaths('/repo')).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it('fails closed on a single oversized path', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValue({
|
||||
stdout: `submodule.large.path ${'x'.repeat(MAX_SUBMODULE_PATH_CODE_UNITS + 1)}\n`
|
||||
})
|
||||
|
||||
await expect(listSubmodulePaths('/repo')).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it('evicts old payloads at the aggregate retained-code-unit budget', async () => {
|
||||
const segment = 'x'.repeat(60 * 1024)
|
||||
const stdout = Array.from(
|
||||
{ length: 16 },
|
||||
(_, index) => `submodule.s${index}.path ${segment}${index}\n`
|
||||
).join('')
|
||||
gitExecFileAsyncMock.mockResolvedValue({ stdout })
|
||||
|
||||
for (let index = 0; index < 18; index += 1) {
|
||||
await listSubmodulePaths(`/repo-${index}`)
|
||||
}
|
||||
|
||||
expect(getSubmodulePathsCacheCodeUnitsForTests()).toBeLessThanOrEqual(
|
||||
MAX_SUBMODULE_PATHS_CACHE_CODE_UNITS
|
||||
)
|
||||
expect(getSubmodulePathsCacheCountForTests()).toBeLessThan(18)
|
||||
})
|
||||
|
||||
it('does not retain an oversized cache key', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'submodule.one.path packages/one\n' })
|
||||
const worktreePath = `/${'r'.repeat(64 * 1024)}`
|
||||
|
||||
await listSubmodulePaths(worktreePath)
|
||||
await listSubmodulePaths(worktreePath)
|
||||
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2)
|
||||
expect(getSubmodulePathsCacheCountForTests()).toBe(0)
|
||||
expect(getSubmodulePathsCacheCodeUnitsForTests()).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -1,92 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as BoundedFileReader from '../../shared/node-bounded-file-reader'
|
||||
|
||||
const { existsSyncMock, gitExecFileAsyncMock, readFileMock } = vi.hoisted(() => ({
|
||||
existsSyncMock: vi.fn(),
|
||||
gitExecFileAsyncMock: vi.fn(),
|
||||
readFileMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./runner', () => ({
|
||||
gitExecFileAsync: gitExecFileAsyncMock,
|
||||
gitStreamStdout: async (
|
||||
args: string[],
|
||||
options: { onStdout: (chunk: string) => boolean | void }
|
||||
) => {
|
||||
const { stdout } = await gitExecFileAsyncMock(args)
|
||||
return { stoppedEarly: options.onStdout(stdout ?? '') === true }
|
||||
},
|
||||
gitOptionalLocksDisabledEnv: (env: NodeJS.ProcessEnv = process.env) => ({
|
||||
...env,
|
||||
GIT_OPTIONAL_LOCKS: '0'
|
||||
})
|
||||
}))
|
||||
|
||||
vi.mock('fs/promises', () => ({ readFile: readFileMock }))
|
||||
vi.mock('fs', () => ({ existsSync: existsSyncMock }))
|
||||
vi.mock('../../shared/node-bounded-file-reader', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof BoundedFileReader>()
|
||||
return {
|
||||
...actual,
|
||||
readNodeFileWithinLimit: async (filePath: string, maxBytes: number) => {
|
||||
const value = await readFileMock(filePath)
|
||||
const buffer = Buffer.isBuffer(value) ? value : Buffer.from(value)
|
||||
if (buffer.length > maxBytes) {
|
||||
throw new actual.NodeFileReadTooLargeError(buffer.length, maxBytes)
|
||||
}
|
||||
return { buffer, stats: { isFile: () => true, size: buffer.length } }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
import {
|
||||
clearEffectiveUpstreamNegativeStatusCache,
|
||||
clearEffectiveUpstreamStatusCacheForTests,
|
||||
getEffectiveUpstreamStatusCacheCountForTests,
|
||||
getEffectiveUpstreamStatusGenerationCountForTests,
|
||||
getStatus,
|
||||
MAX_EFFECTIVE_UPSTREAM_CACHE_KEY_BYTES
|
||||
} from './status'
|
||||
|
||||
describe('effective-upstream cache key bounds', () => {
|
||||
beforeEach(() => {
|
||||
clearEffectiveUpstreamStatusCacheForTests()
|
||||
existsSyncMock.mockReset()
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
readFileMock.mockReset()
|
||||
existsSyncMock.mockReturnValue(false)
|
||||
readFileMock.mockResolvedValue('gitdir: /repo/.git/worktrees/feature\n')
|
||||
gitExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
||||
if (args.includes('status')) {
|
||||
return { stdout: '# branch.oid abcdef1234567890\n# branch.head feature\n' }
|
||||
}
|
||||
if (args[0] === 'symbolic-ref') {
|
||||
return { stdout: 'feature\n' }
|
||||
}
|
||||
if (args[0] === 'config' && args[1] === '--list') {
|
||||
return { stdout: 'core.repositoryformatversion\n0\0' }
|
||||
}
|
||||
if (args[0] === 'rev-parse') {
|
||||
throw new Error('missing upstream')
|
||||
}
|
||||
throw new Error(`unexpected git command: ${args.join(' ')}`)
|
||||
})
|
||||
})
|
||||
|
||||
it('re-probes without retaining keys above 64 KiB', async () => {
|
||||
const worktreePath = `/${'p'.repeat(MAX_EFFECTIVE_UPSTREAM_CACHE_KEY_BYTES)}`
|
||||
|
||||
await getStatus(worktreePath)
|
||||
await getStatus(worktreePath)
|
||||
|
||||
const upstreamProbes = gitExecFileAsyncMock.mock.calls.filter(
|
||||
([args]) => (args as string[])[0] === 'rev-parse' && (args as string[]).includes('HEAD@{u}')
|
||||
)
|
||||
expect(upstreamProbes).toHaveLength(2)
|
||||
expect(getEffectiveUpstreamStatusCacheCountForTests()).toBe(0)
|
||||
expect(getEffectiveUpstreamStatusGenerationCountForTests()).toBe(0)
|
||||
|
||||
clearEffectiveUpstreamNegativeStatusCache({ worktreePath, branchName: 'feature' })
|
||||
expect(getEffectiveUpstreamStatusGenerationCountForTests()).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,4 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as BoundedFileReader from '../../shared/node-bounded-file-reader'
|
||||
|
||||
const { existsSyncMock, gitExecFileAsyncMock, readFileMock } = vi.hoisted(() => ({
|
||||
existsSyncMock: vi.fn(),
|
||||
@@ -31,21 +30,6 @@ vi.mock('fs', () => ({
|
||||
existsSync: existsSyncMock
|
||||
}))
|
||||
|
||||
vi.mock('../../shared/node-bounded-file-reader', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof BoundedFileReader>()
|
||||
return {
|
||||
...actual,
|
||||
readNodeFileWithinLimit: async (filePath: string, maxBytes: number) => {
|
||||
const value = await readFileMock(filePath)
|
||||
const buffer = Buffer.isBuffer(value) ? value : Buffer.from(value)
|
||||
if (buffer.length > maxBytes) {
|
||||
throw new actual.NodeFileReadTooLargeError(buffer.length, maxBytes)
|
||||
}
|
||||
return { buffer, stats: { isFile: () => true, size: buffer.length } }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function isConfigListSnapshotCommand(args: string[]): boolean {
|
||||
return args[0] === 'config' && args[1] === '--list' && args[2] === '-z'
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as BoundedFileReader from '../../shared/node-bounded-file-reader'
|
||||
|
||||
// Repro command:
|
||||
// pnpm exec vitest run --config config/vitest.config.ts src/main/git/status-upstream-probe-churn.test.ts -t "missing-upstream polling churn"
|
||||
@@ -36,21 +35,6 @@ vi.mock('fs', () => ({
|
||||
existsSync: existsSyncMock
|
||||
}))
|
||||
|
||||
vi.mock('../../shared/node-bounded-file-reader', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof BoundedFileReader>()
|
||||
return {
|
||||
...actual,
|
||||
readNodeFileWithinLimit: async (filePath: string, maxBytes: number) => {
|
||||
const value = await readFileMock(filePath)
|
||||
const buffer = Buffer.isBuffer(value) ? value : Buffer.from(value)
|
||||
if (buffer.length > maxBytes) {
|
||||
throw new actual.NodeFileReadTooLargeError(buffer.length, maxBytes)
|
||||
}
|
||||
return { buffer, stats: { isFile: () => true, size: buffer.length } }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
import { clearEffectiveUpstreamStatusCacheForTests, getStatus } from './status'
|
||||
|
||||
function getGitArgs(call: unknown[]): string[] {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/* eslint-disable max-lines -- Why: git status/discard/chunking behavior is verified together here to keep the command contract readable in one place. */
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as NodeFs from 'node:fs'
|
||||
import type * as BoundedFileReader from '../../shared/node-bounded-file-reader'
|
||||
import path from 'node:path'
|
||||
import {
|
||||
MAX_RENDERED_DIFF_COMBINED_CHARACTERS,
|
||||
@@ -63,33 +62,6 @@ vi.mock('fs', () => ({
|
||||
existsSync: existsSyncMock
|
||||
}))
|
||||
|
||||
vi.mock('../../shared/node-bounded-file-reader', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof BoundedFileReader>()
|
||||
return {
|
||||
...actual,
|
||||
readNodeFileWithinLimit: async (filePath: string, maxBytes: number) => {
|
||||
if (maxBytes === 64 * 1024) {
|
||||
const value = await readFileMock(filePath)
|
||||
const buffer = Buffer.isBuffer(value) ? value : Buffer.from(value)
|
||||
if (buffer.length > maxBytes) {
|
||||
throw new actual.NodeFileReadTooLargeError(buffer.length, maxBytes)
|
||||
}
|
||||
return { buffer, stats: { isFile: () => true, size: buffer.length } }
|
||||
}
|
||||
const stats = await statMock(filePath)
|
||||
if (stats.size > maxBytes) {
|
||||
throw new actual.NodeFileReadTooLargeError(stats.size, maxBytes)
|
||||
}
|
||||
const value = await readFileMock(filePath)
|
||||
const buffer = Buffer.isBuffer(value) ? value : Buffer.from(value)
|
||||
if (buffer.length > maxBytes) {
|
||||
throw new actual.NodeFileReadTooLargeError(buffer.length, maxBytes)
|
||||
}
|
||||
return { buffer, stats }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
import {
|
||||
abortMerge,
|
||||
abortRebase,
|
||||
|
||||
+43
-123
@@ -1,5 +1,6 @@
|
||||
/* eslint-disable max-lines */
|
||||
import { existsSync } from 'node:fs'
|
||||
import { readFile, stat } from 'node:fs/promises'
|
||||
import * as path from 'node:path'
|
||||
import type {
|
||||
GitBranchChangeEntry,
|
||||
@@ -30,8 +31,6 @@ import {
|
||||
type GitLineStats
|
||||
} from '../../shared/git-uncommitted-line-stats'
|
||||
import { decodeGitCQuotedPath } from '../../shared/git-cquoted-path'
|
||||
import { iterateNulDelimitedFields } from '../../shared/nul-delimited-fields'
|
||||
import { iterateProcessOutputLines } from '../../shared/process-output-field-scanner'
|
||||
import {
|
||||
gitExecFileAsync,
|
||||
gitExecFileAsyncBuffer,
|
||||
@@ -58,18 +57,12 @@ import {
|
||||
clearGitStatusLineStatsCacheKey,
|
||||
reuseOrRecomputeGitStatusLineStats
|
||||
} from '../../shared/git-status-line-stats-cache'
|
||||
import {
|
||||
NodeFileReadTooLargeError,
|
||||
readNodeFileWithinLimit
|
||||
} from '../../shared/node-bounded-file-reader'
|
||||
|
||||
const MAX_GIT_SHOW_BYTES = 10 * 1024 * 1024
|
||||
const MAX_GIT_POINTER_FILE_BYTES = 64 * 1024
|
||||
const MAX_STAGED_COMMIT_CONTEXT_BYTES = MAX_GIT_SHOW_BYTES
|
||||
const BULK_CHUNK_SIZE = 100
|
||||
const EFFECTIVE_UPSTREAM_NEGATIVE_CACHE_TTL_MS = 5 * 60_000
|
||||
const MAX_EFFECTIVE_UPSTREAM_NEGATIVE_CACHE_ENTRIES = 512
|
||||
export const MAX_EFFECTIVE_UPSTREAM_CACHE_KEY_BYTES = 64 * 1024
|
||||
|
||||
type EffectiveUpstreamStatusCacheEntry = {
|
||||
expiresAt: number
|
||||
@@ -78,19 +71,9 @@ type EffectiveUpstreamStatusCacheEntry = {
|
||||
|
||||
const SUBMODULE_PATHS_CACHE_TTL_MS = 5_000
|
||||
export const MAX_SUBMODULE_PATHS_CACHE_ENTRIES = 512
|
||||
export const MAX_SUBMODULE_PATHS_PER_REPO = 10_000
|
||||
export const MAX_SUBMODULE_PATH_CODE_UNITS = 64 * 1024
|
||||
export const MAX_SUBMODULE_PATHS_PER_REPO_CODE_UNITS = 4 * 1024 * 1024
|
||||
export const MAX_SUBMODULE_PATHS_CACHE_CODE_UNITS = 16 * 1024 * 1024
|
||||
const MAX_SUBMODULE_PATHS_CACHE_KEY_BYTES = 64 * 1024
|
||||
type SubmodulePathsCacheEntry = {
|
||||
paths: string[]
|
||||
expiresAt: number
|
||||
retainedCodeUnits: number
|
||||
}
|
||||
type SubmodulePathsCacheEntry = { paths: string[]; expiresAt: number }
|
||||
const submodulePathsCache = new Map<string, SubmodulePathsCacheEntry>()
|
||||
let submodulePathsCacheGeneration = 0
|
||||
let submodulePathsCacheCodeUnits = 0
|
||||
|
||||
// Why: cache the upstream name to skip its 4-5-spawn resolution chain each poll; revalidate via one rev-list (issue #7576).
|
||||
const RESOLVED_UPSTREAM_NAME_CACHE_TTL_MS = 60_000
|
||||
@@ -134,7 +117,6 @@ export function clearSubmodulePathsCacheForTests(): void {
|
||||
|
||||
function clearSubmodulePathsCache(): void {
|
||||
submodulePathsCache.clear()
|
||||
submodulePathsCacheCodeUnits = 0
|
||||
// Why: bump the generation so a pre-mutation read can't repopulate the invalidated cache.
|
||||
submodulePathsCacheGeneration += 1
|
||||
}
|
||||
@@ -143,10 +125,6 @@ export function getSubmodulePathsCacheCountForTests(): number {
|
||||
return submodulePathsCache.size
|
||||
}
|
||||
|
||||
export function getSubmodulePathsCacheCodeUnitsForTests(): number {
|
||||
return submodulePathsCacheCodeUnits
|
||||
}
|
||||
|
||||
function gitRuntimeOptionsKey(options: GitRuntimeOptions): readonly unknown[] {
|
||||
return [options.wslDistro ?? null]
|
||||
}
|
||||
@@ -159,30 +137,18 @@ function getSubmodulePathsCacheKey(worktreePath: string, options: GitRuntimeOpti
|
||||
function pruneExpiredSubmodulePathsCache(now: number): void {
|
||||
for (const [cacheKey, entry] of submodulePathsCache) {
|
||||
if (entry.expiresAt <= now) {
|
||||
deleteSubmodulePathsCacheEntry(cacheKey)
|
||||
submodulePathsCache.delete(cacheKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function deleteSubmodulePathsCacheEntry(cacheKey: string): void {
|
||||
const entry = submodulePathsCache.get(cacheKey)
|
||||
if (!entry) {
|
||||
return
|
||||
}
|
||||
submodulePathsCache.delete(cacheKey)
|
||||
submodulePathsCacheCodeUnits -= entry.retainedCodeUnits
|
||||
}
|
||||
|
||||
function trimSubmodulePathsCache(): void {
|
||||
while (
|
||||
submodulePathsCache.size > MAX_SUBMODULE_PATHS_CACHE_ENTRIES ||
|
||||
submodulePathsCacheCodeUnits > MAX_SUBMODULE_PATHS_CACHE_CODE_UNITS
|
||||
) {
|
||||
while (submodulePathsCache.size > MAX_SUBMODULE_PATHS_CACHE_ENTRIES) {
|
||||
const oldestKey = submodulePathsCache.keys().next().value
|
||||
if (oldestKey === undefined) {
|
||||
break
|
||||
}
|
||||
deleteSubmodulePathsCacheEntry(oldestKey)
|
||||
submodulePathsCache.delete(oldestKey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,7 +158,7 @@ function getCachedSubmodulePaths(cacheKey: string, now: number): string[] | null
|
||||
return null
|
||||
}
|
||||
if (cached.expiresAt <= now) {
|
||||
deleteSubmodulePathsCacheEntry(cacheKey)
|
||||
submodulePathsCache.delete(cacheKey)
|
||||
return null
|
||||
}
|
||||
submodulePathsCache.delete(cacheKey)
|
||||
@@ -201,23 +167,8 @@ function getCachedSubmodulePaths(cacheKey: string, now: number): string[] | null
|
||||
}
|
||||
|
||||
function rememberSubmodulePaths(cacheKey: string, paths: string[], now: number): void {
|
||||
if (Buffer.byteLength(cacheKey, 'utf8') > MAX_SUBMODULE_PATHS_CACHE_KEY_BYTES) {
|
||||
deleteSubmodulePathsCacheEntry(cacheKey)
|
||||
return
|
||||
}
|
||||
const retainedCodeUnits =
|
||||
cacheKey.length + paths.reduce((total, submodulePath) => total + submodulePath.length, 0)
|
||||
if (retainedCodeUnits > MAX_SUBMODULE_PATHS_CACHE_CODE_UNITS) {
|
||||
deleteSubmodulePathsCacheEntry(cacheKey)
|
||||
return
|
||||
}
|
||||
deleteSubmodulePathsCacheEntry(cacheKey)
|
||||
submodulePathsCache.set(cacheKey, {
|
||||
paths,
|
||||
expiresAt: now + SUBMODULE_PATHS_CACHE_TTL_MS,
|
||||
retainedCodeUnits
|
||||
})
|
||||
submodulePathsCacheCodeUnits += retainedCodeUnits
|
||||
submodulePathsCache.delete(cacheKey)
|
||||
submodulePathsCache.set(cacheKey, { paths, expiresAt: now + SUBMODULE_PATHS_CACHE_TTL_MS })
|
||||
trimSubmodulePathsCache()
|
||||
}
|
||||
|
||||
@@ -634,10 +585,6 @@ function getEffectiveUpstreamStatusCacheKey(
|
||||
return [worktreePath, options.wslDistro ?? 'host', branchName, upstreamName ?? ''].join('\0')
|
||||
}
|
||||
|
||||
function canRetainEffectiveUpstreamCacheKey(cacheKey: string): boolean {
|
||||
return Buffer.byteLength(cacheKey, 'utf8') <= MAX_EFFECTIVE_UPSTREAM_CACHE_KEY_BYTES
|
||||
}
|
||||
|
||||
export function clearEffectiveUpstreamNegativeStatusCache(identity: {
|
||||
worktreePath: string
|
||||
branchName: string
|
||||
@@ -654,9 +601,6 @@ export function clearEffectiveUpstreamNegativeStatusCache(identity: {
|
||||
effectiveUpstreamStatusCache.delete(cacheKey)
|
||||
effectiveUpstreamStatusInFlight.delete(cacheKey)
|
||||
resolvedUpstreamNameCache.delete(cacheKey)
|
||||
if (!canRetainEffectiveUpstreamCacheKey(cacheKey)) {
|
||||
return
|
||||
}
|
||||
effectiveUpstreamStatusWriteGeneration.set(
|
||||
cacheKey,
|
||||
(effectiveUpstreamStatusWriteGeneration.get(cacheKey) ?? 0) + 1
|
||||
@@ -722,11 +666,6 @@ function rememberEffectiveUpstreamStatus(
|
||||
probedSameNameOriginRef: boolean,
|
||||
writeGeneration: number
|
||||
): void {
|
||||
if (!canRetainEffectiveUpstreamCacheKey(cacheKey)) {
|
||||
effectiveUpstreamStatusCache.delete(cacheKey)
|
||||
effectiveUpstreamStatusWriteGeneration.delete(cacheKey)
|
||||
return
|
||||
}
|
||||
// Why: hasConfiguredPushTarget gates a write action; re-probe each poll rather than cache a stale positive.
|
||||
if (status.hasUpstream || status.hasConfiguredPushTarget) {
|
||||
effectiveUpstreamStatusCache.delete(cacheKey)
|
||||
@@ -763,8 +702,7 @@ async function readOrProbeEffectiveUpstreamStatus(
|
||||
options: GitRuntimeOptions = {},
|
||||
bypassCache = false
|
||||
): Promise<GitUpstreamStatus> {
|
||||
const cacheable = !bypassCache && canRetainEffectiveUpstreamCacheKey(cacheKey)
|
||||
if (cacheable) {
|
||||
if (!bypassCache) {
|
||||
const cached = readCachedEffectiveUpstreamStatus(cacheKey, Date.now())
|
||||
if (cached) {
|
||||
return cached
|
||||
@@ -783,7 +721,7 @@ async function readOrProbeEffectiveUpstreamStatus(
|
||||
worktreePath,
|
||||
branchName,
|
||||
options,
|
||||
!cacheable
|
||||
bypassCache
|
||||
).then((result) => {
|
||||
rememberEffectiveUpstreamStatus(
|
||||
cacheKey,
|
||||
@@ -794,7 +732,7 @@ async function readOrProbeEffectiveUpstreamStatus(
|
||||
)
|
||||
return result.status
|
||||
})
|
||||
if (cacheable) {
|
||||
if (!bypassCache) {
|
||||
effectiveUpstreamStatusInFlight.set(cacheKey, probe)
|
||||
}
|
||||
try {
|
||||
@@ -835,11 +773,7 @@ async function probeOrRevalidateEffectiveUpstreamStatus(
|
||||
}
|
||||
}
|
||||
const result = await probeEffectiveUpstreamStatus(worktreePath, branchName, options)
|
||||
if (
|
||||
canRetainEffectiveUpstreamCacheKey(cacheKey) &&
|
||||
result.status.hasUpstream &&
|
||||
result.status.upstreamName
|
||||
) {
|
||||
if (result.status.hasUpstream && result.status.upstreamName) {
|
||||
resolvedUpstreamNameCache.set(cacheKey, {
|
||||
upstreamName: result.status.upstreamName,
|
||||
expiresAt: Date.now() + RESOLVED_UPSTREAM_NAME_CACHE_TTL_MS
|
||||
@@ -1039,9 +973,7 @@ export async function resolveGitDir(worktreePath: string): Promise<string> {
|
||||
const dotGitPath = path.join(worktreePath, '.git')
|
||||
|
||||
try {
|
||||
const dotGitContents = (
|
||||
await readNodeFileWithinLimit(dotGitPath, MAX_GIT_POINTER_FILE_BYTES)
|
||||
).buffer.toString('utf-8')
|
||||
const dotGitContents = await readFile(dotGitPath, 'utf-8')
|
||||
const match = dotGitContents.match(/^gitdir:\s*(.+)\s*$/m)
|
||||
if (match) {
|
||||
return path.resolve(worktreePath, match[1])
|
||||
@@ -1057,37 +989,6 @@ export async function resolveGitDir(worktreePath: string): Promise<string> {
|
||||
* List configured submodule paths (relative, forward-slash) for a worktree, cached
|
||||
* briefly. Read from `.gitmodules` to avoid an index-wide `ls-files` scan.
|
||||
*/
|
||||
function parseSubmodulePaths(stdout: string): string[] | null {
|
||||
const paths: string[] = []
|
||||
let retainedCodeUnits = 0
|
||||
for (const line of iterateProcessOutputLines(stdout)) {
|
||||
if (line.length > MAX_SUBMODULE_PATH_CODE_UNITS + 4_096) {
|
||||
return null
|
||||
}
|
||||
const spaceIndex = line.indexOf(' ')
|
||||
const submodulePath =
|
||||
spaceIndex === -1
|
||||
? ''
|
||||
: line
|
||||
.slice(spaceIndex + 1)
|
||||
.trim()
|
||||
.replace(/\/+$/, '')
|
||||
if (!submodulePath) {
|
||||
continue
|
||||
}
|
||||
if (
|
||||
paths.length >= MAX_SUBMODULE_PATHS_PER_REPO ||
|
||||
submodulePath.length > MAX_SUBMODULE_PATH_CODE_UNITS ||
|
||||
submodulePath.length > MAX_SUBMODULE_PATHS_PER_REPO_CODE_UNITS - retainedCodeUnits
|
||||
) {
|
||||
return null
|
||||
}
|
||||
paths.push(submodulePath)
|
||||
retainedCodeUnits += submodulePath.length
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
export async function listSubmodulePaths(
|
||||
worktreePath: string,
|
||||
options: GitRuntimeOptions = {}
|
||||
@@ -1107,7 +1008,18 @@ export async function listSubmodulePaths(
|
||||
['config', '--file', '.gitmodules', '--get-regexp', '^submodule\\..*\\.path$'],
|
||||
{ ...gitOptionsForWorktree(worktreePath, options), env: gitOptionalLocksDisabledEnv() }
|
||||
)
|
||||
paths = parseSubmodulePaths(stdout) ?? []
|
||||
paths = stdout
|
||||
.split(/\r?\n/)
|
||||
.map((line) => {
|
||||
const spaceIndex = line.indexOf(' ')
|
||||
return spaceIndex === -1
|
||||
? ''
|
||||
: line
|
||||
.slice(spaceIndex + 1)
|
||||
.trim()
|
||||
.replace(/\/+$/, '')
|
||||
})
|
||||
.filter((value) => value.length > 0)
|
||||
} catch {
|
||||
// No .gitmodules (or git config failure) — treat as a repo without submodules.
|
||||
paths = []
|
||||
@@ -1858,23 +1770,31 @@ async function readGitBlobAtOidPath(
|
||||
}
|
||||
|
||||
async function readWorkingTreeFile(filePath: string): Promise<GitBlobReadResult> {
|
||||
let fileStat
|
||||
try {
|
||||
const { buffer, stats: fileStat } = await readNodeFileWithinLimit(filePath, MAX_GIT_SHOW_BYTES)
|
||||
if (!fileStat.isFile()) {
|
||||
return { content: '', isBinary: false, exists: false }
|
||||
}
|
||||
return bufferToBlob(buffer, filePath)
|
||||
fileStat = await stat(filePath)
|
||||
} catch (error) {
|
||||
if (error instanceof NodeFileReadTooLargeError) {
|
||||
return { content: '', isBinary: true, exists: true }
|
||||
}
|
||||
// Why: only ENOENT is a real deletion; other read errors are failures, not absence.
|
||||
// Why: only ENOENT is a real deletion; other stat errors are read failures, not absence.
|
||||
return {
|
||||
content: '',
|
||||
isBinary: false,
|
||||
exists: (error as NodeJS.ErrnoException)?.code !== 'ENOENT'
|
||||
}
|
||||
}
|
||||
if (!fileStat.isFile()) {
|
||||
return { content: '', isBinary: false, exists: false }
|
||||
}
|
||||
if (fileStat.size > MAX_GIT_SHOW_BYTES) {
|
||||
// Why: mirror git's maxBuffer cap for working-tree reads so readFile can't pull in huge assets.
|
||||
return { content: '', isBinary: true, exists: true }
|
||||
}
|
||||
try {
|
||||
const buffer = await readFile(filePath)
|
||||
return bufferToBlob(buffer, filePath)
|
||||
} catch {
|
||||
// Why: the file exists but could not be read — a read failure, not a deletion.
|
||||
return { content: '', isBinary: false, exists: true }
|
||||
}
|
||||
}
|
||||
|
||||
function bufferToBlob(buffer: Buffer, filePath?: string): GitBlobReadResult {
|
||||
@@ -2149,7 +2069,7 @@ async function listTrackedPathSpecs(
|
||||
}
|
||||
)
|
||||
// Why: a tracked directory can hold enough paths to exceed the JS argument limit.
|
||||
for (const trackedPath of iterateNulDelimitedFields(stdout)) {
|
||||
for (const trackedPath of stdout.split('\0')) {
|
||||
if (trackedPath) {
|
||||
trackedPaths.push(trackedPath)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ import { isSubmoduleWorktreeRemovalRefusal } from '../../shared/worktree-submodu
|
||||
import { decodeGitCQuotedPath } from '../../shared/git-cquoted-path'
|
||||
import { parseGitRevListAheadBehindCounts } from '../../shared/git-rev-list-output'
|
||||
import { parseWslUncPath } from '../../shared/wsl-paths'
|
||||
import { iterateNulDelimitedFields } from '../../shared/nul-delimited-fields'
|
||||
import {
|
||||
hasUnsupportedRevParsePathFormatEcho,
|
||||
isUnsupportedRevParsePathFormatError,
|
||||
@@ -549,7 +548,7 @@ function splitNulWorktreeList(output: string): string[][] {
|
||||
const blocks: string[][] = []
|
||||
let currentBlock: string[] = []
|
||||
|
||||
for (const field of iterateNulDelimitedFields(output)) {
|
||||
for (const field of output.split('\0')) {
|
||||
if (field) {
|
||||
currentBlock.push(field)
|
||||
continue
|
||||
@@ -1377,12 +1376,10 @@ function hasOnlyIgnoredUntrackedStatus(
|
||||
)
|
||||
.filter((entry) => entry && !entry.split('/').includes('..'))
|
||||
)
|
||||
for (const entry of iterateNulDelimitedFields(status)) {
|
||||
if (entry && (!entry.startsWith('?? ') || !ignored.has(entry.slice(3).replace(/\\/g, '/')))) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
return status
|
||||
.split('\0')
|
||||
.filter(Boolean)
|
||||
.every((entry) => entry.startsWith('?? ') && ignored.has(entry.slice(3).replace(/\\/g, '/')))
|
||||
}
|
||||
|
||||
function translateWorktreePath(
|
||||
|
||||
Reference in New Issue
Block a user