This repository was archived by the owner on Oct 15, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathgit-shared.ts
More file actions
254 lines (233 loc) · 7.08 KB
/
Copy pathgit-shared.ts
File metadata and controls
254 lines (233 loc) · 7.08 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
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
import { join, relative, resolve } from 'node:path';
import { type SimpleGit, simpleGit } from 'simple-git';
import { isAlwaysSensitivePath } from './policy';
import { resolveRepoPath } from './registry';
export const SKIP_DIRECTORIES = new Set([
'.git',
'.next',
'.cache',
'.venv',
'__pycache__',
'build',
'coverage',
'dist',
'generated',
'node_modules',
'playwright-report',
'test-results',
'_private',
]);
export const SEARCH_GLOBS = [
'*.md',
'*.mdx',
'*.rst',
'*.adoc',
'*.txt',
'*.json',
'*.yaml',
'*.yml',
'*.toml',
'*.ts',
'*.tsx',
'*.js',
'*.jsx',
'*.py',
'*.go',
'*.rs',
'*.java',
'*.cs',
'*.ps1',
'*.sh',
];
export interface SnapshotComponent {
relativePath: string;
branch: string | null;
commitSha: string;
dirtyEntriesExcluded: number;
}
export interface SnapshotMetadata {
generatedAt: string;
sourceRoot: string;
components: SnapshotComponent[];
unversionedDocuments: Array<{ sourcePath: string; sha256: string }>;
}
export interface GitComponent {
relativePath: string;
path: string;
git: SimpleGit;
}
export function snapshotMetadata(root: string): SnapshotMetadata | null {
for (const relative of ['.gitpin/snapshot.json', '.repocontext/snapshot.json']) {
const path = join(root, ...relative.split('/'));
if (!existsSync(path)) continue;
return JSON.parse(readFileSync(path, 'utf-8')) as SnapshotMetadata;
}
return null;
}
export function gitComponents(name: string): GitComponent[] {
const root = resolveRepoPath(name);
return discoverGitRoots(root).map((path) => ({
relativePath: normalizeRelative(relative(root, path)) || '.',
path,
git: simpleGit(path),
}));
}
export function gitHeadSha(component: GitComponent): string {
return execFileSync('git', ['rev-parse', 'HEAD'], {
cwd: component.path,
encoding: 'utf-8',
windowsHide: true,
}).trim();
}
export function gitHeadPaths(component: GitComponent): string[] {
const output = execFileSync('git', ['ls-tree', '-r', '--name-only', '-z', 'HEAD'], {
cwd: component.path,
encoding: 'utf-8',
maxBuffer: 10 * 1024 * 1024,
windowsHide: true,
});
return output.split('\0').filter(Boolean);
}
export function readGitPackageManifest(
component: GitComponent,
sourcePath: string,
): { name?: string; version?: string; scripts: string[] } | null {
try {
const raw = execFileSync('git', ['show', `HEAD:${sourcePath}`], {
cwd: component.path,
encoding: 'utf-8',
maxBuffer: 1024 * 1024,
windowsHide: true,
});
const value = JSON.parse(raw) as { name?: string; version?: string; scripts?: Record<string, unknown> };
return {
name: value.name,
version: value.version,
scripts: Object.keys(value.scripts ?? {}),
};
} catch {
return null;
}
}
export function readPackageManifest(
root: string,
sourcePath: string,
): { name?: string; version?: string; scripts: string[] } | null {
const path = join(root, sourcePath);
if (!existsSync(path)) return null;
try {
const value = JSON.parse(readFileSync(path, 'utf-8')) as {
name?: string;
version?: string;
scripts?: Record<string, unknown>;
};
return {
name: value.name,
version: value.version,
scripts: Object.keys(value.scripts ?? {}),
};
} catch {
return null;
}
}
export function testDirectoriesForPath(path: string, names: Set<string>): string[] {
const parts = normalizeRelative(path).split('/');
const directories: string[] = [];
for (let index = 0; index < parts.length - 1; index += 1) {
if (names.has(parts[index])) directories.push(parts.slice(0, index + 1).join('/'));
}
return directories;
}
export function findFiles(root: string, predicate: (path: string) => boolean, limit: number): string[] {
const found: string[] = [];
walk(root, (path, isDirectory) => {
if (!isDirectory && predicate(path)) found.push(path);
return found.length < limit;
});
return found;
}
export function assertWithinRoot(root: string, full: string, sourcePath: string): void {
if (!isWithin(root, full)) throw new Error(`Path traversal blocked: ${sourcePath}`);
// Existing paths must stay inside the repository after symlink resolution.
if (!existsSync(full)) return;
try {
const rootReal = realpathSync.native(root);
const fullReal = realpathSync.native(full);
if (!isWithin(rootReal, fullReal)) throw new Error(`Path traversal blocked: ${sourcePath}`);
} catch (error) {
if (error instanceof Error && /Path traversal blocked/u.test(error.message)) throw error;
throw new Error(`Path traversal blocked: ${sourcePath}`);
}
}
export function isWithin(root: string, full: string): boolean {
const rootNormalized = resolve(root).toLowerCase();
const fullNormalized = resolve(full).toLowerCase();
return (
fullNormalized === rootNormalized ||
fullNormalized.startsWith(`${rootNormalized}\\`) ||
fullNormalized.startsWith(`${rootNormalized}/`)
);
}
export function isSensitivePath(path: string): boolean {
return isAlwaysSensitivePath(path);
}
export function normalizeRelative(path: string): string {
return path.replace(/\\/g, '/').replace(/^\.\//, '');
}
export function sha256(value: string): string {
return createHash('sha256').update(value).digest('hex');
}
function discoverGitRoots(root: string): string[] {
if (existsSync(join(root, '.git'))) return [root];
const roots: string[] = [];
const walkDirectory = (directory: string, depth: number): void => {
if (depth > 5) return;
for (const item of safeReadDirectory(directory)) {
const full = join(directory, item);
let isDirectory = false;
try {
const entry = lstatSync(full);
if (entry.isSymbolicLink()) continue;
isDirectory = entry.isDirectory();
} catch {
continue;
}
if (!isDirectory || SKIP_DIRECTORIES.has(item) || item.startsWith('.')) continue;
if (existsSync(join(full, '.git'))) roots.push(full);
else walkDirectory(full, depth + 1);
}
};
walkDirectory(root, 0);
return roots;
}
function walk(root: string, visitor: (path: string, isDirectory: boolean) => boolean): void {
const visit = (directory: string, depth: number): void => {
if (depth > 8) return;
for (const item of safeReadDirectory(directory)) {
const full = join(directory, item);
let isDirectory = false;
try {
const entry = lstatSync(full);
// Never follow directory symlinks when scanning repository trees.
if (entry.isSymbolicLink()) continue;
isDirectory = entry.isDirectory();
} catch {
continue;
}
if (isDirectory && (SKIP_DIRECTORIES.has(item) || item.startsWith('.'))) continue;
if (!visitor(full, isDirectory)) return;
if (isDirectory) visit(full, depth + 1);
}
};
visit(root, 0);
}
function safeReadDirectory(path: string): string[] {
try {
return readdirSync(path);
} catch {
return [];
}
}