-
Notifications
You must be signed in to change notification settings - Fork 592
/
Git.ts
617 lines (549 loc) · 19.6 KB
/
Git.ts
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
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import type child_process from 'child_process';
import gitInfo from 'git-repo-info';
import * as path from 'path';
import * as url from 'url';
import { trueCasePathSync } from 'true-case-path';
import { Executable, AlreadyReportedError, Path } from '@rushstack/node-core-library';
import { Colorize, type ITerminal } from '@rushstack/terminal';
import { ensureGitMinimumVersion } from '@rushstack/package-deps-hash';
import { Utilities } from '../utilities/Utilities';
import * as GitEmailPolicy from './policy/GitEmailPolicy';
import type { RushConfiguration } from '../api/RushConfiguration';
import { EnvironmentConfiguration } from '../api/EnvironmentConfiguration';
import { type IChangedGitStatusEntry, type IGitStatusEntry, parseGitStatus } from './GitStatusParser';
import { RushConstants } from './RushConstants';
export const DEFAULT_GIT_TAG_SEPARATOR: string = '_';
interface IResultOrError<TResult> {
error?: Error;
result?: TResult;
}
export interface IGetBlobOptions {
blobSpec: string;
repositoryRoot: string;
}
export class Git {
private readonly _rushConfiguration: RushConfiguration;
private _checkedGitPath: boolean = false;
private _gitPath: string | undefined;
private _checkedGitInfo: boolean = false;
private _gitInfo: gitInfo.GitRepoInfo | undefined;
private _gitEmailResult: IResultOrError<string> | undefined = undefined;
private _gitHooksPath: IResultOrError<string> | undefined = undefined;
public constructor(rushConfiguration: RushConfiguration) {
this._rushConfiguration = rushConfiguration;
}
/**
* Returns the path to the Git binary if found. Otherwise, return undefined.
*/
public get gitPath(): string | undefined {
if (!this._checkedGitPath) {
this._gitPath = EnvironmentConfiguration.gitBinaryPath || Executable.tryResolve('git');
this._checkedGitPath = true;
}
return this._gitPath;
}
public getGitPathOrThrow(): string {
const gitPath: string | undefined = this.gitPath;
if (!gitPath) {
throw new Error('Git is not present');
} else {
return gitPath;
}
}
/**
* Returns true if the Git binary can be found.
*/
public isGitPresent(): boolean {
return !!this.gitPath;
}
/**
* Returns true if the Git binary was found and the current path is under a Git working tree.
* @param repoInfo - If provided, do the check based on this Git repo info. If not provided,
* the result of `this.getGitInfo()` is used.
*/
public isPathUnderGitWorkingTree(repoInfo?: gitInfo.GitRepoInfo): boolean {
if (this.isGitPresent()) {
// Do we even have a Git binary?
if (!repoInfo) {
repoInfo = this.getGitInfo();
}
return !!(repoInfo && repoInfo.sha);
} else {
return false;
}
}
/**
* If a Git email address is configured and is nonempty, this returns it.
* Otherwise, undefined is returned.
*/
public tryGetGitEmail(): string | undefined {
const emailResult: IResultOrError<string> = this._tryGetGitEmail();
if (emailResult.result !== undefined && emailResult.result.length > 0) {
return emailResult.result;
}
return undefined;
}
/**
* If a Git email address is configured and is nonempty, this returns it.
* Otherwise, configuration instructions are printed to the console,
* and AlreadyReportedError is thrown.
*/
public getGitEmail(): string {
// Determine the user's account
// Ex: "bob@example.com"
const emailResult: IResultOrError<string> = this._tryGetGitEmail();
if (emailResult.error) {
// eslint-disable-next-line no-console
console.log(
[
`Error: ${emailResult.error.message}`,
'Unable to determine your Git configuration using this command:',
'',
' git config user.email',
''
].join('\n')
);
throw new AlreadyReportedError();
}
if (emailResult.result === undefined || emailResult.result.length === 0) {
// eslint-disable-next-line no-console
console.log(
[
'This operation requires that a Git email be specified.',
'',
`If you didn't configure your email yet, try something like this:`,
'',
...GitEmailPolicy.getEmailExampleLines(this._rushConfiguration),
''
].join('\n')
);
throw new AlreadyReportedError();
}
return emailResult.result;
}
/**
* Get the folder where Git hooks should go for the current working tree.
* Returns undefined if the current path is not under a Git working tree.
*/
public getHooksFolder(): string | undefined {
const repoInfo: gitInfo.GitRepoInfo | undefined = this.getGitInfo();
if (repoInfo && repoInfo.worktreeGitDir) {
return path.join(repoInfo.worktreeGitDir, 'hooks');
}
return undefined;
}
public isHooksPathDefault(): boolean {
const repoInfo: gitInfo.GitRepoInfo | undefined = this.getGitInfo();
if (!repoInfo?.commonGitDir) {
// This should have never been called in a non-Git environment
return true;
}
let commonGitDir: string = repoInfo.commonGitDir;
try {
commonGitDir = trueCasePathSync(commonGitDir);
} catch (error) {
/* ignore errors from true-case-path */
}
const defaultHooksPath: string = path.resolve(commonGitDir, 'hooks');
const hooksResult: IResultOrError<string> = this._tryGetGitHooksPath();
if (hooksResult.error) {
// eslint-disable-next-line no-console
console.log(
[
`Error: ${hooksResult.error.message}`,
'Unable to determine your Git configuration using this command:',
'',
' git rev-parse --git-path hooks',
'',
'Assuming hooks can still be installed in the default location'
].join('\n')
);
return true;
}
if (hooksResult.result) {
const absoluteHooksPath: string = path.resolve(
this._rushConfiguration.rushJsonFolder,
hooksResult.result
);
return absoluteHooksPath === defaultHooksPath;
}
// No error, but also empty result? Not sure it's possible.
return true;
}
public getConfigHooksPath(): string {
let configHooksPath: string = '';
const gitPath: string = this.getGitPathOrThrow();
try {
configHooksPath = this._executeGitCommandAndCaptureOutput(gitPath, ['config', 'core.hooksPath']).trim();
} catch (e) {
// git config returns error code 1 if core.hooksPath is not set.
}
return configHooksPath;
}
/**
* Get information about the current Git working tree.
* Returns undefined if rush.json is not under a Git working tree.
*/
public getGitInfo(): Readonly<gitInfo.GitRepoInfo> | undefined {
if (!this._checkedGitInfo) {
let repoInfo: gitInfo.GitRepoInfo | undefined;
try {
// gitInfo() shouldn't usually throw, but wrapping in a try/catch just in case
repoInfo = gitInfo(this._rushConfiguration.rushJsonFolder);
} catch (ex) {
// if there's an error, assume we're not in a Git working tree
}
if (repoInfo && this.isPathUnderGitWorkingTree(repoInfo)) {
this._gitInfo = repoInfo;
}
this._checkedGitInfo = true;
}
return this._gitInfo;
}
public getMergeBase(targetBranch: string, terminal: ITerminal, shouldFetch: boolean = false): string {
if (shouldFetch) {
this._fetchRemoteBranch(targetBranch, terminal);
}
const gitPath: string = this.getGitPathOrThrow();
try {
const output: string = this._executeGitCommandAndCaptureOutput(gitPath, [
'--no-optional-locks',
'merge-base',
'--',
'HEAD',
targetBranch
]);
const result: string = output.trim();
return result;
} catch (e) {
terminal.writeErrorLine(
`Unable to determine merge base for branch "${targetBranch}". ` +
'This can occur if the current clone is a shallow clone. If this clone is running in a CI ' +
'pipeline, check your pipeline settings to ensure that the clone depth includes ' +
'the expected merge base. If this clone is running locally, consider running "git fetch --deepen=<depth>".'
);
throw new AlreadyReportedError();
}
}
public getBlobContent({ blobSpec, repositoryRoot }: IGetBlobOptions): string {
const gitPath: string = this.getGitPathOrThrow();
const output: string = this._executeGitCommandAndCaptureOutput(
gitPath,
['cat-file', 'blob', blobSpec, '--'],
repositoryRoot
);
return output;
}
/**
* @param pathPrefix - An optional path prefix "git diff"s should be filtered by.
* @returns
* An array of paths of repo-root-relative paths of files that are different from
* those in the provided {@param targetBranch}. If a {@param pathPrefix} is provided,
* this function only returns results under the that path.
*/
public getChangedFiles(
targetBranch: string,
terminal: ITerminal,
skipFetch: boolean = false,
pathPrefix?: string
): string[] {
if (!skipFetch) {
this._fetchRemoteBranch(targetBranch, terminal);
}
const gitPath: string = this.getGitPathOrThrow();
const output: string = this._executeGitCommandAndCaptureOutput(gitPath, [
'diff',
`${targetBranch}...`,
'--name-only',
'--no-renames',
'--diff-filter=A'
]);
return output
.split('\n')
.map((line) => {
if (line) {
const trimmedLine: string = line.trim();
if (!pathPrefix || Path.isUnderOrEqual(trimmedLine, pathPrefix)) {
return trimmedLine;
}
} else {
return undefined;
}
})
.filter((line) => {
return line && line.length > 0;
}) as string[];
}
/**
* Gets the remote default branch that maps to the provided repository url.
* This method is used by 'Rush change' to find the default remote branch to compare against.
* If repository url is not provided or if there is no match, returns the default remote's
* default branch 'origin/main'.
* If there are more than one matches, returns the first remote's default branch.
*
* @param rushConfiguration - rush configuration
*/
public getRemoteDefaultBranch(): string {
const repositoryUrls: string[] = this._rushConfiguration.repositoryUrls;
if (repositoryUrls.length > 0) {
const gitPath: string = this.getGitPathOrThrow();
const output: string = this._executeGitCommandAndCaptureOutput(gitPath, ['remote']).trim();
const normalizedRepositoryUrls: Set<string> = new Set<string>();
for (const repositoryUrl of repositoryUrls) {
// Apply toUpperCase() for a case-insensitive comparison
normalizedRepositoryUrls.add(Git.normalizeGitUrlForComparison(repositoryUrl).toUpperCase());
}
const matchingRemotes: string[] = output.split('\n').filter((remoteName) => {
if (remoteName) {
const remoteUrl: string = this._executeGitCommandAndCaptureOutput(gitPath, [
'remote',
'get-url',
'--',
remoteName
]).trim();
if (!remoteUrl) {
return false;
}
// Also apply toUpperCase() for a case-insensitive comparison
const normalizedRemoteUrl: string = Git.normalizeGitUrlForComparison(remoteUrl).toUpperCase();
if (normalizedRepositoryUrls.has(normalizedRemoteUrl)) {
return true;
}
}
return false;
});
if (matchingRemotes.length > 0) {
if (matchingRemotes.length > 1) {
// eslint-disable-next-line no-console
console.log(
`More than one git remote matches the repository URL. Using the first remote (${matchingRemotes[0]}).`
);
}
return `${matchingRemotes[0]}/${this._rushConfiguration.repositoryDefaultBranch}`;
} else {
const errorMessage: string =
repositoryUrls.length > 1
? `Unable to find a git remote matching one of the repository URLs (${repositoryUrls.join(
', '
)}). `
: `Unable to find a git remote matching the repository URL (${repositoryUrls[0]}). `;
// eslint-disable-next-line no-console
console.log(Colorize.yellow(errorMessage + 'Detected changes are likely to be incorrect.'));
return this._rushConfiguration.repositoryDefaultFullyQualifiedRemoteBranch;
}
} else {
// eslint-disable-next-line no-console
console.log(
Colorize.yellow(
`A git remote URL has not been specified in ${RushConstants.rushJsonFilename}. Setting the baseline remote URL is recommended.`
)
);
return this._rushConfiguration.repositoryDefaultFullyQualifiedRemoteBranch;
}
}
public hasUncommittedChanges(): boolean {
const gitStatusEntries: Iterable<IGitStatusEntry> = this.getGitStatus();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const gitStatusEntry of gitStatusEntries) {
// If there are any changes, return true. We only need to evaluate the first iterator entry
return true;
}
return false;
}
public hasUnstagedChanges(): boolean {
const gitStatusEntries: Iterable<IGitStatusEntry> = this.getGitStatus();
for (const gitStatusEntry of gitStatusEntries) {
if (
gitStatusEntry.kind === 'untracked' ||
(gitStatusEntry as IChangedGitStatusEntry).unstagedChangeType !== undefined
) {
return true;
}
}
return false;
}
/**
* The list of files changed but not committed
*/
public getUncommittedChanges(): ReadonlyArray<string> {
const result: string[] = [];
const gitStatusEntries: Iterable<IGitStatusEntry> = this.getGitStatus();
for (const gitStatusEntry of gitStatusEntries) {
result.push(gitStatusEntry.path);
}
return result;
}
public getTagSeparator(): string {
return this._rushConfiguration.gitTagSeparator || DEFAULT_GIT_TAG_SEPARATOR;
}
public getGitStatus(): Iterable<IGitStatusEntry> {
const gitPath: string = this.getGitPathOrThrow();
// See Git.test.ts for example output
const output: string = this._executeGitCommandAndCaptureOutput(gitPath, [
'status',
'--porcelain=2',
'--null',
'--ignored=no'
]);
return parseGitStatus(output);
}
/**
* Git remotes can use different URL syntaxes; this converts them all to a normalized HTTPS
* representation for matching purposes. IF THE INPUT IS NOT ALREADY HTTPS, THE OUTPUT IS
* NOT NECESSARILY A VALID GIT URL.
*
* @example
* `git@github.com:ExampleOrg/ExampleProject.git` --> `https://github.com/ExampleOrg/ExampleProject`
*/
public static normalizeGitUrlForComparison(gitUrl: string): string {
// Git URL formats are documented here: https://www.git-scm.com/docs/git-clone#_git_urls
let result: string = gitUrl.trim();
// [user@]host.xz:path/to/repo.git/
// "This syntax is only recognized if there are no slashes before the first colon. This helps
// differentiate a local path that contains a colon."
//
// Match patterns like this:
// user@host.ext:path/to/repo
// host.ext:path/to/repo
// localhost:/~user/path/to/repo
//
// But not:
// http://blah
// c:/windows/path.txt
//
const scpLikeSyntaxRegExp: RegExp = /^(?:[^@:\/]+\@)?([^:\/]{2,})\:((?!\/\/).+)$/;
// Example: "user@host.ext:path/to/repo"
const scpLikeSyntaxMatch: RegExpExecArray | null = scpLikeSyntaxRegExp.exec(gitUrl);
if (scpLikeSyntaxMatch) {
// Example: "host.ext"
const host: string = scpLikeSyntaxMatch[1];
// Example: "path/to/repo"
const urlPath: string = scpLikeSyntaxMatch[2];
if (urlPath.startsWith('/')) {
result = `https://${host}${urlPath}`;
} else {
result = `https://${host}/${urlPath}`;
}
}
const parsedUrl: url.UrlWithStringQuery = url.parse(result);
// Only convert recognized schemes
switch (parsedUrl.protocol) {
case 'http:':
case 'https:':
case 'ssh:':
case 'ftp:':
case 'ftps:':
case 'git:':
case 'git+http:':
case 'git+https:':
case 'git+ssh:':
case 'git+ftp:':
case 'git+ftps:':
// Assemble the parts we want:
result = `https://${parsedUrl.host}${parsedUrl.pathname}`;
break;
}
// Trim ".git" or ".git/" from the end
result = result.replace(/.git\/?$/, '');
return result;
}
private _tryGetGitEmail(): IResultOrError<string> {
if (this._gitEmailResult === undefined) {
const gitPath: string = this.getGitPathOrThrow();
try {
this._gitEmailResult = {
result: this._executeGitCommandAndCaptureOutput(gitPath, ['config', 'user.email']).trim()
};
} catch (e) {
this._gitEmailResult = {
error: e as Error
};
}
}
return this._gitEmailResult;
}
private _tryGetGitHooksPath(): IResultOrError<string> {
if (this._gitHooksPath === undefined) {
const gitPath: string = this.getGitPathOrThrow();
try {
this._gitHooksPath = {
result: this._executeGitCommandAndCaptureOutput(gitPath, [
'rev-parse',
'--git-path',
'hooks'
]).trim()
};
} catch (e) {
this._gitHooksPath = {
error: e as Error
};
}
}
return this._gitHooksPath;
}
private _tryFetchRemoteBranch(remoteBranchName: string): boolean {
const firstSlashIndex: number = remoteBranchName.indexOf('/');
if (firstSlashIndex === -1) {
throw new Error(
`Unexpected git remote branch format: ${remoteBranchName}. ` +
'Expected branch to be in the <remote>/<branch name> format.'
);
}
const remoteName: string = remoteBranchName.substr(0, firstSlashIndex);
const branchName: string = remoteBranchName.substr(firstSlashIndex + 1);
const gitPath: string = this.getGitPathOrThrow();
const spawnResult: child_process.SpawnSyncReturns<string> = Executable.spawnSync(
gitPath,
['fetch', '--', remoteName, branchName],
{
stdio: 'ignore'
}
);
return spawnResult.status === 0;
}
private _fetchRemoteBranch(remoteBranchName: string, terminal: ITerminal): void {
// eslint-disable-next-line no-console
console.log(`Checking for updates to ${remoteBranchName}...`);
const fetchResult: boolean = this._tryFetchRemoteBranch(remoteBranchName);
if (!fetchResult) {
terminal.writeWarningLine(
`Error fetching git remote branch ${remoteBranchName}. Detected changed files may be incorrect.`
);
}
}
/**
* @internal
*/
public _executeGitCommandAndCaptureOutput(
gitPath: string,
args: string[],
repositoryRoot: string = this._rushConfiguration.rushJsonFolder
): string {
try {
return Utilities.executeCommandAndCaptureOutput(gitPath, args, repositoryRoot);
} catch (e) {
ensureGitMinimumVersion(gitPath);
throw e;
}
}
/**
*
* @param ref Given a ref which can be branch name, commit hash, tag name, etc, check if it is a commit hash
*/
public isRefACommit(ref: string): boolean {
const gitPath: string = this.getGitPathOrThrow();
try {
const output: string = this._executeGitCommandAndCaptureOutput(gitPath, ['rev-parse', '--verify', ref]);
const result: string = output.trim();
if (result === ref) {
return true;
}
} catch (e) {
// assume not a commit
return false;
}
return false;
}
}