-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitFilesystem.ts
More file actions
699 lines (640 loc) · 21.8 KB
/
gitFilesystem.ts
File metadata and controls
699 lines (640 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
/**
* Filesystem-based git state reading — avoids spawning git subprocesses.
*
* Covers: resolving .git directories (including worktrees/submodules),
* parsing HEAD, resolving refs via loose files and packed-refs,
* and the GitHeadWatcher that caches branch/SHA with fs.watchFile.
*
* Correctness notes (verified against git source):
* - HEAD: `ref: refs/heads/<branch>\n` or raw SHA (refs/files-backend.c)
* - Packed-refs: `<sha> <refname>\n`, skip `#` and `^` lines (packed-backend.c)
* - .git file (worktree): `gitdir: <path>\n` with optional relative path (setup.c)
* - Shallow: mere existence of `<commonDir>/shallow` means shallow (shallow.c)
*/
import { unwatchFile, watchFile } from 'fs'
import { readdir, readFile, stat } from 'fs/promises'
import { join, resolve } from 'path'
import { waitForScrollIdle } from '../../bootstrap/state.js'
import { registerCleanup } from '../cleanupRegistry.js'
import { getCwd } from '../cwd.js'
import { findGitRoot } from '../git.js'
import { parseGitConfigValue } from './gitConfigParser.js'
// ---------------------------------------------------------------------------
// resolveGitDir — find the actual .git directory
// ---------------------------------------------------------------------------
const resolveGitDirCache = new Map<string, string | null>()
/** Clear cached git dir resolutions. Exported for testing only. */
export function clearResolveGitDirCache(): void {
resolveGitDirCache.clear()
}
/**
* Resolve the actual .git directory for a repo.
* Handles worktrees/submodules where .git is a file containing `gitdir: <path>`.
* Memoized per startPath.
*/
export async function resolveGitDir(
startPath?: string,
): Promise<string | null> {
const cwd = resolve(startPath ?? getCwd())
const cached = resolveGitDirCache.get(cwd)
if (cached !== undefined) {
return cached
}
const root = findGitRoot(cwd)
if (!root) {
resolveGitDirCache.set(cwd, null)
return null
}
const gitPath = join(root, '.git')
try {
const st = await stat(gitPath)
if (st.isFile()) {
// Worktree or submodule: .git is a file with `gitdir: <path>`
// Git strips trailing \n and \r (setup.c read_gitfile_gently).
const content = (await readFile(gitPath, 'utf-8')).trim()
if (content.startsWith('gitdir:')) {
const rawDir = content.slice('gitdir:'.length).trim()
const resolved = resolve(root, rawDir)
resolveGitDirCache.set(cwd, resolved)
return resolved
}
}
// Regular repo: .git is a directory
resolveGitDirCache.set(cwd, gitPath)
return gitPath
} catch {
resolveGitDirCache.set(cwd, null)
return null
}
}
// ---------------------------------------------------------------------------
// isSafeRefName — validate ref/branch names read from .git/
// ---------------------------------------------------------------------------
/**
* Validate that a ref/branch name read from .git/ is safe to use in path
* joins, as git positional arguments, and when interpolated into shell
* commands (commit-push-pr skill interpolates the branch into shell).
* An attacker who controls .git/HEAD or a loose ref file could otherwise
* embed path traversal (`..`), argument injection (leading `-`), or shell
* metacharacters — .git/HEAD is a plain text file that can be written
* without git's own check-ref-format validation.
*
* Allowlist: ASCII alphanumerics, `/`, `.`, `_`, `+`, `-`, `@` only. This
* covers all legitimate git branch names (e.g. `feature/foo`,
* `release-1.2.3+build`, `dependabot/npm_and_yarn/@types/node-18.0.0`)
* while rejecting everything that could be dangerous in shell context
* (newlines, backticks, `$`, `;`, `|`, `&`, `(`, `)`, `<`, `>`, spaces,
* tabs, quotes, backslash) and path traversal (`..`).
*/
export function isSafeRefName(name: string): boolean {
if (!name || name.startsWith('-') || name.startsWith('/')) {
return false
}
if (name.includes('..')) {
return false
}
// Reject single-dot and empty path components (`.`, `foo/./bar`, `foo//bar`,
// `foo/`). Git-check-ref-format rejects these, and `.` normalizes away in
// path joins so a tampered HEAD of `refs/heads/.` would make us watch the
// refs/heads directory itself instead of a branch file.
if (name.split('/').some(c => c === '.' || c === '')) {
return false
}
// Allowlist-only: alphanumerics, /, ., _, +, -, @. Rejects all shell
// metacharacters, whitespace, NUL, and non-ASCII. Git's forbidden @{
// sequence is blocked because { is not in the allowlist.
if (!/^[a-zA-Z0-9/._+@-]+$/.test(name)) {
return false
}
return true
}
/**
* Validate that a string is a git SHA: 40 hex chars (SHA-1) or 64 hex chars
* (SHA-256). Git never writes abbreviated SHAs to HEAD or ref files, so we
* only accept full-length hashes.
*
* An attacker who controls .git/HEAD when detached, or a loose ref file,
* could otherwise return arbitrary content that flows into shell contexts.
*/
export function isValidGitSha(s: string): boolean {
return /^[0-9a-f]{40}$/.test(s) || /^[0-9a-f]{64}$/.test(s)
}
// ---------------------------------------------------------------------------
// readGitHead — parse .git/HEAD
// ---------------------------------------------------------------------------
/**
* Parse .git/HEAD to determine current branch or detached SHA.
*
* HEAD format (per git source, refs/files-backend.c):
* - `ref: refs/heads/<branch>\n` — on a branch
* - `ref: <other-ref>\n` — unusual symref (e.g. during bisect)
* - `<hex-sha>\n` — detached HEAD (e.g. during rebase)
*
* Git strips trailing whitespace via strbuf_rtrim; .trim() is equivalent.
* Git allows any whitespace between "ref:" and the path; we handle
* this by trimming after slicing past "ref:".
*/
export async function readGitHead(
gitDir: string,
): Promise<
{ type: 'branch'; name: string } | { type: 'detached'; sha: string } | null
> {
try {
const content = (await readFile(join(gitDir, 'HEAD'), 'utf-8')).trim()
if (content.startsWith('ref:')) {
const ref = content.slice('ref:'.length).trim()
if (ref.startsWith('refs/heads/')) {
const name = ref.slice('refs/heads/'.length)
// Reject path traversal and argument injection from a tampered HEAD.
if (!isSafeRefName(name)) {
return null
}
return { type: 'branch', name }
}
// Unusual symref (not a local branch) — resolve to SHA
if (!isSafeRefName(ref)) {
return null
}
const sha = await resolveRef(gitDir, ref)
return sha ? { type: 'detached', sha } : { type: 'detached', sha: '' }
}
// Raw SHA (detached HEAD). Validate: an attacker-controlled HEAD file
// could contain shell metacharacters that flow into downstream shell
// contexts.
if (!isValidGitSha(content)) {
return null
}
return { type: 'detached', sha: content }
} catch {
return null
}
}
// ---------------------------------------------------------------------------
// resolveRef — resolve loose/packed refs to SHAs
// ---------------------------------------------------------------------------
/**
* Resolve a git ref (e.g. `refs/heads/main`) to a commit SHA.
* Checks loose ref files first, then falls back to packed-refs.
* Follows symrefs (e.g. `ref: refs/remotes/origin/main`).
*
* For worktrees, refs live in the common gitdir (pointed to by the
* `commondir` file), not the worktree-specific gitdir. We check the
* worktree gitdir first, then fall back to the common dir.
*
* Packed-refs format (per packed-backend.c):
* - Header: `# pack-refs with: <traits>\n`
* - Entries: `<40-hex-sha> <refname>\n`
* - Peeled: `^<40-hex-sha>\n` (after annotated tag entries)
*/
export async function resolveRef(
gitDir: string,
ref: string,
): Promise<string | null> {
const result = await resolveRefInDir(gitDir, ref)
if (result) {
return result
}
// For worktrees: try the common gitdir where shared refs live
const commonDir = await getCommonDir(gitDir)
if (commonDir && commonDir !== gitDir) {
return resolveRefInDir(commonDir, ref)
}
return null
}
async function resolveRefInDir(
dir: string,
ref: string,
): Promise<string | null> {
// Try loose ref file
try {
const content = (await readFile(join(dir, ref), 'utf-8')).trim()
if (content.startsWith('ref:')) {
const target = content.slice('ref:'.length).trim()
// Reject path traversal in a tampered symref chain.
if (!isSafeRefName(target)) {
return null
}
return resolveRef(dir, target)
}
// Loose ref content should be a raw SHA. Validate: an attacker-controlled
// ref file could contain shell metacharacters.
if (!isValidGitSha(content)) {
return null
}
return content
} catch {
// Loose ref doesn't exist, try packed-refs
}
try {
const packed = await readFile(join(dir, 'packed-refs'), 'utf-8')
for (const line of packed.split('\n')) {
if (line.startsWith('#') || line.startsWith('^')) {
continue
}
const spaceIdx = line.indexOf(' ')
if (spaceIdx === -1) {
continue
}
if (line.slice(spaceIdx + 1) === ref) {
const sha = line.slice(0, spaceIdx)
return isValidGitSha(sha) ? sha : null
}
}
} catch {
// No packed-refs
}
return null
}
/**
* Read the `commondir` file to find the shared git directory.
* In a worktree, this points to the main repo's .git dir.
* Returns null if no commondir file exists (regular repo).
*/
export async function getCommonDir(gitDir: string): Promise<string | null> {
try {
const content = (await readFile(join(gitDir, 'commondir'), 'utf-8')).trim()
return resolve(gitDir, content)
} catch {
return null
}
}
/**
* Read a raw symref file and extract the branch name after a known prefix.
* Returns null if the ref doesn't exist, isn't a symref, or doesn't match the prefix.
* Checks loose file only — packed-refs doesn't store symrefs.
*/
export async function readRawSymref(
gitDir: string,
refPath: string,
branchPrefix: string,
): Promise<string | null> {
try {
const content = (await readFile(join(gitDir, refPath), 'utf-8')).trim()
if (content.startsWith('ref:')) {
const target = content.slice('ref:'.length).trim()
if (target.startsWith(branchPrefix)) {
const name = target.slice(branchPrefix.length)
// Reject path traversal and argument injection from a tampered symref.
if (!isSafeRefName(name)) {
return null
}
return name
}
}
} catch {
// Not a loose ref
}
return null
}
// ---------------------------------------------------------------------------
// GitFileWatcher — watches git files and caches derived values.
// Lazily initialized on first cache access. Invalidates all cached
// values when any watched file changes.
//
// Watches:
// .git/HEAD — branch switches, detached HEAD
// .git/config — remote URL changes
// .git/refs/heads/<branch> — new commits on the current branch
//
// When HEAD changes (branch switch), the branch ref watcher is updated
// to track the new branch's ref file.
// ---------------------------------------------------------------------------
type CacheEntry<T> = {
value: T
dirty: boolean
compute: () => Promise<T>
}
const WATCH_INTERVAL_MS = process.env.NODE_ENV === 'test' ? 10 : 1000
class GitFileWatcher {
private gitDir: string | null = null
private commonDir: string | null = null
private initialized = false
private initPromise: Promise<void> | null = null
private watchedPaths: string[] = []
private branchRefPath: string | null = null
private cache = new Map<string, CacheEntry<unknown>>()
async ensureStarted(): Promise<void> {
if (this.initialized) {
return
}
if (this.initPromise) {
return this.initPromise
}
this.initPromise = this.start()
return this.initPromise
}
private async start(): Promise<void> {
this.gitDir = await resolveGitDir()
this.initialized = true
if (!this.gitDir) {
return
}
// In a worktree, branch refs and the main config are shared and live in
// commonDir, not the per-worktree gitDir. Resolve once so we don't
// re-read the commondir file on every branch switch.
this.commonDir = await getCommonDir(this.gitDir)
// Watch .git/HEAD and .git/config
this.watchPath(join(this.gitDir, 'HEAD'), () => {
void this.onHeadChanged()
})
// Config (remote URLs) lives in commonDir for worktrees
this.watchPath(join(this.commonDir ?? this.gitDir, 'config'), () => {
this.invalidate()
})
// Watch the current branch's ref file for commit changes
await this.watchCurrentBranchRef()
registerCleanup(async () => {
this.stopWatching()
})
}
private watchPath(path: string, callback: () => void): void {
this.watchedPaths.push(path)
watchFile(path, { interval: WATCH_INTERVAL_MS }, callback)
}
/**
* Watch the loose ref file for the current branch.
* Called on startup and whenever HEAD changes (branch switch).
*/
private async watchCurrentBranchRef(): Promise<void> {
if (!this.gitDir) {
return
}
const head = await readGitHead(this.gitDir)
// Branch refs live in commonDir for worktrees (gitDir for regular repos)
const refsDir = this.commonDir ?? this.gitDir
const refPath =
head?.type === 'branch' ? join(refsDir, 'refs', 'heads', head.name) : null
// Already watching this ref (or already not watching anything)
if (refPath === this.branchRefPath) {
return
}
// Stop watching old branch ref. Runs for branch→branch AND
// branch→detached (checkout --detach, rebase, bisect).
if (this.branchRefPath) {
unwatchFile(this.branchRefPath)
this.watchedPaths = this.watchedPaths.filter(
p => p !== this.branchRefPath,
)
}
this.branchRefPath = refPath
if (!refPath) {
return
}
// The ref file may not exist yet (new branch before first commit).
// watchFile works on nonexistent files — it fires when the file appears.
this.watchPath(refPath, () => {
this.invalidate()
})
}
private async onHeadChanged(): Promise<void> {
// HEAD changed — could be a branch switch or detach.
// Defer file I/O (readGitHead, watchFile setup) until scroll settles so
// watchFile callbacks that land mid-scroll don't compete for the event
// loop. invalidate() is cheap (just marks dirty) so do it first — the
// cache correctly serves stale-marked values until the watcher updates.
this.invalidate()
await waitForScrollIdle()
await this.watchCurrentBranchRef()
}
private invalidate(): void {
for (const entry of this.cache.values()) {
entry.dirty = true
}
}
private stopWatching(): void {
for (const path of this.watchedPaths) {
unwatchFile(path)
}
this.watchedPaths = []
this.branchRefPath = null
}
/**
* Get a cached value by key. On first call for a key, computes and caches it.
* Subsequent calls return the cached value until a watched file changes,
* which marks the entry dirty. The next get() re-computes from disk.
*
* Race condition handling: dirty is cleared BEFORE the async compute starts.
* If a file change arrives during compute, it re-sets dirty, so the next
* get() will re-read again rather than serving a stale value.
*/
async get<T>(key: string, compute: () => Promise<T>): Promise<T> {
await this.ensureStarted()
const existing = this.cache.get(key)
if (existing && !existing.dirty) {
return existing.value as T
}
// Clear dirty before compute — if the file changes again during the
// async read, invalidate() will re-set dirty and we'll re-read on
// the next get() call.
if (existing) {
existing.dirty = false
}
const value = await compute()
// Only update the cached value if no new invalidation arrived during compute
const entry = this.cache.get(key)
if (entry && !entry.dirty) {
entry.value = value
}
if (!entry) {
this.cache.set(key, { value, dirty: false, compute })
}
return value
}
/** Reset all state. Stops file watchers. For testing only. */
reset(): void {
this.stopWatching()
this.cache.clear()
this.initialized = false
this.initPromise = null
this.gitDir = null
this.commonDir = null
}
}
const gitWatcher = new GitFileWatcher()
async function computeBranch(): Promise<string> {
const gitDir = await resolveGitDir()
if (!gitDir) {
return 'HEAD'
}
const head = await readGitHead(gitDir)
if (!head) {
return 'HEAD'
}
return head.type === 'branch' ? head.name : 'HEAD'
}
async function computeHead(): Promise<string> {
const gitDir = await resolveGitDir()
if (!gitDir) {
return ''
}
const head = await readGitHead(gitDir)
if (!head) {
return ''
}
if (head.type === 'branch') {
return (await resolveRef(gitDir, `refs/heads/${head.name}`)) ?? ''
}
return head.sha
}
async function computeRemoteUrl(): Promise<string | null> {
const gitDir = await resolveGitDir()
if (!gitDir) {
return null
}
const url = await parseGitConfigValue(gitDir, 'remote', 'origin', 'url')
if (url) {
return url
}
// In worktrees, the config with remote URLs is in the common dir
const commonDir = await getCommonDir(gitDir)
if (commonDir && commonDir !== gitDir) {
return parseGitConfigValue(commonDir, 'remote', 'origin', 'url')
}
return null
}
async function computeDefaultBranch(): Promise<string> {
const gitDir = await resolveGitDir()
if (!gitDir) {
return 'main'
}
// refs/remotes/ lives in commonDir, not the per-worktree gitDir
const commonDir = (await getCommonDir(gitDir)) ?? gitDir
const branchFromSymref = await readRawSymref(
commonDir,
'refs/remotes/origin/HEAD',
'refs/remotes/origin/',
)
if (branchFromSymref) {
return branchFromSymref
}
for (const candidate of ['main', 'master']) {
const sha = await resolveRef(commonDir, `refs/remotes/origin/${candidate}`)
if (sha) {
return candidate
}
}
return 'main'
}
export function getCachedBranch(): Promise<string> {
return gitWatcher.get('branch', computeBranch)
}
export function getCachedHead(): Promise<string> {
return gitWatcher.get('head', computeHead)
}
export function getCachedRemoteUrl(): Promise<string | null> {
return gitWatcher.get('remoteUrl', computeRemoteUrl)
}
export function getCachedDefaultBranch(): Promise<string> {
return gitWatcher.get('defaultBranch', computeDefaultBranch)
}
/** Reset the git file watcher state. For testing only. */
export function resetGitFileWatcher(): void {
gitWatcher.reset()
}
/**
* Read the HEAD SHA for an arbitrary directory (not using the watcher).
* Used by plugins that need the HEAD of a specific repo, not the CWD repo.
*/
export async function getHeadForDir(cwd: string): Promise<string | null> {
const gitDir = await resolveGitDir(cwd)
if (!gitDir) {
return null
}
const head = await readGitHead(gitDir)
if (!head) {
return null
}
if (head.type === 'branch') {
return resolveRef(gitDir, `refs/heads/${head.name}`)
}
return head.sha
}
/**
* Read the HEAD SHA for a git worktree directory (not the main repo).
*
* Unlike `getHeadForDir`, this reads `<worktreePath>/.git` directly as a
* `gitdir:` pointer file, with no upward walk. `getHeadForDir` walks upward
* via `findGitRoot` and would find the parent repo's `.git` when the
* worktree path doesn't exist — misreporting the parent HEAD as the worktree's.
*
* Returns null if the worktree doesn't exist (`.git` pointer ENOENT) or is
* malformed. Caller can treat null as "not a valid worktree".
*/
export async function readWorktreeHeadSha(
worktreePath: string,
): Promise<string | null> {
let gitDir: string
try {
const ptr = (await readFile(join(worktreePath, '.git'), 'utf-8')).trim()
if (!ptr.startsWith('gitdir:')) {
return null
}
gitDir = resolve(worktreePath, ptr.slice('gitdir:'.length).trim())
} catch {
return null
}
const head = await readGitHead(gitDir)
if (!head) {
return null
}
if (head.type === 'branch') {
return resolveRef(gitDir, `refs/heads/${head.name}`)
}
return head.sha
}
/**
* Read the remote origin URL for an arbitrary directory via .git/config.
*/
export async function getRemoteUrlForDir(cwd: string): Promise<string | null> {
const gitDir = await resolveGitDir(cwd)
if (!gitDir) {
return null
}
const url = await parseGitConfigValue(gitDir, 'remote', 'origin', 'url')
if (url) {
return url
}
// In worktrees, the config with remote URLs is in the common dir
const commonDir = await getCommonDir(gitDir)
if (commonDir && commonDir !== gitDir) {
return parseGitConfigValue(commonDir, 'remote', 'origin', 'url')
}
return null
}
/**
* Check if we're in a shallow clone by looking for <commonDir>/shallow.
* Per git's shallow.c, mere existence of the file means shallow.
* The shallow file lives in commonDir, not the per-worktree gitDir.
*/
export async function isShallowClone(): Promise<boolean> {
const gitDir = await resolveGitDir()
if (!gitDir) {
return false
}
const commonDir = (await getCommonDir(gitDir)) ?? gitDir
try {
await stat(join(commonDir, 'shallow'))
return true
} catch {
return false
}
}
/**
* Count worktrees by reading <commonDir>/worktrees/ directory.
* The worktrees/ directory lives in commonDir, not the per-worktree gitDir.
* The main worktree is not listed there, so add 1.
*/
export async function getWorktreeCountFromFs(): Promise<number> {
try {
const gitDir = await resolveGitDir()
if (!gitDir) {
return 0
}
const commonDir = (await getCommonDir(gitDir)) ?? gitDir
const entries = await readdir(join(commonDir, 'worktrees'))
return entries.length + 1
} catch {
// No worktrees directory means only the main worktree
return 1
}
}