refactor: organize shared foundation modules by owner (#42914)

This commit is contained in:
Neil
2026-11-15 19:09:38 -08:00
committed by GitHub
parent ae2ed119a4
commit 61ae9700f2
931 changed files with 1103 additions and 2423 deletions
@@ -1,4 +1,4 @@
import { isWindowsAbsolutePathLike } from '../../cross-platform-path'
import { isWindowsAbsolutePathLike } from '../../file-access/cross-platform-path'
import { quotePosixShell } from '../../shell/launch/shell-argument-quoting'
export type GitSshPolicyMode =
@@ -0,0 +1,64 @@
import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { countLooseRefs } from './loose-ref-count'
const roots: string[] = []
async function makeRefsTree(counts: Record<string, number>): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-loose-refs-'))
roots.push(root)
const refs = join(root, 'refs')
for (const [namespace, count] of Object.entries(counts)) {
const directory = join(refs, namespace)
await mkdir(directory, { recursive: true })
for (let index = 0; index < count; index += 1) {
await writeFile(join(directory, `ref-${index}`), 'a'.repeat(40))
}
}
await mkdir(refs, { recursive: true })
return refs
}
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('countLooseRefs', () => {
it('counts files across nested namespaces', async () => {
const refs = await makeRefsTree({ heads: 3, 'remotes/origin': 4, 'remotes/fork/deep': 2 })
await expect(countLooseRefs(refs, 100)).resolves.toEqual({ count: 9, saturated: false })
})
it('stops at the budget instead of walking the whole backlog', async () => {
const refs = await makeRefsTree({ 'remotes/origin': 500 })
const result = await countLooseRefs(refs, 10)
expect(result).toEqual({ count: 10, saturated: true })
})
it('reports zero for a repository with no refs directory', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-loose-refs-missing-'))
roots.push(root)
await expect(countLooseRefs(join(root, 'refs'), 100)).resolves.toEqual({
count: 0,
saturated: false
})
})
it('does not follow directory symlinks into a loop', async () => {
const refs = await makeRefsTree({ heads: 2 })
await symlink(refs, join(refs, 'loop'), 'dir')
const result = await countLooseRefs(refs, 100)
expect(result.saturated).toBe(false)
// The symlink is one dirent, never a second traversal of the tree.
expect(result.count).toBe(3)
})
})
@@ -0,0 +1,58 @@
import { readdir } from 'node:fs/promises'
import { join } from 'node:path'
export type LooseRefCount = {
/** Loose ref files seen, never above `budget`. */
count: number
/** The walk stopped early, so `count` is a floor rather than the total. */
saturated: boolean
}
// Bound visited directories and the pending queue so pathological ref trees cannot make admission unbounded.
const DIRECTORY_VISIT_CEILING = 4096
/** Budgeted admission probe, independent of backlog size. One readdir per directory avoids per-entry stat and streaming round trips:
* 23ms vs 177ms median on 36,600 refs at threshold 1,000; retain only the widest directory’s dirents.
* Strictly sequential to occupy at most one shared libuv slot. Abort between directories; a hung readdir is not interruptible but holds no Git lock. */
export async function countLooseRefs(
refsDirectory: string,
budget: number,
signal?: AbortSignal
): Promise<LooseRefCount> {
const pending = [refsDirectory]
let count = 0
let visited = 0
while (pending.length > 0) {
const directory = pending.pop()
if (directory === undefined) {
break
}
visited += 1
// Cancellation returns a floor; callers already treat saturation as unknown cleanliness.
if (
signal?.aborted === true ||
visited > DIRECTORY_VISIT_CEILING ||
pending.length > DIRECTORY_VISIT_CEILING
) {
return { count, saturated: true }
}
let entries: { name: string; isDirectory: () => boolean }[]
try {
entries = await readdir(directory, { withFileTypes: true })
} catch {
// A missing or unreadable namespace contributes nothing to the count.
continue
}
for (const entry of entries) {
if (entry.isDirectory()) {
pending.push(join(directory, entry.name))
continue
}
count += 1
if (count >= budget) {
return { count, saturated: true }
}
}
}
return { count, saturated: false }
}
@@ -0,0 +1,38 @@
/** Wait only for packed-refs rewriting. Killing Git during prune can strand ref lock files that Git never clears. */
export class PackedRefsLockGate {
private held = false
private waiters: (() => void)[] = []
setHeld(held: boolean): void {
this.held = held
if (held) {
return
}
const waiting = this.waiters
this.waiters = []
for (const resolve of waiting) {
resolve()
}
}
/** Resolves on release, or on `timeoutMs` -- past which Git's own retry is the better bet. */
whenReleased(timeoutMs: number): Promise<void> {
if (!this.held) {
return Promise.resolve()
}
return new Promise<void>((resolve) => {
let settled = false
const finish = (): void => {
if (settled) {
return
}
settled = true
clearTimeout(timer)
resolve()
}
const timer = setTimeout(finish, timeoutMs)
timer.unref?.()
this.waiters.push(finish)
})
}
}
@@ -1,5 +1,5 @@
import { countLooseRefs } from '../../loose-ref-count'
import { PackedRefsLockGate } from '../../packed-refs-lock-gate'
import { countLooseRefs } from './loose-ref-count'
import { PackedRefsLockGate } from './packed-refs-lock-gate'
import { RepoMaintenanceSchedule } from './repo-maintenance-schedule'
import {
LOOSE_REF_PACK_THRESHOLD,
@@ -1,7 +1,7 @@
import { lstat, mkdtemp, readdir, rename, stat } from 'node:fs/promises'
import { posix, win32 } from 'node:path'
import { isWindowsAbsolutePathLike } from '../../cross-platform-path'
import { isDefinitiveAbsence } from '../../definitive-filesystem-absence'
import { isWindowsAbsolutePathLike } from '../../file-access/cross-platform-path'
import { isDefinitiveAbsence } from '../../errors/definitive-filesystem-absence'
import { removeTree } from '../../file-write/windows-transient-lock-removal'
/** Run throwaway merge-tree object writes in a scratch store; alternates retain access to real objects without leaving unreachable loose objects. */
@@ -0,0 +1,14 @@
// Fetch fork PR/MR heads from hosting origin; otherwise accept only a lone remote rather than guessing a contributor fork.
export function pickPreferredGitRemote(remotes: readonly string[]): string {
const cleaned = remotes.map((line) => line.trim()).filter(Boolean)
if (cleaned.includes('origin')) {
return 'origin'
}
if (cleaned.length === 1) {
return cleaned[0]!
}
if (cleaned.length === 0) {
throw new Error('Repo has no configured git remotes.')
}
throw new Error(`Repo has multiple remotes (${cleaned.join(', ')}) and no default is configured.`)
}
@@ -0,0 +1,36 @@
/** Conservative path-only heuristic separating regenerated churn from authored branch totals; false positives understate work.
* Use anchored raw-path regexes as in test-code-path.ts. */
// Exclude build/target/out/bin: they commonly contain authored source.
const GENERATED_DIRECTORY =
/(?:^|[/\\])(?:__generated__|__pycache__|\.next|\.nuxt|coverage|dist|generated|node_modules|vendor)[/\\]/i
// Lockfiles regenerate wholesale. Two narrow anchored regexes reject nonmatches faster than one wide alternation (12.5k-path measurement).
const LOCKFILE =
/(?:^|[/\\])(?:bun\.lockb?|cargo\.lock|composer\.lock|flake\.lock|gemfile\.lock|go\.sum|gradle\.lockfile|mix\.lock|npm-shrinkwrap\.json|package-lock\.json|packages\.lock\.json|pipfile\.lock|pnpm-lock\.yaml|poetry\.lock|pubspec\.lock|uv\.lock|yarn\.lock)$/i
const GENERATED_BASENAME = new RegExp(
`(?:${[
/\.(?:generated|designer)\.[^./\\]+/, // Foo.generated.ts, Form.Designer.cs
// Allow plugin suffix segments such as service.pb.gw.go and service.pb.validate.go.
/[._](?:pb|pb2|pb2_grpc)\.(?:[^./\\]+\.)*[^./\\]+/,
/[._]gen\.[^./\\]+/, // schema.gen.ts, mock_gen.go
/_generated\.[^./\\]+/, // bindings_generated.go
/\.(?:g|freezed)\.dart/, // model.g.dart
/\.min\.(?:js|css|mjs)/,
/\.(?:js|css|mjs)\.map/, // source maps
/\.snap/ // vitest/jest snapshots, rewritten by `-u`
]
.map((pattern) => pattern.source)
.join('|')})$`,
'i'
)
/** Accepts POSIX and Windows separators — git reports `/`, callers may not. */
export function isGeneratedCodePath(filePath: string): boolean {
return (
GENERATED_BASENAME.test(filePath) ||
LOCKFILE.test(filePath) ||
GENERATED_DIRECTORY.test(filePath)
)
}
@@ -5,8 +5,8 @@ import {
parseNumstat,
type GitLineStats
} from './git-uncommitted-line-stats'
import { isGeneratedCodePath } from '../../generated-code-path'
import { isTestCodePath } from '../../test-code-path'
import { isGeneratedCodePath } from './generated-code-path'
import { isTestCodePath } from './test-code-path'
// Bound large base-to-worktree diffs over SSH; failures invalidate totals instead of publishing partial values.
export const GIT_BRANCH_LINE_TOTAL_TIMEOUT_MS = 15_000
+32
View File
@@ -0,0 +1,32 @@
// Conservative path-only test classification for branch line totals; avoid per-file normalization.
// Match directory segments, not filenames. Keep specs/ excluded (usually production specifications); test basenames still match there.
const TEST_DIRECTORY =
/(?:^|[/\\])(?:__mocks__|__snapshots__|__tests__|cypress|e2e|spec|tests?|testdata)[/\\]/i
// Keep matches inside basenames; combine ecosystem patterns so V8 scans each path once.
const TEST_BASENAME = new RegExp(
`(?:${[
/\.(?:test|spec)\.[^./\\]+/, // Chip.test.tsx, git-status.spec.js
/[-_](?:test|spec)s?\.[^./\\]+/, // handler_test.go, user_spec.rb
// Restrict test_ to Python or fixtures/pages become tests. test_client.py remains indistinguishable from a pytest module.
/(?:^|[/\\])test_[^./\\]*\.py/,
/(?:^|[/\\])conftest\.py/,
/\.snap/
]
.map((pattern) => pattern.source)
.join('|')})$`,
'i'
)
// Use case-sensitive conventional Test/Tests/Spec suffixes or Contest.java/Latest.kt become false positives.
const TEST_TYPE_NAME_SUFFIX = /(?:Test|Tests|Spec)\.(?:java|kt|kts|scala|groovy|cs|swift|php|rb)$/
/** Accepts POSIX and Windows separators — git reports `/`, callers may not. */
export function isTestCodePath(filePath: string): boolean {
return (
TEST_DIRECTORY.test(filePath) ||
TEST_BASENAME.test(filePath) ||
TEST_TYPE_NAME_SUFFIX.test(filePath)
)
}