Skip to content

Commit f4edb15

Browse files
committed
Refactor policy reporting code for flexibility and to ignore git issues when git isn't present.
1 parent 28fc021 commit f4edb15

9 files changed

Lines changed: 194 additions & 117 deletions

File tree

‎apps/rush-lib/src/cli/actions/PublishAction.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import { Npm } from '../../utilities/Npm';
1919
import { RushCommandLineParser } from '../RushCommandLineParser';
2020
import { PublishUtilities } from '../../logic/PublishUtilities';
2121
import { ChangelogGenerator } from '../../logic/ChangelogGenerator';
22-
import { GitPolicy } from '../../logic/GitPolicy';
22+
import { GitEmailPolicy } from '../../logic/policy/GitEmailPolicy';
2323
import { PrereleaseToken } from '../../logic/PrereleaseToken';
2424
import { ChangeManager } from '../../logic/ChangeManager';
2525
import { BaseRushAction } from './BaseRushAction';
@@ -173,7 +173,7 @@ export class PublishAction extends BaseRushAction {
173173
* Executes the publish action, which will read change request files, apply changes to package.jsons,
174174
*/
175175
protected run(): Promise<void> {
176-
if (!GitPolicy.getUserEmail(this.rushConfiguration, true)) {
176+
if (!GitEmailPolicy.getUserEmail(this.rushConfiguration)) {
177177
process.exit(1);
178178
return Promise.resolve();
179179
}

‎apps/rush-lib/src/cli/actions/VersionAction.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ import { RushConfiguration } from '../../api/RushConfiguration';
1717
import { VersionControl } from '../../utilities/VersionControl';
1818
import { VersionMismatchFinder } from '../../api/VersionMismatchFinder';
1919
import { RushCommandLineParser } from '../RushCommandLineParser';
20-
import { GitPolicy } from '../../logic/GitPolicy';
20+
import { GitEmailPolicy } from '../../logic/policy/GitEmailPolicy';
21+
import { PolicyValidator } from '../../logic/policy/PolicyValidator';
2122
import { BaseRushAction } from './BaseRushAction';
2223
import { VersionManager } from '../../logic/VersionManager';
2324
import { Git } from '../../logic/Git';
@@ -94,7 +95,8 @@ export class VersionAction extends BaseRushAction {
9495

9596
protected run(): Promise<void> {
9697
return Promise.resolve().then(() => {
97-
const userEmail: string = GitPolicy.getUserEmail(this.rushConfiguration, this._bypassPolicy.value);
98+
PolicyValidator.validatePolicy(this.rushConfiguration, this._bypassPolicy.value);
99+
const userEmail: string = GitEmailPolicy.getUserEmail(this.rushConfiguration);
98100

99101
this._validateInput();
100102

‎apps/rush-lib/src/logic/Git.ts‎

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,33 @@ import * as child_process from 'child_process';
77
import { PublishUtilities } from './PublishUtilities';
88

99
export class Git {
10+
private static _hasGit: boolean | undefined = undefined;
11+
private static _gitPath: string | undefined;
12+
1013
private _targetBranch: string | undefined;
1114

12-
public static detectIfGitIsSupported(): boolean {
13-
const command: string = process.platform === 'win32' ? 'where' : 'which';
14-
const result: child_process.SpawnSyncReturns<string> = child_process.spawnSync(command, ['git']);
15+
public static getGitPath(): string | undefined {
16+
if (Git._hasGit === undefined) {
17+
const command: string = process.platform === 'win32' ? 'where' : 'which';
18+
const result: child_process.SpawnSyncReturns<string> = child_process.spawnSync(command, ['git']);
1519

16-
if (result.status !== 0) {
17-
return false;
20+
if (result.status === 0) {
21+
Git._gitPath = result.stdout;
22+
}
1823
}
1924

20-
try {
21-
return !!gitInfo().sha;
22-
} catch (e) {
23-
return false; // Unexpected, but possible if the .git directory is corrupted.
25+
return Git._gitPath;
26+
}
27+
28+
public static detectIfGitIsSupported(): boolean {
29+
if (Git.getGitPath()) { // Do we even have a git binary?
30+
try {
31+
return !!gitInfo().sha;
32+
} catch (e) {
33+
return false; // Unexpected, but possible if the .git directory is corrupted.
34+
}
35+
} else {
36+
return false;
2437
}
2538
}
2639

‎apps/rush-lib/src/logic/GitPolicy.ts‎

Lines changed: 0 additions & 102 deletions
This file was deleted.

‎apps/rush-lib/src/logic/InstallManager.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import { ApprovedPackagesChecker } from '../logic/ApprovedPackagesChecker';
2525
import { AsyncRecycler } from '../utilities/AsyncRecycler';
2626
import { BaseLinkManager } from '../logic/base/BaseLinkManager';
2727
import { BaseShrinkwrapFile } from '../logic/base/BaseShrinkwrapFile';
28-
import { GitPolicy } from '../logic/GitPolicy';
28+
import { PolicyValidator } from '../logic/policy/PolicyValidator';
2929
import { IRushTempPackageJson } from '../logic/base/BasePackage';
3030
import { LastInstallFlag } from '../api/LastInstallFlag';
3131
import { LinkManagerFactory } from '../logic/LinkManagerFactory';
@@ -206,7 +206,7 @@ export class InstallManager {
206206
return Promise.resolve().then(() => {
207207

208208
// Check the policies
209-
GitPolicy.getUserEmail(this._rushConfiguration, options.bypassPolicy);
209+
PolicyValidator.validatePolicy(this._rushConfiguration, options.bypassPolicy);
210210

211211
ApprovedPackagesChecker.rewriteConfigFiles(this._rushConfiguration);
212212

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2+
// See LICENSE in the project root for license information.
3+
4+
import * as colors from 'colors';
5+
import * as os from 'os';
6+
7+
import { GitPolicy } from './GitPolicy';
8+
import { RushConfiguration } from '../../api/RushConfiguration';
9+
import { AlreadyReportedError } from '../../utilities/AlreadyReportedError';
10+
import { Utilities } from '../../utilities/Utilities';
11+
12+
interface IResultOrError<TResult> {
13+
error?: Error;
14+
result?: TResult;
15+
}
16+
17+
export class GitEmailPolicy extends GitPolicy {
18+
public static getUserEmail(rushConfiguration: RushConfiguration): string {
19+
// Determine the user's account
20+
// Ex: "bob@example.com"
21+
const emailResult: IResultOrError<string> = GitEmailPolicy.tryGetEmail();
22+
if (emailResult.error) {
23+
console.log(
24+
[
25+
`Error: ${emailResult.error.message}`,
26+
'Unable to determine your Git configuration using this command:',
27+
'',
28+
' git config user.email',
29+
'',
30+
`If you didn't configure your e-mail yet, try something like this:`,
31+
...GitEmailPolicy.getEmailExampleLines(rushConfiguration)
32+
].join(os.EOL)
33+
);
34+
throw new AlreadyReportedError();
35+
}
36+
37+
return emailResult.result || '';
38+
}
39+
40+
private static tryGetEmail(): IResultOrError<string> {
41+
try {
42+
return {
43+
result: Utilities.executeCommandAndCaptureOutput(
44+
'git',
45+
['config', 'user.email'],
46+
'.'
47+
).trim()
48+
};
49+
} catch (e) {
50+
return {
51+
error: e
52+
};
53+
}
54+
}
55+
56+
private static getEmailExampleLines(rushConfiguration: RushConfiguration): string[] {
57+
return [
58+
colors.cyan(' git config --local user.name "Mr. Example"'),
59+
colors.cyan(` git config --local user.email "${rushConfiguration.gitSampleEmail || 'example@contoso.com'}"`)
60+
];
61+
}
62+
63+
protected innerValidate(gitPath: string, rushConfiguration: RushConfiguration ): void {
64+
const userEmail: string = GitEmailPolicy.getUserEmail(rushConfiguration);
65+
if (!userEmail) {
66+
console.log(colors.red('Aborting, so you can go fix your settings. (Or use --bypass-policy to skip.)'));
67+
throw new AlreadyReportedError();
68+
}
69+
70+
// sanity check; a valid e-mail should not contain any whitespace
71+
// if this fails, then we have another issue to report
72+
if (userEmail && userEmail.match(/^\S+$/g)) {
73+
console.log('Checking Git policy for this repository.' + os.EOL);
74+
75+
if (rushConfiguration.gitAllowedEmailRegExps.length === 0) {
76+
return;
77+
}
78+
79+
for (const pattern of rushConfiguration.gitAllowedEmailRegExps) {
80+
const regex: RegExp = new RegExp('^' + pattern + '$', 'i');
81+
if (userEmail.match(regex)) {
82+
return;
83+
}
84+
}
85+
}
86+
87+
// Show the user's name as well.
88+
// Ex. "Mr. Example <mr@example.com>"
89+
let fancyEmail: string = colors.cyan(userEmail);
90+
try {
91+
const userName: string = Utilities.executeCommandAndCaptureOutput('git',
92+
['config', 'user.name'], '.').trim();
93+
if (userName) {
94+
fancyEmail = `${userName} <${fancyEmail}>`;
95+
}
96+
} catch (e) {
97+
// but if it fails, this isn't critical, so don't bother them about it
98+
}
99+
100+
debugger;
101+
console.log([
102+
'Hey there! To keep things tidy, this repo asks you to submit your Git commits using an e-mail like ',
103+
rushConfiguration.gitAllowedEmailRegExps.length > 1 ? 'one of these patterns:' : 'this pattern:',
104+
'',
105+
...rushConfiguration.gitAllowedEmailRegExps.map((pattern) => ' ' + colors.cyan(pattern)),
106+
'',
107+
'...but yours is configured like this:',
108+
'',
109+
` ${fancyEmail}`,
110+
'',
111+
'To fix it, you can use commands like this:',
112+
'',
113+
...GitEmailPolicy.getEmailExampleLines(rushConfiguration),
114+
''
115+
].join(os.EOL));
116+
117+
console.log(colors.red('Aborting, so you can go fix your settings. (Or use --bypass-policy to skip.)'));
118+
throw new AlreadyReportedError();
119+
}
120+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2+
// See LICENSE in the project root for license information.
3+
4+
import { RushPolicy } from './RushPolicy';
5+
import { RushConfiguration } from '../../api/RushConfiguration';
6+
import { Git } from '../Git';
7+
8+
export abstract class GitPolicy extends RushPolicy {
9+
public validate(rushConfiguration: RushConfiguration): void {
10+
const gitPath: string | undefined = Git.getGitPath();
11+
if (gitPath) {
12+
this.innerValidate(gitPath, rushConfiguration);
13+
}
14+
}
15+
16+
protected abstract innerValidate(gitPath: string, rushConfiguration: RushConfiguration): void;
17+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2+
// See LICENSE in the project root for license information.
3+
4+
import { RushConfiguration } from '../../api/RushConfiguration';
5+
import { GitEmailPolicy } from './GitEmailPolicy';
6+
import { RushPolicy } from './RushPolicy';
7+
8+
export class PolicyValidator {
9+
public static validatePolicy(rushConfiguration: RushConfiguration, bypassPolicy: boolean): void {
10+
if (bypassPolicy) {
11+
return;
12+
}
13+
14+
const policies: RushPolicy[] = [new GitEmailPolicy()];
15+
for (const policy of policies) {
16+
policy.validate(rushConfiguration);
17+
}
18+
}
19+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2+
// See LICENSE in the project root for license information.
3+
4+
import { RushConfiguration } from '../../api/RushConfiguration';
5+
6+
export abstract class RushPolicy {
7+
public abstract validate(rushConfiguration: RushConfiguration): void;
8+
}

0 commit comments

Comments
 (0)