-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstall.ts
More file actions
364 lines (316 loc) · 9.5 KB
/
Copy pathinstall.ts
File metadata and controls
364 lines (316 loc) · 9.5 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
import { spawnSync } from 'node:child_process';
import {
chmodSync,
existsSync,
mkdirSync,
readFileSync,
statSync,
writeFileSync,
} from 'node:fs';
import path from 'node:path';
import { createHookFiles, hookNames } from './hooks.ts';
const defaultHooksDir = '.rstack/hooks';
const generatedDirectoryName = '_';
const ownerFileName = '.owner';
const gitignore = '*\n';
type InstallHooksOptions = {
cwd?: string;
hooksDir?: string;
};
type FailedInstallResult = {
status: 'failed';
reason: string;
message: string;
};
type SkippedInstallResult = {
status: 'skipped';
reason: string;
message?: string;
};
type InstallResult =
| { status: 'installed'; hooksPath: string }
| { status: 'unchanged'; hooksPath: string }
| SkippedInstallResult
| FailedInstallResult;
type GitContext = {
defaultHooksDirectory: string;
effectiveHooksDirectory: string;
gitRoot: string;
projectPath: string;
};
const fail = (reason: string, message: string): FailedInstallResult => ({
status: 'failed',
reason,
message,
});
const skip = (reason: string, message?: string): SkippedInstallResult => ({
status: 'skipped',
reason,
...(message ? { message } : {}),
});
const resolveHooksDir = (hooksDir: string): string | FailedInstallResult => {
const resolvedDir = hooksDir.replaceAll('\\', '/');
if (resolvedDir.length === 0) {
return fail(
'invalid-hooks-directory',
'Git hooks directory must not be empty.',
);
}
if (path.isAbsolute(resolvedDir)) {
return fail(
'invalid-hooks-directory',
'Git hooks directory must be relative to the Git repository root.',
);
}
if (resolvedDir.includes('..')) {
return fail(
'invalid-hooks-directory',
'Git hooks directory must not contain "..".',
);
}
return resolvedDir;
};
const runGit = (cwd: string, args: string[]) =>
spawnSync('git', args, { cwd, encoding: 'utf8' });
const removeLineEnding = (value: string): string =>
value.replace(/\r?\n$/u, '');
const gitFailure = (
error: NodeJS.ErrnoException | undefined,
stderr: string,
): FailedInstallResult => {
if (error?.code === 'ENOENT') {
return fail('git-not-found', 'Git command not found.');
}
return fail(
'git-command-failed',
`Failed to run Git: ${error?.message || stderr.trim()}`,
);
};
const resolveGitContext = (cwd: string): GitContext | InstallResult => {
// Resolve every repository path in one Git process. `--git-path hooks`
// accounts for an existing local or global core.hooksPath configuration.
const repository = runGit(cwd, [
'rev-parse',
'--is-inside-work-tree',
'--path-format=absolute',
'--show-toplevel',
'--show-prefix',
'--git-common-dir',
'--git-path',
'hooks',
]);
if (repository.error || repository.status === null) {
return gitFailure(repository.error, repository.stderr);
}
const [
insideWorkTree = '',
gitRoot = '',
repositoryPrefix = '',
gitCommonDirectory = '',
effectiveHooksDirectory = '',
] = removeLineEnding(repository.stdout).split(/\r?\n/u);
if (insideWorkTree !== 'true') {
return skip('not-git-repository');
}
if (repository.status !== 0) {
return fail(
'git-command-failed',
`Failed to resolve the Git repository paths: ${repository.stderr.trim()}`,
);
}
if (!gitRoot || !gitCommonDirectory || !effectiveHooksDirectory) {
return fail(
'git-command-failed',
'Failed to resolve the Git repository paths.',
);
}
return {
defaultHooksDirectory: path.join(gitCommonDirectory, 'hooks'),
effectiveHooksDirectory,
gitRoot,
projectPath:
repositoryPrefix.replaceAll('\\', '/').replace(/\/$/u, '') || '.',
};
};
const isCurrentFile = (
filePath: string,
content: string,
executable = false,
): boolean => {
try {
// Windows does not expose POSIX executable bits, but Git for Windows still runs hook shims.
return (
readFileSync(filePath, 'utf8') === content &&
(!executable ||
process.platform === 'win32' ||
(statSync(filePath).mode & 0o777) === 0o755)
);
} catch {
return false;
}
};
const isSamePath = (first: string, second: string): boolean =>
path.resolve(first) === path.resolve(second);
const readOwner = (directory: string): string | undefined => {
try {
const content = readFileSync(path.join(directory, ownerFileName), 'utf8');
const owner = removeLineEnding(content);
return content === `${owner}\n` &&
owner.length > 0 &&
!/[\r\n]/u.test(owner)
? owner
: undefined;
} catch {
return undefined;
}
};
const displayPath = (gitRoot: string, filePath: string): string => {
const relativePath = path.relative(gitRoot, filePath).replaceAll('\\', '/');
return relativePath.length > 0 && !relativePath.startsWith('../')
? relativePath
: filePath;
};
const ownerConflict = (project: string): SkippedInstallResult =>
skip(
'owned-by-another-project',
`Git hooks are already managed by Rstack project "${project}"`,
);
const directoryConflict = (
gitRoot: string,
directory: string,
): SkippedInstallResult =>
skip(
'hooks-directory-conflict',
`the hooks directory "${displayPath(gitRoot, directory)}" is not managed by Rstack`,
);
const claimOwner = (
directory: string,
gitRoot: string,
project: string,
): SkippedInstallResult | undefined => {
const ownerPath = path.join(directory, ownerFileName);
const owner = readOwner(directory);
if (owner) {
return owner === project ? undefined : ownerConflict(owner);
}
try {
// Exclusive creation makes concurrent prepare scripts agree on one owner.
writeFileSync(ownerPath, `${project}\n`, { flag: 'wx' });
} catch (error) {
const code =
error instanceof Error && 'code' in error ? error.code : undefined;
if (code !== 'EEXIST') {
throw error;
}
const concurrentOwner = readOwner(directory);
if (!concurrentOwner) {
return directoryConflict(gitRoot, directory);
}
return concurrentOwner === project
? undefined
: ownerConflict(concurrentOwner);
}
return undefined;
};
const findExistingHooks = (directory: string): string[] =>
hookNames.filter((name) => existsSync(path.join(directory, name)));
export const installHooks = ({
cwd = process.cwd(),
hooksDir = defaultHooksDir,
}: InstallHooksOptions = {}): InstallResult => {
if (process.env.RSTACK_HOOKS === '0') {
return skip('disabled');
}
const resolvedDir = resolveHooksDir(hooksDir);
if (typeof resolvedDir !== 'string') {
return resolvedDir;
}
// Check Git before touching the filesystem so non-repositories have no side effects.
const context = resolveGitContext(cwd);
if ('status' in context) {
return context;
}
const {
defaultHooksDirectory,
effectiveHooksDirectory,
gitRoot,
projectPath,
} = context;
const hooksPath = `${resolvedDir}/${generatedDirectoryName}`;
const directory = path.join(gitRoot, resolvedDir, generatedDirectoryName);
const hooksPathMatches = isSamePath(effectiveHooksDirectory, directory);
const usesDefaultHooks = isSamePath(
effectiveHooksDirectory,
defaultHooksDirectory,
);
if (!hooksPathMatches && !usesDefaultHooks) {
const activeOwner = readOwner(effectiveHooksDirectory);
if (!activeOwner) {
return skip(
'hooks-path-conflict',
`Git hooks are already configured at "${displayPath(gitRoot, effectiveHooksDirectory)}"`,
);
}
if (activeOwner !== projectPath) {
return ownerConflict(activeOwner);
}
}
if (usesDefaultHooks) {
const existingHooks = findExistingHooks(defaultHooksDirectory);
if (existingHooks.length > 0) {
return skip(
'existing-git-hooks',
`existing Git hooks were found: ${existingHooks.join(', ')}`,
);
}
}
const files = Object.entries(createHookFiles());
try {
mkdirSync(directory, { recursive: true });
const ownerResult = claimOwner(directory, gitRoot, projectPath);
if (ownerResult) {
return ownerResult;
}
// Skip generated file writes when their content and executable modes match.
const unchanged =
hooksPathMatches &&
isCurrentFile(path.join(directory, '.gitignore'), gitignore) &&
files.every(([name, content]) =>
isCurrentFile(path.join(directory, name), content, true),
);
if (unchanged) {
return { status: 'unchanged', hooksPath };
}
writeFileSync(path.join(directory, '.gitignore'), gitignore);
for (const [name, content] of files) {
const filePath = path.join(directory, name);
writeFileSync(filePath, content);
// chmod also repairs existing files because writeFile does not update their mode.
chmodSync(filePath, 0o755);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return fail('write-failed', `Failed to write Git hook files: ${message}`);
}
// Avoid rewriting .git/config when only the generated files needed repair.
if (hooksPathMatches) {
return { status: 'installed', hooksPath };
}
// Point Git at the generated directory only after every runtime file is ready.
const configured = runGit(cwd, [
'config',
'--local',
'core.hooksPath',
hooksPath,
]);
if (configured.error || configured.status === null) {
return gitFailure(configured.error, configured.stderr);
}
if (configured.status !== 0) {
return fail(
'git-config-failed',
`Failed to configure core.hooksPath: ${configured.stderr.trim()}`,
);
}
return { status: 'installed', hooksPath };
};