Skip to content

Commit bf7ff13

Browse files
committed
Refactor the way git tasks are called and errors are captured.
1 parent aac30fa commit bf7ff13

9 files changed

Lines changed: 198 additions & 178 deletions

File tree

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,11 @@ export abstract class BaseRushAction extends CommandLineAction {
7676
}
7777

7878
console.log(`Starting "rush ${this.actionName}"${os.EOL}`);
79-
return this.run().then(() => {
80-
// If we make it here, everything went fine, so reset the exit code back to 0
81-
process.exitCode = 0;
79+
return Promise.resolve().then(() => {
80+
return this.run().then(() => {
81+
// If we make it here, everything went fine, so reset the exit code back to 0
82+
process.exitCode = 0;
83+
});
8284
});
8385
}
8486

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

Lines changed: 7 additions & 9 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 { GitEmailPolicy } from '../../logic/policy/GitEmailPolicy';
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,10 +173,8 @@ 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 (!GitEmailPolicy.getUserEmail(this.rushConfiguration)) {
177-
process.exit(1);
178-
return Promise.resolve();
179-
}
176+
PolicyValidator.validatePolicy(this.rushConfiguration, false);
177+
180178
const allPackages: Map<string, RushConfigurationProject> = this.rushConfiguration.projectsByName;
181179

182180
if (this._regenerateChangelogs.value) {
@@ -224,7 +222,7 @@ export class PublishAction extends BaseRushAction {
224222

225223
if (changeManager.hasChanges()) {
226224
const orderedChanges: IChangeInfo[] = changeManager.changes;
227-
const git: Git = new Git(this._targetBranch.value);
225+
const git: PublishGit = new PublishGit(this._targetBranch.value);
228226
const tempBranch: string = 'publish-' + new Date().getTime();
229227

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

281279
let updated: boolean = false;
282-
const git: Git = new Git(this._targetBranch.value);
280+
const git: PublishGit = new PublishGit(this._targetBranch.value);
283281

284282
allPackages.forEach((packageConfig, packageName) => {
285283
if (packageConfig.shouldPublish &&
@@ -303,7 +301,7 @@ export class PublishAction extends BaseRushAction {
303301
}
304302
}
305303

306-
private _gitAddTags(git: Git, orderedChanges: IChangeInfo[]): void {
304+
private _gitAddTags(git: PublishGit, orderedChanges: IChangeInfo[]): void {
307305
for (const change of orderedChanges) {
308306
if (
309307
change.changeType &&

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

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -34,22 +34,21 @@ export class PurgeAction extends BaseRushAction {
3434
}
3535

3636
protected run(): Promise<void> {
37-
return Promise.resolve().then(() => {
38-
const stopwatch: Stopwatch = Stopwatch.start();
37+
const stopwatch: Stopwatch = Stopwatch.start();
3938

40-
const purgeManager: PurgeManager = new PurgeManager(this.rushConfiguration);
39+
const purgeManager: PurgeManager = new PurgeManager(this.rushConfiguration);
4140

42-
if (this._unsafeParameter.value!) {
43-
purgeManager.purgeUnsafe();
44-
} else {
45-
purgeManager.purgeNormal();
46-
}
41+
if (this._unsafeParameter.value!) {
42+
purgeManager.purgeUnsafe();
43+
} else {
44+
purgeManager.purgeNormal();
45+
}
4746

48-
purgeManager.deleteAll();
47+
purgeManager.deleteAll();
4948

50-
console.log(os.EOL + colors.green(`Rush purge started successfully and will complete asynchronously.`
51-
+ ` (${stopwatch.toString()})`));
52-
});
53-
}
49+
console.log(os.EOL + colors.green(`Rush purge started successfully and will complete asynchronously.`
50+
+ ` (${stopwatch.toString()})`));
5451

52+
return Promise.resolve();
53+
}
5554
}

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

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +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 { GitEmailPolicy } from '../../logic/policy/GitEmailPolicy';
2120
import { PolicyValidator } from '../../logic/policy/PolicyValidator';
2221
import { BaseRushAction } from './BaseRushAction';
2322
import { VersionManager } from '../../logic/VersionManager';
23+
import { PublishGit } from '../../logic/PublishGit';
2424
import { Git } from '../../logic/Git';
2525

2626
export class VersionAction extends BaseRushAction {
@@ -94,35 +94,34 @@ export class VersionAction extends BaseRushAction {
9494
}
9595

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

101-
this._validateInput();
100+
this._validateInput();
102101

103-
this._versionManager = new VersionManager(this.rushConfiguration, userEmail);
102+
this._versionManager = new VersionManager(this.rushConfiguration, userEmail);
104103

105-
if (this._ensureVersionPolicy.value) {
106-
this._overwritePolicyVersionIfNeeded();
107-
const tempBranch: string = 'version/ensure-' + new Date().getTime();
108-
this._versionManager.ensure(this._versionPolicy.value, true,
109-
!!this._overrideVersion.value || !!this._prereleaseIdentifier.value);
104+
if (this._ensureVersionPolicy.value) {
105+
this._overwritePolicyVersionIfNeeded();
106+
const tempBranch: string = 'version/ensure-' + new Date().getTime();
107+
this._versionManager.ensure(this._versionPolicy.value, true,
108+
!!this._overrideVersion.value || !!this._prereleaseIdentifier.value);
110109

111-
const updatedPackages: Map<string, IPackageJson> = this._versionManager.updatedProjects;
112-
if (updatedPackages.size > 0) {
113-
console.log(`${updatedPackages.size} packages are getting updated.`);
114-
this._gitProcess(tempBranch);
115-
}
116-
} else if (this._bumpVersion.value) {
117-
const tempBranch: string = 'version/bump-' + new Date().getTime();
118-
this._versionManager.bump(this._versionPolicy.value,
119-
this._overwriteBump.value ? BumpType[this._overwriteBump.value] : undefined,
120-
this._prereleaseIdentifier.value,
121-
true);
110+
const updatedPackages: Map<string, IPackageJson> = this._versionManager.updatedProjects;
111+
if (updatedPackages.size > 0) {
112+
console.log(`${updatedPackages.size} packages are getting updated.`);
122113
this._gitProcess(tempBranch);
123114
}
124-
return Promise.resolve();
125-
});
115+
} else if (this._bumpVersion.value) {
116+
const tempBranch: string = 'version/bump-' + new Date().getTime();
117+
this._versionManager.bump(this._versionPolicy.value,
118+
this._overwriteBump.value ? BumpType[this._overwriteBump.value] : undefined,
119+
this._prereleaseIdentifier.value,
120+
true);
121+
this._gitProcess(tempBranch);
122+
}
123+
124+
return Promise.resolve();
126125
}
127126

128127
private _overwritePolicyVersionIfNeeded(): void {
@@ -195,7 +194,7 @@ export class VersionAction extends BaseRushAction {
195194
// Validate the result before commit.
196195
this._validateResult();
197196

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

200199
// Make changes in temp branch.
201200
git.checkout(tempBranch, true);

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

Lines changed: 57 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,30 @@
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';
12+
13+
interface IResultOrError<TResult> {
14+
error?: Error;
15+
result?: TResult;
16+
}
817

918
export class Git {
1019
private static _hasGit: boolean | undefined = undefined;
1120
private static _gitPath: string | undefined;
1221

13-
private _targetBranch: string | undefined;
14-
1522
public static getGitPath(): string | undefined {
1623
if (Git._hasGit === undefined) {
1724
const command: string = process.platform === 'win32' ? 'where' : 'which';
1825
const result: child_process.SpawnSyncReturns<string> = child_process.spawnSync(command, ['git']);
1926

2027
if (result.status === 0) {
2128
Git._gitPath = result.stdout;
29+
Git._hasGit = !!result.stdout;
2230
}
2331
}
2432

@@ -37,55 +45,57 @@ export class Git {
3745
}
3846
}
3947

40-
constructor(targetBranch: string | undefined) {
41-
this._targetBranch = targetBranch;
42-
}
43-
44-
public checkout(branchName: string | undefined, createBranch?: boolean): void {
45-
const params: string = `checkout ${createBranch ? '-b ' : ''}${branchName}`;
46-
47-
PublishUtilities.execCommand(!!this._targetBranch, 'git', params.split(' '));
48-
}
49-
50-
public merge(branchName: string): void {
51-
PublishUtilities.execCommand(!!this._targetBranch, 'git', `merge ${branchName} --no-edit`.split(' '));
52-
}
53-
54-
public deleteBranch(branchName: string, hasRemote: boolean = true): void {
55-
PublishUtilities.execCommand(!!this._targetBranch, 'git', `branch -d ${branchName}`.split(' '));
56-
if (hasRemote) {
57-
PublishUtilities.execCommand(!!this._targetBranch, 'git', `push origin --delete ${branchName}`.split(' '));
48+
public static getGitEmail(rushConfiguration: RushConfiguration): string {
49+
// Determine the user's account
50+
// Ex: "bob@example.com"
51+
const emailResult: IResultOrError<string> = Git.tryGetGitEmail();
52+
if (emailResult.error) {
53+
console.log(
54+
[
55+
`Error: ${emailResult.error.message}`,
56+
'Unable to determine your Git configuration using this command:',
57+
'',
58+
' git config user.email',
59+
''
60+
].join(os.EOL)
61+
);
62+
throw new AlreadyReportedError();
5863
}
59-
}
6064

61-
public pull(): void {
62-
PublishUtilities.execCommand(!!this._targetBranch, 'git', `pull origin ${this._targetBranch}`.split(' '));
63-
}
64-
65-
public addChanges(pathspec?: string, workingDirectory?: string): void {
66-
const files: string = pathspec ? pathspec : '.';
67-
PublishUtilities.execCommand(!!this._targetBranch, 'git', ['add', files],
68-
workingDirectory ? workingDirectory : process.cwd());
69-
}
65+
if (!emailResult.result) {
66+
console.log([
67+
'Git email was not specified. Unable to continue.',
68+
'',
69+
`If you didn't configure your e-mail yet, try something like this:`,
70+
'',
71+
...GitEmailPolicy.getEmailExampleLines(rushConfiguration)
72+
].join(os.EOL));
73+
throw new AlreadyReportedError();
74+
}
7075

71-
public addTag(shouldExecute: boolean, packageName: string, packageVersion: string): void {
72-
// Tagging only happens if we're publishing to real NPM and committing to git.
73-
const tagName: string = PublishUtilities.createTagname(packageName, packageVersion);
74-
PublishUtilities.execCommand(
75-
!!this._targetBranch && shouldExecute,
76-
'git',
77-
['tag', '-a', tagName, '-m', `${packageName} v${packageVersion}`]);
76+
return emailResult.result;
7877
}
7978

80-
public commit(message?: string): void {
81-
const commitMessage: string = message ? message : 'Applying package updates.';
82-
PublishUtilities.execCommand(!!this._targetBranch, 'git', ['commit', '-m', commitMessage]);
83-
}
79+
private static tryGetGitEmail(): IResultOrError<string> {
80+
const gitPath: string | undefined = Git.getGitPath();
81+
if (!gitPath) {
82+
return {
83+
error: new Error('Git isn\'t present on the path')
84+
};
85+
}
8486

85-
public push(branchName: string | undefined): void {
86-
PublishUtilities.execCommand(
87-
!!this._targetBranch,
88-
'git',
89-
['push', 'origin', 'HEAD:' + branchName, '--follow-tags', '--verbose']);
87+
try {
88+
return {
89+
result: Utilities.executeCommandAndCaptureOutput(
90+
'git',
91+
['config', 'user.email'],
92+
'.'
93+
).trim()
94+
};
95+
} catch (e) {
96+
return {
97+
error: e
98+
};
99+
}
90100
}
91101
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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 { PublishUtilities } from './PublishUtilities';
5+
6+
export class PublishGit {
7+
private _targetBranch: string | undefined;
8+
9+
constructor(targetBranch: string | undefined) {
10+
11+
this._targetBranch = targetBranch;
12+
}
13+
14+
public checkout(branchName: string | undefined, createBranch?: boolean): void {
15+
const params: string = `checkout ${createBranch ? '-b ' : ''}${branchName}`;
16+
17+
PublishUtilities.execCommand(!!this._targetBranch, 'git', params.split(' '));
18+
}
19+
20+
public merge(branchName: string): void {
21+
PublishUtilities.execCommand(!!this._targetBranch, 'git', `merge ${branchName} --no-edit`.split(' '));
22+
}
23+
24+
public deleteBranch(branchName: string, hasRemote: boolean = true): void {
25+
PublishUtilities.execCommand(!!this._targetBranch, 'git', `branch -d ${branchName}`.split(' '));
26+
if (hasRemote) {
27+
PublishUtilities.execCommand(!!this._targetBranch, 'git', `push origin --delete ${branchName}`.split(' '));
28+
}
29+
}
30+
31+
public pull(): void {
32+
PublishUtilities.execCommand(!!this._targetBranch, 'git', `pull origin ${this._targetBranch}`.split(' '));
33+
}
34+
35+
public addChanges(pathspec?: string, workingDirectory?: string): void {
36+
const files: string = pathspec ? pathspec : '.';
37+
PublishUtilities.execCommand(!!this._targetBranch, 'git', ['add', files],
38+
workingDirectory ? workingDirectory : process.cwd());
39+
}
40+
41+
public addTag(shouldExecute: boolean, packageName: string, packageVersion: string): void {
42+
// Tagging only happens if we're publishing to real NPM and committing to git.
43+
const tagName: string = PublishUtilities.createTagname(packageName, packageVersion);
44+
PublishUtilities.execCommand(
45+
!!this._targetBranch && shouldExecute,
46+
'git',
47+
['tag', '-a', tagName, '-m', `${packageName} v${packageVersion}`]);
48+
}
49+
50+
public commit(message?: string): void {
51+
const commitMessage: string = message ? message : 'Applying package updates.';
52+
PublishUtilities.execCommand(!!this._targetBranch, 'git', ['commit', '-m', commitMessage]);
53+
}
54+
55+
public push(branchName: string | undefined): void {
56+
PublishUtilities.execCommand(
57+
!!this._targetBranch,
58+
'git',
59+
['push', 'origin', 'HEAD:' + branchName, '--follow-tags', '--verbose']);
60+
}
61+
}

0 commit comments

Comments
 (0)