Skip to content

Commit bfae2fc

Browse files
authored
Merge pull request microsoft#786 from Microsoft/ianc/fixing-git-policy
Refactor policy reporting code for flexibility and to ignore git issues when git isn't present.
2 parents 1a62316 + f174195 commit bfae2fc

14 files changed

Lines changed: 309 additions & 192 deletions

‎apps/rush-lib/src/api/RushConfiguration.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -531,7 +531,7 @@ export class RushConfiguration {
531531

532532
/**
533533
* [Part of the "gitPolicy" feature.]
534-
* A list of regular expressions describing allowable e-mail patterns for Git commits.
534+
* A list of regular expressions describing allowable email patterns for Git commits.
535535
* They are case-insensitive anchored JavaScript RegExps.
536536
* Example: ".*@example\.com"
537537
* This array will never be undefined.
@@ -542,7 +542,7 @@ export class RushConfiguration {
542542

543543
/**
544544
* [Part of the "gitPolicy" feature.]
545-
* An example valid e-mail address that conforms to one of the allowedEmailRegExps.
545+
* An example valid email address that conforms to one of the allowedEmailRegExps.
546546
* Example: "foxtrot@example\.com"
547547
* This will never be undefined, and will always be nonempty if gitAllowedEmailRegExps is used.
548548
*/

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ export class ChangeAction extends BaseRushAction {
228228
});
229229
} else {
230230
this._warnUncommittedChanges();
231-
// We are done, collect their e-mail
231+
// We are done, collect their email
232232
return this._detectOrAskForEmail().then((email: string) => {
233233
this._changeFileData.forEach((changeFile: IChangeFile) => {
234234
changeFile.email = email;
@@ -393,7 +393,7 @@ export class ChangeAction extends BaseRushAction {
393393
}
394394

395395
/**
396-
* Asks the user for their e-mail address
396+
* Asks the user for their email address
397397
*/
398398
private _promptForEmail(): Promise<string> {
399399
return this._prompt([

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

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,12 @@ 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';
2322
import { PrereleaseToken } from '../../logic/PrereleaseToken';
2423
import { ChangeManager } from '../../logic/ChangeManager';
2524
import { BaseRushAction } from './BaseRushAction';
26-
import { Git } from '../../logic/Git';
25+
import { PublishGit } from '../../logic/PublishGit';
2726
import { VersionControl } from '../../utilities/VersionControl';
27+
import { PolicyValidator } from '../../logic/policy/PolicyValidator';
2828

2929
export class PublishAction extends BaseRushAction {
3030
private _addCommitDetails: CommandLineFlagParameter;
@@ -173,29 +173,28 @@ 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)) {
177-
process.exit(1);
178-
return Promise.resolve();
179-
}
180-
const allPackages: Map<string, RushConfigurationProject> = this.rushConfiguration.projectsByName;
176+
return Promise.resolve().then(() => {
177+
PolicyValidator.validatePolicy(this.rushConfiguration, false);
181178

182-
if (this._regenerateChangelogs.value) {
183-
console.log('Regenerating changelogs');
184-
ChangelogGenerator.regenerateChangelogs(allPackages, this.rushConfiguration);
185-
return Promise.resolve();
186-
}
179+
const allPackages: Map<string, RushConfigurationProject> = this.rushConfiguration.projectsByName;
187180

188-
this._validate();
181+
if (this._regenerateChangelogs.value) {
182+
console.log('Regenerating changelogs');
183+
ChangelogGenerator.regenerateChangelogs(allPackages, this.rushConfiguration);
184+
return Promise.resolve();
185+
}
189186

190-
if (this._includeAll.value) {
191-
this._publishAll(allPackages);
192-
} else {
193-
this._prereleaseToken = new PrereleaseToken(this._prereleaseName.value, this._suffix.value);
194-
this._publishChanges(allPackages);
195-
}
187+
this._validate();
196188

197-
console.log(EOL + colors.green('Rush publish finished successfully.'));
198-
return Promise.resolve();
189+
if (this._includeAll.value) {
190+
this._publishAll(allPackages);
191+
} else {
192+
this._prereleaseToken = new PrereleaseToken(this._prereleaseName.value, this._suffix.value);
193+
this._publishChanges(allPackages);
194+
}
195+
196+
console.log(EOL + colors.green('Rush publish finished successfully.'));
197+
});
199198
}
200199

201200
/**
@@ -224,7 +223,7 @@ export class PublishAction extends BaseRushAction {
224223

225224
if (changeManager.hasChanges()) {
226225
const orderedChanges: IChangeInfo[] = changeManager.changes;
227-
const git: Git = new Git(this._targetBranch.value);
226+
const git: PublishGit = new PublishGit(this._targetBranch.value);
228227
const tempBranch: string = 'publish-' + new Date().getTime();
229228

230229
// Make changes in temp branch.
@@ -279,7 +278,7 @@ export class PublishAction extends BaseRushAction {
279278
console.log(`Rush publish starts with includeAll and version policy ${this._versionPolicy.value}`);
280279

281280
let updated: boolean = false;
282-
const git: Git = new Git(this._targetBranch.value);
281+
const git: PublishGit = new PublishGit(this._targetBranch.value);
283282

284283
allPackages.forEach((packageConfig, packageName) => {
285284
if (packageConfig.shouldPublish &&
@@ -303,7 +302,7 @@ export class PublishAction extends BaseRushAction {
303302
}
304303
}
305304

306-
private _gitAddTags(git: Git, orderedChanges: IChangeInfo[]): void {
305+
private _gitAddTags(git: PublishGit, orderedChanges: IChangeInfo[]): void {
307306
for (const change of orderedChanges) {
308307
if (
309308
change.changeType &&

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,5 +51,4 @@ export class PurgeAction extends BaseRushAction {
5151
+ ` (${stopwatch.toString()})`));
5252
});
5353
}
54-
5554
}

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@ 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 { PolicyValidator } from '../../logic/policy/PolicyValidator';
2121
import { BaseRushAction } from './BaseRushAction';
2222
import { VersionManager } from '../../logic/VersionManager';
23+
import { PublishGit } from '../../logic/PublishGit';
2324
import { Git } from '../../logic/Git';
2425

2526
export class VersionAction extends BaseRushAction {
@@ -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 = Git.getGitEmail(this.rushConfiguration);
98100

99101
this._validateInput();
100102

@@ -119,7 +121,6 @@ export class VersionAction extends BaseRushAction {
119121
true);
120122
this._gitProcess(tempBranch);
121123
}
122-
return Promise.resolve();
123124
});
124125
}
125126

@@ -193,7 +194,7 @@ export class VersionAction extends BaseRushAction {
193194
// Validate the result before commit.
194195
this._validateResult();
195196

196-
const git: Git = new Git(this._targetBranch.value);
197+
const git: PublishGit = new PublishGit(this._targetBranch.value);
197198

198199
// Make changes in temp branch.
199200
git.checkout(tempBranch, true);

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

Lines changed: 88 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -3,76 +3,110 @@
33

44
import gitInfo = require('git-repo-info');
55
import * as child_process from 'child_process';
6+
import * as os from 'os';
67

7-
import { PublishUtilities } from './PublishUtilities';
8+
import { Utilities } from '../utilities/Utilities';
9+
import { AlreadyReportedError } from '../utilities/AlreadyReportedError';
10+
import { GitEmailPolicy } from './policy/GitEmailPolicy';
11+
import { RushConfiguration } from '../api/RushConfiguration';
812

9-
export class Git {
10-
private _targetBranch: string | undefined;
11-
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-
16-
if (result.status !== 0) {
17-
return false;
18-
}
13+
interface IResultOrError<TResult> {
14+
error?: Error;
15+
result?: TResult;
16+
}
1917

20-
try {
21-
return !!gitInfo().sha;
22-
} catch (e) {
23-
return false; // Unexpected, but possible if the .git directory is corrupted.
18+
export class Git {
19+
private static _hasGit: boolean | undefined = undefined;
20+
private static _gitPath: string | undefined;
21+
22+
/**
23+
* Returns the path to the git binary if git is found. If git can't be found, return undefined.
24+
*/
25+
public static getGitPath(): string | undefined {
26+
if (Git._hasGit === undefined) {
27+
const command: string = process.platform === 'win32' ? 'where' : 'which';
28+
const result: child_process.SpawnSyncReturns<string> = child_process.spawnSync(command, ['git']);
29+
30+
if (result.status === 0) {
31+
Git._gitPath = result.stdout;
32+
Git._hasGit = !!result.stdout;
33+
}
2434
}
25-
}
2635

27-
constructor(targetBranch: string | undefined) {
28-
this._targetBranch = targetBranch;
36+
return Git._gitPath;
2937
}
3038

31-
public checkout(branchName: string | undefined, createBranch?: boolean): void {
32-
const params: string = `checkout ${createBranch ? '-b ' : ''}${branchName}`;
33-
34-
PublishUtilities.execCommand(!!this._targetBranch, 'git', params.split(' '));
39+
public static isGitPresent(): boolean {
40+
return !!Git.getGitPath();
3541
}
3642

37-
public merge(branchName: string): void {
38-
PublishUtilities.execCommand(!!this._targetBranch, 'git', `merge ${branchName} --no-edit`.split(' '));
39-
}
40-
41-
public deleteBranch(branchName: string, hasRemote: boolean = true): void {
42-
PublishUtilities.execCommand(!!this._targetBranch, 'git', `branch -d ${branchName}`.split(' '));
43-
if (hasRemote) {
44-
PublishUtilities.execCommand(!!this._targetBranch, 'git', `push origin --delete ${branchName}`.split(' '));
43+
/**
44+
* Checks if git is supported and if the current path is under a git working tree.
45+
*/
46+
public static isPathUnderGitWorkingTree(): boolean {
47+
if (Git.isGitPresent()) { // Do we even have a git binary?
48+
try {
49+
return !!gitInfo().sha;
50+
} catch (e) {
51+
return false; // Unexpected, but possible if the .git directory is corrupted.
52+
}
53+
} else {
54+
return false;
4555
}
4656
}
4757

48-
public pull(): void {
49-
PublishUtilities.execCommand(!!this._targetBranch, 'git', `pull origin ${this._targetBranch}`.split(' '));
50-
}
58+
public static getGitEmail(rushConfiguration: RushConfiguration): string {
59+
// Determine the user's account
60+
// Ex: "bob@example.com"
61+
const emailResult: IResultOrError<string> = Git.tryGetGitEmail();
62+
if (emailResult.error) {
63+
console.log(
64+
[
65+
`Error: ${emailResult.error.message}`,
66+
'Unable to determine your Git configuration using this command:',
67+
'',
68+
' git config user.email',
69+
''
70+
].join(os.EOL)
71+
);
72+
throw new AlreadyReportedError();
73+
}
5174

52-
public addChanges(pathspec?: string, workingDirectory?: string): void {
53-
const files: string = pathspec ? pathspec : '.';
54-
PublishUtilities.execCommand(!!this._targetBranch, 'git', ['add', files],
55-
workingDirectory ? workingDirectory : process.cwd());
56-
}
75+
if (!emailResult.result) {
76+
console.log([
77+
'This operation requires that a git email be specified.',
78+
'',
79+
`If you didn't configure your email yet, try something like this:`,
80+
'',
81+
...GitEmailPolicy.getEmailExampleLines(rushConfiguration),
82+
''
83+
].join(os.EOL));
84+
throw new AlreadyReportedError();
85+
}
5786

58-
public addTag(shouldExecute: boolean, packageName: string, packageVersion: string): void {
59-
// Tagging only happens if we're publishing to real NPM and committing to git.
60-
const tagName: string = PublishUtilities.createTagname(packageName, packageVersion);
61-
PublishUtilities.execCommand(
62-
!!this._targetBranch && shouldExecute,
63-
'git',
64-
['tag', '-a', tagName, '-m', `${packageName} v${packageVersion}`]);
87+
return emailResult.result;
6588
}
6689

67-
public commit(message?: string): void {
68-
const commitMessage: string = message ? message : 'Applying package updates.';
69-
PublishUtilities.execCommand(!!this._targetBranch, 'git', ['commit', '-m', commitMessage]);
70-
}
90+
private static tryGetGitEmail(): IResultOrError<string> {
91+
const gitPath: string | undefined = Git.getGitPath();
92+
if (!gitPath) {
93+
return {
94+
error: new Error('Git isn\'t present on the path')
95+
};
96+
}
7197

72-
public push(branchName: string | undefined): void {
73-
PublishUtilities.execCommand(
74-
!!this._targetBranch,
75-
'git',
76-
['push', 'origin', 'HEAD:' + branchName, '--follow-tags', '--verbose']);
98+
try {
99+
return {
100+
result: Utilities.executeCommandAndCaptureOutput(
101+
'git',
102+
['config', 'user.email'],
103+
'.'
104+
).trim()
105+
};
106+
} catch (e) {
107+
return {
108+
error: e
109+
};
110+
}
77111
}
78112
}

0 commit comments

Comments
 (0)