@hubspot/npm-scripts 0.3.2 → 0.3.3-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # @hubspot/npm-scripts
2
2
 
3
+ ![npm version](https://img.shields.io/npm/v/@hubspot/npm-scripts)
4
+ ![npm downloads](https://img.shields.io/npm/dm/@hubspot/npm-scripts)
5
+ ![npm license](https://img.shields.io/npm/l/@hubspot/npm-scripts)
6
+ ![node version](https://img.shields.io/node/v/@hubspot/npm-scripts)
7
+
3
8
  **A collection of scripts for internal HubSpot npm package development and management.**
4
9
 
5
10
  ## Tools
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/npm-scripts",
3
- "version": "0.3.2",
3
+ "version": "0.3.3-beta.1",
4
4
  "description": "Scripts for working with npm packages in the HubSpot ecosystem",
5
5
  "author": "",
6
6
  "license": "Apache-2.0",
@@ -43,7 +43,7 @@ vi.mock('fs-extra', () => ({
43
43
  readJsonSync: vi.fn(),
44
44
  },
45
45
  }));
46
- vi.mock('semver', async () => await vi.importActual('semver'));
46
+ vi.mock('semver', async () => vi.importActual('semver'));
47
47
  vi.mock('yargs', () => ({
48
48
  default: vi.fn(),
49
49
  }));
@@ -171,8 +171,12 @@ describe('release handler', () => {
171
171
  expect(gitCleanup).toHaveBeenCalledWith(expect.any(String), false, undefined, undefined);
172
172
  });
173
173
  it('should call gitCleanup when the custom build function throws', async () => {
174
- const buildFn = vi.fn().mockRejectedValue(new Error('custom build failed'));
175
- const handler = setupAndGetHandler(DEFAULT_PACKAGE_JSON, { build: buildFn });
174
+ const buildFn = vi
175
+ .fn()
176
+ .mockRejectedValue(new Error('custom build failed'));
177
+ const handler = setupAndGetHandler(DEFAULT_PACKAGE_JSON, {
178
+ build: buildFn,
179
+ });
176
180
  await withExitMocked(() => handler({
177
181
  versionIncrement: 'patch',
178
182
  tag: 'next',
package/src/release.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BuildReleaseScriptBase } from './types.js';
1
+ import type { BuildReleaseScriptBase } from './types.js';
2
2
  export declare function buildReleaseScript({ packageJsonLocation, buildHandlerOptions, }: {
3
3
  packageJsonLocation: string;
4
4
  buildHandlerOptions: BuildReleaseScriptBase;
package/src/release.js CHANGED
@@ -1,197 +1,129 @@
1
- import { exec as _exec, execSync } from 'node:child_process';
2
- import { promisify } from 'util';
3
1
  import yargs from 'yargs';
4
- import semver from 'semver';
5
- import open from 'open';
6
2
  import fs from 'fs-extra';
7
3
  import { logger } from './utils/logging.js';
8
4
  import { EXIT_CODES } from './utils/process.js';
9
- import { DEFAULT_MAIN_BRANCH, INCREMENT, PRERELEASE_IDENTIFIER, TAG, TAG_OPTIONS, VERSION_INCREMENT_OPTIONS, } from './constants/release.js';
10
- import { getCurrentGitBranch, gitCleanup } from './utils/git.js';
11
- import { getDistTags, publish, updateNextTag, updatePreviousTag, } from './utils/npm.js';
12
- import { confirm } from './utils/prompting.js';
13
- const exec = promisify(_exec);
5
+ import { DEFAULT_MAIN_BRANCH, TAG, TAG_OPTIONS, VERSION_INCREMENT_OPTIONS, } from './constants/release.js';
6
+ import { getCurrentGitBranch } from './utils/git.js';
7
+ import { getDistTags } from './utils/npm.js';
8
+ import { ReleaseError } from './utils/release/errors.js';
9
+ import { validatePreviousBranchConfigured, validateBranchForTag, validateTagIncrementCombination, validateVersionSync, validateNextReleaseIsNotOverIncrement, } from './utils/release/validate.js';
10
+ import { computeNewVersion } from './utils/release/version.js';
11
+ import { confirmRelease, createTempBranch, bumpVersion, tryBuild, ensureNpmAuth, tryPublish, updateDistTagsForLatest, finalizeRelease, logReleaseSuccess, } from './utils/release/steps.js';
14
12
  function buildHandler({ build, postLatestRelease, packageName, localVersion, registry, repositoryUrl, mainBranch, previousBranch, ignoreScripts, }) {
15
13
  return async function handler({ versionIncrement, tag, dryRun, skipBranchValidation, skipVersionCheck, }) {
16
- const branch = await getCurrentGitBranch();
17
- const isExperimental = tag === TAG.EXPERIMENTAL;
18
- const isPrevious = tag === TAG.PREVIOUS;
19
- const isDryRun = Boolean(dryRun);
20
- if (isPrevious && !previousBranch) {
21
- logger.error('Cannot release to previous tag: previousBranch is not configured');
22
- process.exit(EXIT_CODES.ERROR);
23
- }
24
- if (!skipBranchValidation) {
25
- if (isExperimental &&
26
- (branch === mainBranch || branch === previousBranch)) {
27
- logger.error(`Releases to experimental tag cannot be published from the ${branch} branch`);
28
- process.exit(EXIT_CODES.ERROR);
29
- }
30
- else if (isPrevious && branch !== previousBranch) {
31
- logger.error(`Releases to previous tag can only be published from the ${previousBranch} branch`);
32
- process.exit(EXIT_CODES.ERROR);
33
- }
34
- else if (!isExperimental && !isPrevious && branch !== mainBranch) {
35
- logger.error(`Releases to latest and next tags can only be published from the ${mainBranch} branch`);
36
- process.exit(EXIT_CODES.ERROR);
37
- }
38
- }
39
- if ((tag === TAG.LATEST || tag === TAG.PREVIOUS) &&
40
- versionIncrement === INCREMENT.PRERELEASE) {
41
- logger.error(`Invalid release: cannot increment prerelease number on ${tag} tag.`);
42
- process.exit(EXIT_CODES.ERROR);
43
- }
44
- const { latest: currentLatestTag, next: currentNextTag, experimental: currentExperimentalTag, previous: currentPreviousTag, } = await getDistTags(packageName);
45
- if (!skipVersionCheck) {
46
- if (!isExperimental && !isPrevious && currentNextTag !== localVersion) {
47
- logger.error(`Local package.json version ${localVersion} is out of sync with published version ${currentNextTag}`);
48
- process.exit(EXIT_CODES.ERROR);
49
- }
50
- if (isPrevious && currentPreviousTag !== localVersion) {
51
- logger.error(`Local package.json version ${localVersion} is out of sync with published version ${currentPreviousTag}`);
52
- process.exit(EXIT_CODES.ERROR);
53
- }
54
- }
55
- const currentVersion = isExperimental
56
- ? currentExperimentalTag
57
- : localVersion;
58
- const prereleaseIdentifier = isExperimental
59
- ? PRERELEASE_IDENTIFIER.EXPERIMENTAL
60
- : PRERELEASE_IDENTIFIER.NEXT;
61
- const incrementType = tag === TAG.LATEST ||
62
- tag === TAG.PREVIOUS ||
63
- versionIncrement === INCREMENT.PRERELEASE
64
- ? versionIncrement
65
- : `pre${versionIncrement}`;
66
- const newVersion = semver.inc(currentVersion, incrementType, prereleaseIdentifier);
67
- const tempBranch = `v${newVersion}-publish`;
68
- if (!newVersion) {
69
- logger.error('Error incrementing version.');
70
- process.exit(EXIT_CODES.ERROR);
71
- }
72
- if (dryRun) {
73
- logger.log('\nDRY RUN');
74
- }
75
- logger.log(`\nCurrent version: ${currentVersion}`);
76
- logger.log(`New version to release: ${newVersion}`);
77
- const shouldRelease = await confirm({
78
- message: `Release version ${newVersion} on tag ${tag}?`,
79
- });
80
- if (!shouldRelease) {
81
- process.exit(EXIT_CODES.SUCCESS);
82
- }
83
- if (tag === TAG.LATEST &&
84
- !localVersion.includes(PRERELEASE_IDENTIFIER.NEXT)) {
85
- const proceedWithoutBetaRelease = await confirm({
86
- message: `The current changes have not yet been released in beta. It's recommended to release and test all changes on the ${TAG.NEXT} tag before releasing them to ${TAG.LATEST}. Are you sure you want to proceed?`,
87
- default: false,
88
- });
89
- if (!proceedWithoutBetaRelease) {
90
- logger.log(`\nTo release your changes on the next tag, run \`yarn release -v=${versionIncrement} -t=next\``);
91
- process.exit(EXIT_CODES.SUCCESS);
92
- }
93
- }
94
- if ((branch === mainBranch || branch === previousBranch) && !dryRun) {
95
- logger.log(`Creating a temporary branch '${tempBranch}' for the release`);
96
- await exec(`git checkout -b ${tempBranch}`);
97
- }
98
- const onTempBranch = (branch === mainBranch || branch === previousBranch) && !isDryRun;
99
- logger.log(`\nUpdating version to ${newVersion}...`);
100
- if (isExperimental) {
101
- await exec(`yarn version --no-git-tag-version --new-version ${newVersion}`);
102
- }
103
- else {
104
- await exec(`yarn version --new-version ${newVersion}`);
105
- }
106
- logger.success('Version updated successfully \n');
107
14
  try {
108
- if (build && typeof build === 'function') {
109
- await build();
110
- }
111
- else {
112
- logger.log('Installing dependencies...');
113
- await exec('yarn');
114
- logger.log('Building...');
115
- await exec(`yarn build`);
116
- }
117
- }
118
- catch (e) {
119
- logger.error(e);
120
- logger.error('Build failed. Cleaning up...');
121
- await gitCleanup(newVersion, !isExperimental, onTempBranch ? tempBranch : undefined, onTempBranch ? branch : undefined);
122
- process.exit(EXIT_CODES.ERROR);
123
- }
124
- if (!isDryRun) {
125
- try {
126
- await exec(`npm whoami --registry ${registry}`);
15
+ const branch = await getCurrentGitBranch();
16
+ const isExperimental = tag === TAG.EXPERIMENTAL;
17
+ const isPrevious = tag === TAG.PREVIOUS;
18
+ const isDryRun = Boolean(dryRun);
19
+ const resolvedMainBranch = mainBranch ?? DEFAULT_MAIN_BRANCH;
20
+ validatePreviousBranchConfigured(isPrevious, previousBranch);
21
+ if (!skipBranchValidation) {
22
+ validateBranchForTag({
23
+ isExperimental,
24
+ isPrevious,
25
+ branch,
26
+ mainBranch: resolvedMainBranch,
27
+ previousBranch,
28
+ });
127
29
  }
128
- catch (err) {
129
- try {
130
- execSync(`npm adduser --registry ${registry}`, { stdio: 'inherit' });
131
- }
132
- catch (authErr) {
133
- logger.error('Failed to authenticate with npm');
134
- process.exit(EXIT_CODES.ERROR);
135
- }
30
+ validateTagIncrementCombination(tag, versionIncrement);
31
+ const distTags = await getDistTags(packageName);
32
+ if (!skipVersionCheck) {
33
+ validateVersionSync({
34
+ isExperimental,
35
+ isPrevious,
36
+ localVersion,
37
+ distTags,
38
+ });
136
39
  }
137
- }
138
- try {
139
- await publish(tag, isDryRun, ignoreScripts || false, registry);
40
+ validateNextReleaseIsNotOverIncrement({
41
+ tag,
42
+ versionIncrement,
43
+ localVersion,
44
+ distTags,
45
+ });
46
+ const newVersion = computeNewVersion({
47
+ tag,
48
+ versionIncrement,
49
+ isExperimental,
50
+ distTags,
51
+ localVersion,
52
+ });
53
+ const tempBranch = `v${newVersion}-publish`;
54
+ const currentVersion = isExperimental
55
+ ? distTags.experimental
56
+ : localVersion;
57
+ const onTempBranch = (branch === resolvedMainBranch || branch === previousBranch) &&
58
+ !isDryRun;
59
+ await confirmRelease({
60
+ isDryRun,
61
+ currentVersion,
62
+ newVersion,
63
+ tag,
64
+ localVersion,
65
+ versionIncrement,
66
+ });
67
+ await createTempBranch(branch, resolvedMainBranch, previousBranch, isDryRun, tempBranch);
68
+ await bumpVersion(newVersion, isExperimental);
69
+ await tryBuild({
70
+ build,
71
+ newVersion,
72
+ isExperimental,
73
+ onTempBranch,
74
+ tempBranch,
75
+ originalBranch: branch,
76
+ });
77
+ await ensureNpmAuth(isDryRun, registry);
78
+ await tryPublish({
79
+ tag,
80
+ isDryRun,
81
+ ignoreScripts: ignoreScripts || false,
82
+ registry,
83
+ newVersion,
84
+ isExperimental,
85
+ onTempBranch,
86
+ tempBranch,
87
+ originalBranch: branch,
88
+ });
89
+ await updateDistTagsForLatest({
90
+ tag,
91
+ versionIncrement,
92
+ packageName,
93
+ newVersion,
94
+ currentLatestTag: distTags.latest,
95
+ isDryRun,
96
+ registry,
97
+ tempBranch,
98
+ });
99
+ await finalizeRelease({
100
+ isDryRun,
101
+ isExperimental,
102
+ newVersion,
103
+ localVersion,
104
+ tempBranch,
105
+ isPrevious,
106
+ previousBranch,
107
+ mainBranch: resolvedMainBranch,
108
+ repositoryUrl,
109
+ });
110
+ await logReleaseSuccess({
111
+ packageName,
112
+ newVersion,
113
+ tag,
114
+ repositoryUrl,
115
+ isDryRun,
116
+ postLatestRelease,
117
+ });
140
118
  }
141
119
  catch (e) {
142
- logger.error(e);
143
- logger.error('An error occurred while releasing this package. Correct the error and re-run `yarn build`.');
144
- await gitCleanup(newVersion, !isExperimental, onTempBranch ? tempBranch : undefined, onTempBranch ? branch : undefined);
145
- process.exit(EXIT_CODES.ERROR);
146
- }
147
- const gitCommand = `git push --atomic origin ${tempBranch} v${newVersion}`;
148
- if (tag === TAG.LATEST) {
149
- try {
150
- await updateNextTag(packageName, newVersion, isDryRun, registry);
151
- }
152
- catch (e) {
153
- logger.error(`An error occurred while updating the ${TAG.NEXT} tag. To finish this release, run the following commands:`);
154
- logger.log(`npm dist-tag add ${packageName}@${newVersion} ${TAG.NEXT}`);
155
- logger.log(gitCommand);
156
- }
157
- if (versionIncrement === INCREMENT.MAJOR) {
158
- try {
159
- await updatePreviousTag(packageName, currentLatestTag, isDryRun, registry);
160
- }
161
- catch (e) {
162
- logger.error(`An error occurred while updating the ${TAG.PREVIOUS} tag. To finish this release, run the following command:`);
163
- logger.log(`npm dist-tag add ${packageName}@${currentLatestTag} ${TAG.PREVIOUS}`);
120
+ if (e instanceof ReleaseError) {
121
+ if (e.message) {
122
+ logger.error(e.message);
164
123
  }
124
+ process.exit(e.exitCode);
165
125
  }
166
- }
167
- if (isDryRun) {
168
- await gitCleanup(newVersion, !isExperimental);
169
- logger.log(`\nDry run: skipping push to Github`);
170
- logger.log('Dry run release finished successfully');
171
- process.exit(EXIT_CODES.SUCCESS);
172
- }
173
- if (isExperimental) {
174
- logger.log(`\nExperimental release: Skipping push to Github`);
175
- // Reset the version back to the local version
176
- await exec(`yarn version --no-git-tag-version --new-version ${localVersion}`);
177
- }
178
- else {
179
- logger.log(`\nPushing changes to Github...`);
180
- await exec(gitCommand);
181
- logger.log(`Changes pushed successfully`);
182
- const baseBranch = isPrevious ? previousBranch : mainBranch;
183
- await open(`${repositoryUrl}/compare/${baseBranch}...${tempBranch}`);
184
- }
185
- logger.success(`${packageName} version ${newVersion} published successfully`);
186
- logger.log(`https://www.npmjs.com/package/${packageName}?activeTab=versions`);
187
- if (tag === TAG.LATEST || tag === TAG.PREVIOUS) {
188
- logger.log(`\nRemember to create a new release on Github!`);
189
- await open(`${repositoryUrl}/releases/new`);
190
- if (tag === TAG.LATEST &&
191
- postLatestRelease &&
192
- typeof postLatestRelease === 'function') {
193
- await postLatestRelease({ newVersion, dryRun });
194
- }
126
+ throw e;
195
127
  }
196
128
  };
197
129
  }
@@ -69,7 +69,13 @@ describe('npm', () => {
69
69
  };
70
70
  mockedSpawn.mockImplementation(() => mockChildProcess);
71
71
  await publish(TAG.LATEST, false, false, 'https://registry.npmjs.org/');
72
- expect(mockedSpawn).toHaveBeenCalledWith('npm', ['publish', '--tag', TAG.LATEST, '--registry', 'https://registry.npmjs.org/'], {
72
+ expect(mockedSpawn).toHaveBeenCalledWith('npm', [
73
+ 'publish',
74
+ '--tag',
75
+ TAG.LATEST,
76
+ '--registry',
77
+ 'https://registry.npmjs.org/',
78
+ ], {
73
79
  stdio: 'inherit',
74
80
  cwd: './dist',
75
81
  });
@@ -0,0 +1 @@
1
+ export {};