@hubspot/npm-scripts 0.3.0-beta.0 → 0.3.1-beta.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/npm-scripts",
3
- "version": "0.3.0-beta.0",
3
+ "version": "0.3.1-beta.0",
4
4
  "description": "Scripts for working with npm packages in the HubSpot ecosystem",
5
5
  "author": "",
6
6
  "license": "Apache-2.0",
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,494 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { buildReleaseScript } from '../release.js';
3
+ import { exec as _exec } from 'node:child_process';
4
+ import yargs from 'yargs';
5
+ import { getCurrentGitBranch, gitCleanup } from '../utils/git.js';
6
+ import { getDistTags, publish, updateNextTag, updatePreviousTag, } from '../utils/npm.js';
7
+ import { confirm, input } from '../utils/prompting.js';
8
+ import { logger } from '../utils/logging.js';
9
+ import fs from 'fs-extra';
10
+ vi.mock('util', () => ({
11
+ promisify: vi.fn(fn => fn),
12
+ }));
13
+ vi.mock('node:child_process', () => ({
14
+ exec: vi.fn(),
15
+ execSync: vi.fn(),
16
+ }));
17
+ vi.mock('../utils/git.js', () => ({
18
+ getCurrentGitBranch: vi.fn(),
19
+ gitCleanup: vi.fn(),
20
+ }));
21
+ vi.mock('../utils/npm.js', () => ({
22
+ getDistTags: vi.fn(),
23
+ publish: vi.fn(),
24
+ updateNextTag: vi.fn(),
25
+ updatePreviousTag: vi.fn(),
26
+ }));
27
+ vi.mock('../utils/prompting.js', () => ({
28
+ confirm: vi.fn(),
29
+ input: vi.fn(),
30
+ }));
31
+ vi.mock('../utils/logging.js', () => ({
32
+ logger: {
33
+ log: vi.fn(),
34
+ error: vi.fn(),
35
+ success: vi.fn(),
36
+ },
37
+ }));
38
+ vi.mock('open', () => ({
39
+ default: vi.fn().mockResolvedValue(undefined),
40
+ }));
41
+ vi.mock('fs-extra', () => ({
42
+ default: {
43
+ readJsonSync: vi.fn(),
44
+ },
45
+ }));
46
+ vi.mock('semver', async () => await vi.importActual('semver'));
47
+ vi.mock('yargs', () => ({
48
+ default: vi.fn(),
49
+ }));
50
+ const mockedExec = vi.mocked(_exec);
51
+ const DEFAULT_PACKAGE_JSON = {
52
+ name: '@hubspot/test-package',
53
+ version: '1.0.0-beta.1',
54
+ publishConfig: { registry: 'https://registry.npmjs.org/' },
55
+ };
56
+ function setupAndGetHandler(packageJson = DEFAULT_PACKAGE_JSON, handlerOptions = {}) {
57
+ let capturedHandler;
58
+ const yargsInstance = {
59
+ scriptName: vi.fn().mockReturnThis(),
60
+ usage: vi.fn().mockReturnThis(),
61
+ command: vi.fn((_name, _desc, _builder, handler) => {
62
+ capturedHandler = handler;
63
+ return yargsInstance;
64
+ }),
65
+ version: vi.fn().mockReturnThis(),
66
+ help: vi.fn(() => yargsInstance),
67
+ argv: {},
68
+ };
69
+ vi.mocked(yargs).mockReturnValue(yargsInstance);
70
+ vi.mocked(fs.readJsonSync).mockReturnValue(packageJson);
71
+ buildReleaseScript({
72
+ packageJsonLocation: '/fake/package.json',
73
+ buildHandlerOptions: {
74
+ repositoryUrl: 'https://github.com/test/repo',
75
+ mainBranch: 'master',
76
+ ...handlerOptions,
77
+ },
78
+ });
79
+ if (!capturedHandler) {
80
+ throw new Error('yargs command handler was not captured');
81
+ }
82
+ return capturedHandler;
83
+ }
84
+ async function withExitMocked(fn) {
85
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
86
+ throw new Error('process.exit called');
87
+ });
88
+ try {
89
+ await fn();
90
+ }
91
+ catch (e) {
92
+ if (!(e instanceof Error && e.message === 'process.exit called'))
93
+ throw e;
94
+ }
95
+ finally {
96
+ exitSpy.mockRestore();
97
+ }
98
+ }
99
+ describe('release handler', () => {
100
+ beforeEach(() => {
101
+ vi.resetAllMocks();
102
+ vi.mocked(getCurrentGitBranch).mockResolvedValue('master');
103
+ vi.mocked(getDistTags).mockResolvedValue({
104
+ latest: '1.0.0',
105
+ next: '1.0.0-beta.1',
106
+ experimental: '1.0.0-experimental.1',
107
+ previous: '0.9.0',
108
+ });
109
+ vi.mocked(confirm).mockResolvedValue(true);
110
+ vi.mocked(input).mockResolvedValue('123456');
111
+ vi.mocked(publish).mockResolvedValue(undefined);
112
+ vi.mocked(updateNextTag).mockResolvedValue(undefined);
113
+ vi.mocked(updatePreviousTag).mockResolvedValue(undefined);
114
+ vi.mocked(gitCleanup).mockResolvedValue(undefined);
115
+ mockedExec.mockResolvedValue({ stdout: '', stderr: '' });
116
+ });
117
+ describe('build order', () => {
118
+ it('should run build after creating the temp branch and bumping the version', async () => {
119
+ const handler = setupAndGetHandler();
120
+ await handler({
121
+ versionIncrement: 'patch',
122
+ tag: 'next',
123
+ dryRun: false,
124
+ skipBranchValidation: false,
125
+ skipVersionCheck: false,
126
+ });
127
+ const calls = mockedExec.mock.calls.map(args => args[0]);
128
+ const buildIdx = calls.indexOf('yarn build');
129
+ const branchIdx = calls.findIndex(cmd => cmd.startsWith('git checkout -b'));
130
+ const versionIdx = calls.findIndex(cmd => cmd.startsWith('yarn version --new-version'));
131
+ expect(buildIdx).toBeGreaterThan(-1);
132
+ expect(buildIdx).toBeGreaterThan(branchIdx);
133
+ expect(buildIdx).toBeGreaterThan(versionIdx);
134
+ });
135
+ });
136
+ describe('build failure', () => {
137
+ it('should call gitCleanup with tempBranch and originalBranch when build fails on main branch', async () => {
138
+ mockedExec.mockImplementation((cmd) => {
139
+ if (cmd === 'yarn build') {
140
+ return Promise.reject(new Error('build failed'));
141
+ }
142
+ return Promise.resolve({ stdout: '', stderr: '' });
143
+ });
144
+ const handler = setupAndGetHandler();
145
+ await withExitMocked(() => handler({
146
+ versionIncrement: 'patch',
147
+ tag: 'next',
148
+ dryRun: false,
149
+ skipBranchValidation: false,
150
+ skipVersionCheck: false,
151
+ }));
152
+ // semver.inc('1.0.0-beta.1', 'prepatch', 'beta') = '1.0.1-beta.0'
153
+ expect(gitCleanup).toHaveBeenCalledWith('1.0.1-beta.0', true, 'v1.0.1-beta.0-publish', 'master');
154
+ });
155
+ it('should call gitCleanup without tempBranch when build fails on a non-main branch', async () => {
156
+ vi.mocked(getCurrentGitBranch).mockResolvedValue('feature-branch');
157
+ mockedExec.mockImplementation((cmd) => {
158
+ if (cmd === 'yarn build') {
159
+ return Promise.reject(new Error('build failed'));
160
+ }
161
+ return Promise.resolve({ stdout: '', stderr: '' });
162
+ });
163
+ const handler = setupAndGetHandler();
164
+ await withExitMocked(() => handler({
165
+ versionIncrement: 'prerelease',
166
+ tag: 'experimental',
167
+ dryRun: false,
168
+ skipBranchValidation: false,
169
+ skipVersionCheck: false,
170
+ }));
171
+ expect(gitCleanup).toHaveBeenCalledWith(expect.any(String), false, undefined, undefined);
172
+ });
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 });
176
+ await withExitMocked(() => handler({
177
+ versionIncrement: 'patch',
178
+ tag: 'next',
179
+ dryRun: false,
180
+ skipBranchValidation: false,
181
+ skipVersionCheck: false,
182
+ }));
183
+ expect(gitCleanup).toHaveBeenCalledWith('1.0.1-beta.0', true, 'v1.0.1-beta.0-publish', 'master');
184
+ });
185
+ });
186
+ describe('branch validation', () => {
187
+ it('exits with error when releasing experimental from main branch', async () => {
188
+ const handler = setupAndGetHandler();
189
+ await withExitMocked(() => handler({
190
+ versionIncrement: 'prerelease',
191
+ tag: 'experimental',
192
+ dryRun: false,
193
+ skipBranchValidation: false,
194
+ skipVersionCheck: false,
195
+ }));
196
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('experimental tag cannot be published from the master branch'));
197
+ expect(publish).not.toHaveBeenCalled();
198
+ });
199
+ it('exits with error when releasing latest/next from a non-main branch', async () => {
200
+ vi.mocked(getCurrentGitBranch).mockResolvedValue('feature-branch');
201
+ const handler = setupAndGetHandler();
202
+ await withExitMocked(() => handler({
203
+ versionIncrement: 'patch',
204
+ tag: 'next',
205
+ dryRun: false,
206
+ skipBranchValidation: false,
207
+ skipVersionCheck: false,
208
+ }));
209
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('can only be published from the master branch'));
210
+ expect(publish).not.toHaveBeenCalled();
211
+ });
212
+ it('exits with error when previous tag is used without previousBranch configured', async () => {
213
+ const handler = setupAndGetHandler();
214
+ await withExitMocked(() => handler({
215
+ versionIncrement: 'patch',
216
+ tag: 'previous',
217
+ dryRun: false,
218
+ skipBranchValidation: false,
219
+ skipVersionCheck: false,
220
+ }));
221
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('previousBranch is not configured'));
222
+ expect(publish).not.toHaveBeenCalled();
223
+ });
224
+ it('bypasses branch check when skipBranchValidation is true', async () => {
225
+ vi.mocked(getCurrentGitBranch).mockResolvedValue('feature-branch');
226
+ const handler = setupAndGetHandler();
227
+ await handler({
228
+ versionIncrement: 'patch',
229
+ tag: 'next',
230
+ dryRun: false,
231
+ skipBranchValidation: true,
232
+ skipVersionCheck: true,
233
+ });
234
+ expect(publish).toHaveBeenCalled();
235
+ });
236
+ });
237
+ describe('invalid increment/tag combinations', () => {
238
+ it('exits with error when using prerelease increment on latest tag', async () => {
239
+ const handler = setupAndGetHandler();
240
+ await withExitMocked(() => handler({
241
+ versionIncrement: 'prerelease',
242
+ tag: 'latest',
243
+ dryRun: false,
244
+ skipBranchValidation: false,
245
+ skipVersionCheck: false,
246
+ }));
247
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('cannot increment prerelease number on latest tag'));
248
+ expect(publish).not.toHaveBeenCalled();
249
+ });
250
+ });
251
+ describe('version sync check', () => {
252
+ it('exits with error when local version does not match published next tag', async () => {
253
+ vi.mocked(getDistTags).mockResolvedValue({
254
+ latest: '1.0.0',
255
+ next: '1.0.0-beta.2',
256
+ experimental: '1.0.0-experimental.1',
257
+ previous: '0.9.0',
258
+ });
259
+ const handler = setupAndGetHandler();
260
+ await withExitMocked(() => handler({
261
+ versionIncrement: 'patch',
262
+ tag: 'next',
263
+ dryRun: false,
264
+ skipBranchValidation: false,
265
+ skipVersionCheck: false,
266
+ }));
267
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('out of sync'));
268
+ expect(publish).not.toHaveBeenCalled();
269
+ });
270
+ it('bypasses version check when skipVersionCheck is true', async () => {
271
+ vi.mocked(getDistTags).mockResolvedValue({
272
+ latest: '1.0.0',
273
+ next: '1.0.0-beta.2',
274
+ experimental: '1.0.0-experimental.1',
275
+ previous: '0.9.0',
276
+ });
277
+ const handler = setupAndGetHandler();
278
+ await handler({
279
+ versionIncrement: 'patch',
280
+ tag: 'next',
281
+ dryRun: false,
282
+ skipBranchValidation: false,
283
+ skipVersionCheck: true,
284
+ });
285
+ expect(publish).toHaveBeenCalled();
286
+ });
287
+ });
288
+ describe('user cancellation', () => {
289
+ it('exits cleanly when user declines the initial confirmation', async () => {
290
+ vi.mocked(confirm).mockResolvedValue(false);
291
+ const handler = setupAndGetHandler();
292
+ await withExitMocked(() => handler({
293
+ versionIncrement: 'patch',
294
+ tag: 'next',
295
+ dryRun: false,
296
+ skipBranchValidation: false,
297
+ skipVersionCheck: false,
298
+ }));
299
+ expect(publish).not.toHaveBeenCalled();
300
+ });
301
+ it('exits cleanly when user declines the beta warning on a latest release', async () => {
302
+ // version without 'beta' in it triggers the beta warning
303
+ const handler = setupAndGetHandler({
304
+ name: '@hubspot/test-package',
305
+ version: '1.0.0',
306
+ publishConfig: { registry: 'https://registry.npmjs.org/' },
307
+ });
308
+ vi.mocked(getDistTags).mockResolvedValue({
309
+ latest: '1.0.0',
310
+ next: '1.0.0',
311
+ experimental: '1.0.0-experimental.1',
312
+ previous: '0.9.0',
313
+ });
314
+ // first confirm (proceed with release) = true, second (beta warning) = false
315
+ vi.mocked(confirm)
316
+ .mockResolvedValueOnce(true)
317
+ .mockResolvedValueOnce(false);
318
+ await withExitMocked(() => handler({
319
+ versionIncrement: 'patch',
320
+ tag: 'latest',
321
+ dryRun: false,
322
+ skipBranchValidation: false,
323
+ skipVersionCheck: false,
324
+ }));
325
+ expect(publish).not.toHaveBeenCalled();
326
+ });
327
+ });
328
+ describe('dry run', () => {
329
+ it('calls gitCleanup to revert the version bump', async () => {
330
+ const handler = setupAndGetHandler();
331
+ await withExitMocked(() => handler({
332
+ versionIncrement: 'patch',
333
+ tag: 'next',
334
+ dryRun: true,
335
+ skipBranchValidation: false,
336
+ skipVersionCheck: false,
337
+ }));
338
+ // semver.inc('1.0.0-beta.1', 'prepatch', 'beta') = '1.0.1-beta.0'
339
+ expect(gitCleanup).toHaveBeenCalledWith('1.0.1-beta.0', true);
340
+ });
341
+ it('does not create a temp branch', async () => {
342
+ const handler = setupAndGetHandler();
343
+ await withExitMocked(() => handler({
344
+ versionIncrement: 'patch',
345
+ tag: 'next',
346
+ dryRun: true,
347
+ skipBranchValidation: false,
348
+ skipVersionCheck: false,
349
+ }));
350
+ expect(mockedExec).not.toHaveBeenCalledWith(expect.stringContaining('git checkout -b'));
351
+ });
352
+ });
353
+ describe('publish failure', () => {
354
+ it('calls gitCleanup with tempBranch and original branch when publish fails from main', async () => {
355
+ const handler = setupAndGetHandler();
356
+ vi.mocked(publish).mockRejectedValue(new Error('publish failed'));
357
+ await withExitMocked(() => handler({
358
+ versionIncrement: 'patch',
359
+ tag: 'next',
360
+ dryRun: false,
361
+ skipBranchValidation: false,
362
+ skipVersionCheck: false,
363
+ }));
364
+ // semver.inc('1.0.0-beta.1', 'prepatch', 'beta') = '1.0.1-beta.0'
365
+ expect(gitCleanup).toHaveBeenCalledWith('1.0.1-beta.0', true, 'v1.0.1-beta.0-publish', 'master');
366
+ });
367
+ it('calls gitCleanup without tempBranch when publish fails on a non-main branch', async () => {
368
+ vi.mocked(getCurrentGitBranch).mockResolvedValue('feature-branch');
369
+ vi.mocked(publish).mockRejectedValue(new Error('publish failed'));
370
+ const handler = setupAndGetHandler();
371
+ await withExitMocked(() => handler({
372
+ versionIncrement: 'prerelease',
373
+ tag: 'experimental',
374
+ dryRun: false,
375
+ skipBranchValidation: false,
376
+ skipVersionCheck: false,
377
+ }));
378
+ expect(gitCleanup).toHaveBeenCalledWith(expect.any(String), false, undefined, undefined);
379
+ });
380
+ });
381
+ describe('latest release', () => {
382
+ it('calls updateNextTag after a successful latest release', async () => {
383
+ const handler = setupAndGetHandler();
384
+ await handler({
385
+ versionIncrement: 'patch',
386
+ tag: 'latest',
387
+ dryRun: false,
388
+ skipBranchValidation: false,
389
+ skipVersionCheck: true,
390
+ });
391
+ expect(updateNextTag).toHaveBeenCalledWith('@hubspot/test-package', expect.any(String), '123456', false, 'https://registry.npmjs.org/');
392
+ });
393
+ it('calls updatePreviousTag on a major latest release', async () => {
394
+ const handler = setupAndGetHandler();
395
+ await handler({
396
+ versionIncrement: 'major',
397
+ tag: 'latest',
398
+ dryRun: false,
399
+ skipBranchValidation: false,
400
+ skipVersionCheck: true,
401
+ });
402
+ expect(updatePreviousTag).toHaveBeenCalledWith('@hubspot/test-package', '1.0.0', // currentLatestTag from getDistTags mock
403
+ '123456', false, 'https://registry.npmjs.org/');
404
+ });
405
+ it('does not call updatePreviousTag on a non-major latest release', async () => {
406
+ const handler = setupAndGetHandler();
407
+ await handler({
408
+ versionIncrement: 'patch',
409
+ tag: 'latest',
410
+ dryRun: false,
411
+ skipBranchValidation: false,
412
+ skipVersionCheck: true,
413
+ });
414
+ expect(updatePreviousTag).not.toHaveBeenCalled();
415
+ });
416
+ it('logs an error but continues the release when updateNextTag fails', async () => {
417
+ vi.mocked(updateNextTag).mockRejectedValue(new Error('dist-tag failed'));
418
+ const handler = setupAndGetHandler();
419
+ await handler({
420
+ versionIncrement: 'patch',
421
+ tag: 'latest',
422
+ dryRun: false,
423
+ skipBranchValidation: false,
424
+ skipVersionCheck: true,
425
+ });
426
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining(`updating the next tag`));
427
+ // git push still happened
428
+ const calls = mockedExec.mock.calls.map(args => args[0]);
429
+ expect(calls.some(cmd => cmd.startsWith('git push'))).toBe(true);
430
+ });
431
+ it('invokes postLatestRelease hook with newVersion and dryRun', async () => {
432
+ const postLatestRelease = vi.fn().mockResolvedValue(undefined);
433
+ const handler = setupAndGetHandler(DEFAULT_PACKAGE_JSON, {
434
+ postLatestRelease,
435
+ });
436
+ await handler({
437
+ versionIncrement: 'patch',
438
+ tag: 'latest',
439
+ dryRun: false,
440
+ skipBranchValidation: false,
441
+ skipVersionCheck: true,
442
+ });
443
+ expect(postLatestRelease).toHaveBeenCalledWith({
444
+ newVersion: expect.any(String),
445
+ dryRun: false,
446
+ });
447
+ });
448
+ });
449
+ describe('experimental release', () => {
450
+ it('does not create a temp branch or git commit/tag', async () => {
451
+ vi.mocked(getCurrentGitBranch).mockResolvedValue('feature-branch');
452
+ const handler = setupAndGetHandler();
453
+ await handler({
454
+ versionIncrement: 'prerelease',
455
+ tag: 'experimental',
456
+ dryRun: false,
457
+ skipBranchValidation: false,
458
+ skipVersionCheck: false,
459
+ });
460
+ expect(mockedExec).not.toHaveBeenCalledWith(expect.stringContaining('git checkout -b'));
461
+ expect(mockedExec).not.toHaveBeenCalledWith(expect.stringContaining('git commit'));
462
+ expect(mockedExec).not.toHaveBeenCalledWith(expect.stringContaining('git tag v'));
463
+ });
464
+ it('resets package.json version back to localVersion after a successful publish', async () => {
465
+ vi.mocked(getCurrentGitBranch).mockResolvedValue('feature-branch');
466
+ const handler = setupAndGetHandler();
467
+ await handler({
468
+ versionIncrement: 'prerelease',
469
+ tag: 'experimental',
470
+ dryRun: false,
471
+ skipBranchValidation: false,
472
+ skipVersionCheck: false,
473
+ });
474
+ expect(mockedExec).toHaveBeenCalledWith('yarn version --no-git-tag-version --new-version 1.0.0-beta.1');
475
+ });
476
+ });
477
+ describe('custom build function', () => {
478
+ it('calls the provided build function instead of running yarn build', async () => {
479
+ const buildFn = vi.fn().mockResolvedValue(undefined);
480
+ const handler = setupAndGetHandler(DEFAULT_PACKAGE_JSON, {
481
+ build: buildFn,
482
+ });
483
+ await handler({
484
+ versionIncrement: 'patch',
485
+ tag: 'next',
486
+ dryRun: false,
487
+ skipBranchValidation: false,
488
+ skipVersionCheck: false,
489
+ });
490
+ expect(buildFn).toHaveBeenCalledOnce();
491
+ expect(mockedExec).not.toHaveBeenCalledWith('yarn build');
492
+ });
493
+ });
494
+ });
package/src/release.js CHANGED
@@ -7,7 +7,7 @@ import fs from 'fs-extra';
7
7
  import { logger } from './utils/logging.js';
8
8
  import { EXIT_CODES } from './utils/process.js';
9
9
  import { DEFAULT_MAIN_BRANCH, INCREMENT, PRERELEASE_IDENTIFIER, TAG, TAG_OPTIONS, VERSION_INCREMENT_OPTIONS, } from './constants/release.js';
10
- import { gitCleanup, getCurrentGitBranch } from './utils/git.js';
10
+ import { getCurrentGitBranch, gitCleanup } from './utils/git.js';
11
11
  import { getDistTags, publish, updateNextTag, updatePreviousTag, } from './utils/npm.js';
12
12
  import { confirm, input } from './utils/prompting.js';
13
13
  const exec = promisify(_exec);
@@ -80,10 +80,6 @@ function buildHandler({ build, postLatestRelease, packageName, localVersion, reg
80
80
  if (!shouldRelease) {
81
81
  process.exit(EXIT_CODES.SUCCESS);
82
82
  }
83
- if ((branch === mainBranch || branch === previousBranch) && !dryRun) {
84
- logger.log(`Creating a temporary branch '${tempBranch}' for the release`);
85
- await exec(`git checkout -b ${tempBranch}`);
86
- }
87
83
  if (tag === TAG.LATEST &&
88
84
  !localVersion.includes(PRERELEASE_IDENTIFIER.NEXT)) {
89
85
  const proceedWithoutBetaRelease = await confirm({
@@ -95,6 +91,11 @@ function buildHandler({ build, postLatestRelease, packageName, localVersion, reg
95
91
  process.exit(EXIT_CODES.SUCCESS);
96
92
  }
97
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;
98
99
  logger.log(`\nUpdating version to ${newVersion}...`);
99
100
  if (isExperimental) {
100
101
  await exec(`yarn version --no-git-tag-version --new-version ${newVersion}`);
@@ -103,14 +104,22 @@ function buildHandler({ build, postLatestRelease, packageName, localVersion, reg
103
104
  await exec(`yarn version --new-version ${newVersion}`);
104
105
  }
105
106
  logger.success('Version updated successfully \n');
106
- if (build && typeof build === 'function') {
107
- await build();
107
+ 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
+ }
108
117
  }
109
- else {
110
- logger.log('Installing dependencies...');
111
- await exec('yarn');
112
- logger.log('Building...');
113
- await exec(`yarn build`);
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);
114
123
  }
115
124
  let otp = '';
116
125
  if (!isDryRun) {
@@ -139,7 +148,7 @@ function buildHandler({ build, postLatestRelease, packageName, localVersion, reg
139
148
  catch (e) {
140
149
  logger.error(e);
141
150
  logger.error('An error occurred while releasing this package. Correct the error and re-run `yarn build`.');
142
- await gitCleanup(newVersion, !isExperimental);
151
+ await gitCleanup(newVersion, !isExperimental, onTempBranch ? tempBranch : undefined, onTempBranch ? branch : undefined);
143
152
  process.exit(EXIT_CODES.ERROR);
144
153
  }
145
154
  const gitCommand = `git push --atomic origin ${tempBranch} v${newVersion}`;
@@ -56,20 +56,45 @@ describe('git', () => {
56
56
  });
57
57
  });
58
58
  describe('gitCleanup', () => {
59
- it('should reset HEAD and checkout files', async () => {
59
+ it('should only checkout files when deleteTag is false', async () => {
60
60
  mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
61
61
  await gitCleanup('1.0.0', false);
62
- expect(mockedExec).toHaveBeenCalledWith('git reset HEAD~');
63
62
  expect(mockedExec).toHaveBeenCalledWith('git checkout .');
63
+ expect(mockedExec).not.toHaveBeenCalledWith('git reset HEAD~');
64
64
  expect(mockedExec).not.toHaveBeenCalledWith(expect.stringContaining('git tag -d'));
65
65
  });
66
- it('should delete tag when deleteTag is true', async () => {
66
+ it('should reset HEAD, checkout files, and delete tag when deleteTag is true', async () => {
67
67
  mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
68
68
  await gitCleanup('1.0.0', true);
69
69
  expect(mockedExec).toHaveBeenCalledWith('git reset HEAD~');
70
70
  expect(mockedExec).toHaveBeenCalledWith('git checkout .');
71
71
  expect(mockedExec).toHaveBeenCalledWith('git tag -d v1.0.0');
72
72
  });
73
+ it('should checkout originalBranch and delete tempBranch when both are provided', async () => {
74
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
75
+ await gitCleanup('1.0.0', true, 'v1.0.0-publish', 'master');
76
+ expect(mockedExec).toHaveBeenCalledWith('git reset HEAD~');
77
+ expect(mockedExec).toHaveBeenCalledWith('git checkout .');
78
+ expect(mockedExec).toHaveBeenCalledWith('git tag -d v1.0.0');
79
+ expect(mockedExec).toHaveBeenCalledWith('git checkout master');
80
+ expect(mockedExec).toHaveBeenCalledWith('git branch -D v1.0.0-publish');
81
+ });
82
+ it('should not perform branch cleanup or reset when deleteTag is false and no branches provided', async () => {
83
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
84
+ await gitCleanup('1.0.0', false);
85
+ expect(mockedExec).not.toHaveBeenCalledWith('git reset HEAD~');
86
+ expect(mockedExec).not.toHaveBeenCalledWith(expect.stringContaining('git checkout master'));
87
+ expect(mockedExec).not.toHaveBeenCalledWith(expect.stringContaining('git branch -D'));
88
+ });
89
+ it('should log an error and continue if branch cleanup fails', async () => {
90
+ mockedExec
91
+ .mockResolvedValueOnce({ stdout: '', stderr: '' })
92
+ .mockResolvedValueOnce({ stdout: '', stderr: '' })
93
+ .mockResolvedValueOnce({ stdout: '', stderr: '' })
94
+ .mockRejectedValueOnce(new Error('checkout failed'));
95
+ await gitCleanup('1.0.0', true, 'v1.0.0-publish', 'master');
96
+ expect(vi.mocked(logger.error)).toHaveBeenCalledWith(expect.stringContaining("'v1.0.0-publish'"));
97
+ });
73
98
  });
74
99
  describe('getGitEnvWithSshKey', () => {
75
100
  it('should return process.env when sshKeyPath is not provided and user leaves blank', async () => {
@@ -1,5 +1,5 @@
1
1
  export declare function getCurrentGitBranch(): Promise<string>;
2
- export declare function gitCleanup(newVersion: string, deleteTag: boolean): Promise<void>;
2
+ export declare function gitCleanup(newVersion: string, deleteTag: boolean, tempBranch?: string, originalBranch?: string): Promise<void>;
3
3
  export declare function getGitEnvWithSshKey(sshKeyPath?: string): Promise<typeof process.env | undefined>;
4
4
  export declare function cloneRepo(repoUrl: string, destinationDir: string, gitEnvironment?: typeof process.env): Promise<string>;
5
5
  export declare function checkoutBranch(branchName: string, pullLatest?: boolean): Promise<void>;
package/src/utils/git.js CHANGED
@@ -16,12 +16,21 @@ export async function getCurrentGitBranch() {
16
16
  const { stdout } = await exec('git rev-parse --abbrev-ref HEAD');
17
17
  return stdout.trim();
18
18
  }
19
- export async function gitCleanup(newVersion, deleteTag) {
20
- await exec(`git reset HEAD~`);
21
- await exec(`git checkout .`);
19
+ export async function gitCleanup(newVersion, deleteTag, tempBranch, originalBranch) {
22
20
  if (deleteTag) {
21
+ await exec(`git reset HEAD~`);
23
22
  await exec(`git tag -d v${newVersion}`);
24
23
  }
24
+ await exec(`git checkout .`);
25
+ if (tempBranch && originalBranch) {
26
+ try {
27
+ await exec(`git checkout ${originalBranch}`);
28
+ await exec(`git branch -D ${tempBranch}`);
29
+ }
30
+ catch (e) {
31
+ logger.error(`Failed to clean up temporary branch '${tempBranch}'. You may need to delete it manually with: git branch -D ${tempBranch}`);
32
+ }
33
+ }
25
34
  }
26
35
  export async function getGitEnvWithSshKey(sshKeyPath) {
27
36
  if (!sshKeyPath) {