-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathhelpers.ts
More file actions
211 lines (191 loc) · 5.96 KB
/
Copy pathhelpers.ts
File metadata and controls
211 lines (191 loc) · 5.96 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
/**
* Integration test helpers for @gitlens/git library.
*
* Creates real git repositories in temp directories and provides
* a configured CliGitProvider for testing sub-providers.
*/
import { execFileSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { FileSystemProvider, GitServiceConfig, GitServiceContext, GitServiceHooks } from '@gitlens/git/context.js';
import { Logger } from '@gitlens/utils/logger.js';
import { toFsPath } from '@gitlens/utils/uri.js';
import { CliGitProvider } from '../../../cliGitProvider.js';
import type { GitOptions } from '../../../exec/git.js';
import { findGitPath } from '../../../exec/locator.js';
export interface TestRepo {
path: string;
provider: CliGitProvider;
cleanup: () => void;
}
// Cache git location across all tests
let gitLocationPromise: ReturnType<typeof findGitPath>;
function getGitLocation() {
return (gitLocationPromise ??= findGitPath(null));
}
// Configure logger once (no-op unless debugging)
let loggerConfigured = false;
function ensureLogger() {
if (loggerConfigured) return;
loggerConfigured = true;
const noop = () => {};
const debugLog = process.env.GITLENS_TEST_DEBUG
? (name: string) => (_msg: string) => {
console.error(`[${name}] ${_msg}`);
}
: () => noop;
Logger.configure({
name: 'test',
createChannel: function (name) {
const log = debugLog(name);
return {
name: name,
logLevel: 0,
dispose: noop,
trace: log,
debug: log,
info: log,
warn: log,
error: log,
};
},
});
}
function createMinimalContext(hooks?: GitServiceHooks, config?: GitServiceConfig): GitServiceContext {
return {
fs: createNodeFs(),
hooks: hooks,
config: config,
};
}
function createNodeFs(): FileSystemProvider {
return {
readFile: async function (uri) {
return readFile(toFsPath(uri));
},
stat: async function (uri) {
try {
const stats = statSync(toFsPath(uri));
return {
type: stats.isDirectory() ? 2 : 1,
ctime: stats.ctimeMs,
mtime: stats.mtimeMs,
size: stats.size,
};
} catch {
return undefined;
}
},
readDirectory: async function (uri) {
const entries = readdirSync(toFsPath(uri), { withFileTypes: true });
return entries.map(e => [e.name, e.isDirectory() ? 2 : 1]);
},
};
}
/**
* Creates a test git repository with an initial commit.
* Returns the provider, git instance, and cleanup function.
*
* Call `cleanup()` in your `teardown()` / `suiteTeardown()`.
*/
export function createTestRepo(options?: {
hooks?: GitServiceHooks;
gitOptions?: GitOptions;
config?: GitServiceConfig;
}): TestRepo {
ensureLogger();
const dir = mkdtempSync(join(tmpdir(), 'gitlens-test-'));
// Initialize a git repo with deterministic config
execFileSync('git', ['init', '-b', 'main'], { cwd: dir, stdio: 'pipe' });
execFileSync('git', ['config', 'user.email', 'test@gitlens.test'], { cwd: dir, stdio: 'pipe' });
execFileSync('git', ['config', 'user.name', 'Test User'], { cwd: dir, stdio: 'pipe' });
// Disable gpg signing in test repos
execFileSync('git', ['config', 'commit.gpgsign', 'false'], { cwd: dir, stdio: 'pipe' });
// Create initial commit
writeFileSync(join(dir, 'README.md'), '# Test Repository\n');
execFileSync('git', ['add', 'README.md'], {
cwd: dir,
stdio: 'pipe',
});
execFileSync('git', ['commit', '-m', 'Initial commit'], {
cwd: dir,
stdio: 'pipe',
env: { ...process.env, GIT_COMMITTER_DATE: '2024-01-01T00:00:00Z', GIT_AUTHOR_DATE: '2024-01-01T00:00:00Z' },
});
const context = createMinimalContext(options?.hooks, options?.config);
const provider = new CliGitProvider({
context: context,
locator: getGitLocation,
gitOptions: { gitTimeout: 30000, ...options?.gitOptions },
});
return {
path: dir,
provider: provider,
cleanup: () => {
provider.dispose();
rmSync(dir, { recursive: true, force: true });
},
};
}
/**
* Add a file and commit it in the test repo.
*/
export function addCommit(
repoPath: string,
filename: string,
content: string,
message: string,
options?: { date?: string },
): void {
const filePath = join(repoPath, filename);
// Ensure parent directory exists
mkdirSync(join(repoPath, ...filename.split('/').slice(0, -1)), { recursive: true });
writeFileSync(filePath, content);
const env = { ...process.env };
if (options?.date) {
env.GIT_COMMITTER_DATE = options.date;
env.GIT_AUTHOR_DATE = options.date;
}
execFileSync('git', ['add', filename], { cwd: repoPath, stdio: 'pipe', env: env });
execFileSync('git', ['commit', '-m', message], { cwd: repoPath, stdio: 'pipe', env: env });
}
/**
* Create a branch in the test repo.
*/
export function createBranch(repoPath: string, name: string, options?: { checkout?: boolean }): void {
if (options?.checkout) {
execFileSync('git', ['checkout', '-b', name], { cwd: repoPath, stdio: 'pipe' });
} else {
execFileSync('git', ['branch', name], { cwd: repoPath, stdio: 'pipe' });
}
}
/**
* Create a tag in the test repo.
*/
export function createTag(repoPath: string, name: string, message?: string): void {
if (message) {
execFileSync('git', ['tag', '-a', name, '-m', message], { cwd: repoPath, stdio: 'pipe' });
} else {
execFileSync('git', ['tag', name], { cwd: repoPath, stdio: 'pipe' });
}
}
/**
* Create a stash in the test repo.
*/
export function createStash(repoPath: string, message?: string): void {
writeFileSync(join(repoPath, 'stash-file.txt'), `stash content ${Date.now()}\n`);
execFileSync('git', ['add', 'stash-file.txt'], { cwd: repoPath, stdio: 'pipe' });
const args = ['stash', 'push'];
if (message) {
args.push('-m', message);
}
execFileSync('git', args, { cwd: repoPath, stdio: 'pipe' });
}
/**
* Get the HEAD sha of the test repo.
*/
export function getHeadSha(repoPath: string): string {
return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: repoPath, encoding: 'utf-8' }).trim();
}