@hubspot/npm-scripts 0.3.3 → 0.3.4-experimental.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.
@@ -1,19 +1,24 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { exec as _exec, execSync } from 'node:child_process';
2
+ import { exec as _exec, execFile as _execFile, execSync, } from 'node:child_process';
3
3
  import open from 'open';
4
+ import fs from 'fs-extra';
4
5
  import { logger } from '../../../utils/logging.js';
5
6
  import { EXIT_CODES } from '../../../utils/process.js';
6
7
  import { gitCleanup } from '../../../utils/git.js';
7
8
  import { publish, updateNextTag, updatePreviousTag, } from '../../../utils/npm.js';
8
- import { confirm } from '../../../utils/prompting.js';
9
+ import { confirm, select } from '../../../utils/prompting.js';
9
10
  import { TAG, INCREMENT } from '../../../constants/release.js';
10
- import { confirmRelease, runBuild, tryBuild, createTempBranch, bumpVersion, ensureNpmAuth, tryPublish, updateDistTagsForLatest, finalizeRelease, logReleaseSuccess, } from '../steps.js';
11
+ import { confirmRelease, runBuild, tryBuild, createTempBranch, bumpVersion, ensureNpmAuth, tryPublish, updateDistTagsForLatest, finalizeRelease, logReleaseSuccess, ensureCleanWorkingTree, ensureGhCli, ensureBranchPushed, findWorkflowRun, openReleasePr, resolveVersionIncrement, runExperimentalWorkflow, } from '../steps.js';
11
12
  import { ReleaseError } from '../errors.js';
12
13
  vi.mock('util', () => ({ promisify: vi.fn(fn => fn) }));
13
- vi.mock('node:child_process', () => ({ exec: vi.fn(), execSync: vi.fn() }));
14
+ vi.mock('node:child_process', () => ({
15
+ exec: vi.fn(),
16
+ execFile: vi.fn(),
17
+ execSync: vi.fn(),
18
+ }));
14
19
  vi.mock('open', () => ({ default: vi.fn().mockResolvedValue(undefined) }));
15
20
  vi.mock('../../../utils/logging.js', () => ({
16
- logger: { log: vi.fn(), error: vi.fn(), success: vi.fn() },
21
+ logger: { log: vi.fn(), error: vi.fn(), success: vi.fn(), warn: vi.fn() },
17
22
  }));
18
23
  vi.mock('../../../utils/process.js', () => ({
19
24
  EXIT_CODES: { SUCCESS: 0, ERROR: 1 },
@@ -24,8 +29,15 @@ vi.mock('../../../utils/npm.js', () => ({
24
29
  updateNextTag: vi.fn(),
25
30
  updatePreviousTag: vi.fn(),
26
31
  }));
27
- vi.mock('../../../utils/prompting.js', () => ({ confirm: vi.fn() }));
32
+ vi.mock('../../../utils/prompting.js', () => ({
33
+ confirm: vi.fn(),
34
+ select: vi.fn(),
35
+ }));
36
+ vi.mock('fs-extra', () => ({
37
+ default: { mkdtemp: vi.fn(), readFile: vi.fn(), remove: vi.fn() },
38
+ }));
28
39
  const mockedExec = vi.mocked(_exec);
40
+ const mockedExecFile = vi.mocked(_execFile);
29
41
  const mockedExecSync = vi.mocked(execSync);
30
42
  const mockedGitCleanup = vi.mocked(gitCleanup);
31
43
  const mockedPublish = vi.mocked(publish);
@@ -56,6 +68,30 @@ describe('release/steps', () => {
56
68
  });
57
69
  expect(logger.log).toHaveBeenCalledWith('\nDRY RUN');
58
70
  });
71
+ it('should label the current version with currentVersionLabel when given', async () => {
72
+ await confirmRelease({
73
+ isDryRun: false,
74
+ currentVersion: '1.0.0',
75
+ currentVersionLabel: 'Current latest version',
76
+ newVersion: '1.0.0-experimental.0',
77
+ tag: TAG.EXPERIMENTAL,
78
+ localVersion: '1.0.0-beta.1',
79
+ versionIncrement: INCREMENT.PRERELEASE,
80
+ });
81
+ expect(logger.log).toHaveBeenCalledWith('\nCurrent latest version: 1.0.0');
82
+ });
83
+ it('should log the last experimental release when given', async () => {
84
+ await confirmRelease({
85
+ isDryRun: false,
86
+ currentVersion: '1.0.0',
87
+ lastExperimentalVersion: '0.9.0-experimental.3',
88
+ newVersion: '1.0.0-experimental.0',
89
+ tag: TAG.EXPERIMENTAL,
90
+ localVersion: '1.0.0-beta.1',
91
+ versionIncrement: INCREMENT.PRERELEASE,
92
+ });
93
+ expect(logger.log).toHaveBeenCalledWith('Last experimental release: 0.9.0-experimental.3');
94
+ });
59
95
  it('should not log \\nDRY RUN when isDryRun is false', async () => {
60
96
  await confirmRelease({
61
97
  isDryRun: false,
@@ -122,6 +158,60 @@ describe('release/steps', () => {
122
158
  versionIncrement: INCREMENT.PATCH,
123
159
  })).rejects.toMatchObject({ exitCode: EXIT_CODES.SUCCESS });
124
160
  });
161
+ it('should not prompt when skipPrompts is true', async () => {
162
+ await confirmRelease({
163
+ isDryRun: false,
164
+ currentVersion: '1.0.0-beta.1',
165
+ newVersion: '1.0.1-beta.0',
166
+ tag: TAG.NEXT,
167
+ localVersion: '1.0.0-beta.1',
168
+ versionIncrement: INCREMENT.PATCH,
169
+ skipPrompts: true,
170
+ });
171
+ expect(mockedConfirm).not.toHaveBeenCalled();
172
+ });
173
+ it('should warn about the beta release and continue when skipPrompts is true', async () => {
174
+ await expect(confirmRelease({
175
+ isDryRun: false,
176
+ currentVersion: '1.0.0',
177
+ newVersion: '1.0.1',
178
+ tag: TAG.LATEST,
179
+ localVersion: '1.0.0',
180
+ versionIncrement: INCREMENT.PATCH,
181
+ skipPrompts: true,
182
+ })).resolves.toBeUndefined();
183
+ expect(mockedConfirm).not.toHaveBeenCalled();
184
+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('have not yet been released in beta'));
185
+ });
186
+ });
187
+ describe('resolveVersionIncrement', () => {
188
+ it('should return the given increment without prompting', async () => {
189
+ await expect(resolveVersionIncrement(TAG.LATEST, INCREMENT.MINOR, false)).resolves.toBe(INCREMENT.MINOR);
190
+ expect(vi.mocked(select)).not.toHaveBeenCalled();
191
+ });
192
+ it('should prompt with patch, minor, and major for latest', async () => {
193
+ vi.mocked(select).mockResolvedValue(INCREMENT.PATCH);
194
+ await expect(resolveVersionIncrement(TAG.LATEST, undefined, false)).resolves.toBe(INCREMENT.PATCH);
195
+ expect(vi.mocked(select)).toHaveBeenCalledWith(expect.objectContaining({
196
+ choices: ['patch', 'minor', 'major'].map(value => ({
197
+ name: value,
198
+ value,
199
+ })),
200
+ }));
201
+ });
202
+ it('should include prerelease in the choices for next', async () => {
203
+ vi.mocked(select).mockResolvedValue(INCREMENT.PRERELEASE);
204
+ await resolveVersionIncrement(TAG.NEXT, undefined, false);
205
+ expect(vi.mocked(select)).toHaveBeenCalledWith(expect.objectContaining({
206
+ choices: expect.arrayContaining([
207
+ { name: 'prerelease', value: 'prerelease' },
208
+ ]),
209
+ }));
210
+ });
211
+ it('should throw an actionable ReleaseError instead of prompting when skipPrompts is true', async () => {
212
+ await expect(resolveVersionIncrement(TAG.NEXT, undefined, true)).rejects.toThrow('Pass -v <patch|minor|major|prerelease>');
213
+ expect(vi.mocked(select)).not.toHaveBeenCalled();
214
+ });
125
215
  });
126
216
  describe('runBuild', () => {
127
217
  it('should call the provided build function when given', async () => {
@@ -239,6 +329,409 @@ describe('release/steps', () => {
239
329
  });
240
330
  await expect(ensureNpmAuth(false, REGISTRY)).rejects.toThrow('Failed to authenticate with npm');
241
331
  });
332
+ it('should throw instead of running npm adduser when skipPrompts is true', async () => {
333
+ mockedExec.mockRejectedValue(new Error('not logged in'));
334
+ await expect(ensureNpmAuth(false, REGISTRY, true)).rejects.toThrow(`npm login --registry ${REGISTRY}`);
335
+ expect(mockedExecSync).not.toHaveBeenCalled();
336
+ });
337
+ });
338
+ describe('ensureCleanWorkingTree', () => {
339
+ it('should resolve when git status is empty', async () => {
340
+ await expect(ensureCleanWorkingTree()).resolves.toBeUndefined();
341
+ expect(mockedExec).toHaveBeenCalledWith('git status --porcelain');
342
+ });
343
+ it('should throw an actionable ReleaseError listing the changes when the tree is dirty', async () => {
344
+ mockedExec.mockResolvedValue({
345
+ stdout: ' M src/index.ts\n?? notes.txt\n',
346
+ stderr: '',
347
+ });
348
+ const result = ensureCleanWorkingTree();
349
+ await expect(result).rejects.toThrow(ReleaseError);
350
+ await expect(result).rejects.toThrow(/uncommitted changes\. Commit or stash them[\s\S]*M src\/index\.ts/);
351
+ });
352
+ });
353
+ describe('ensureGhCli', () => {
354
+ const REPO_URL = 'https://github.com/test/repo';
355
+ it('should check gh is installed and logged in to the repository host', async () => {
356
+ await expect(ensureGhCli(REPO_URL)).resolves.toBeUndefined();
357
+ expect(mockedExec).toHaveBeenCalledWith('gh --version');
358
+ expect(mockedExec).toHaveBeenCalledWith('gh auth status --hostname github.com');
359
+ });
360
+ it('should throw an actionable ReleaseError when gh is missing', async () => {
361
+ mockedExec.mockRejectedValue(new Error('command not found: gh'));
362
+ await expect(ensureGhCli(REPO_URL)).rejects.toThrow('https://cli.github.com');
363
+ });
364
+ it('should throw an actionable ReleaseError when gh is not logged in', async () => {
365
+ mockedExec.mockImplementation((cmd) => cmd.startsWith('gh auth status')
366
+ ? Promise.reject(new Error('not logged in'))
367
+ : Promise.resolve({ stdout: '', stderr: '' }));
368
+ await expect(ensureGhCli(REPO_URL)).rejects.toThrow('gh auth login --hostname github.com');
369
+ });
370
+ it('should check auth without a hostname when the repository URL cannot be parsed', async () => {
371
+ await ensureGhCli('not a url');
372
+ expect(mockedExec).toHaveBeenCalledWith('gh auth status');
373
+ expect(mockedExecFile).not.toHaveBeenCalled();
374
+ });
375
+ it('should check that the active gh account can access the repository', async () => {
376
+ await ensureGhCli(REPO_URL);
377
+ expect(mockedExecFile).toHaveBeenCalledWith('gh', [
378
+ 'repo',
379
+ 'view',
380
+ REPO_URL,
381
+ '--json',
382
+ 'name',
383
+ ]);
384
+ });
385
+ it('should name the active account and how to switch when it cannot access the repository', async () => {
386
+ mockedExecFile.mockImplementation((_file, args) => args[0] === 'repo'
387
+ ? Promise.reject(new Error('HTTP 404: Not Found'))
388
+ : Promise.resolve({ stdout: 'someone-else\n', stderr: '' }));
389
+ await expect(ensureGhCli(REPO_URL)).rejects.toThrow(`Your active gh account (someone-else) can't access ${REPO_URL}. Switch to an account that can with \`gh auth switch --hostname github.com\``);
390
+ });
391
+ it('should still explain the access error when the active account cannot be read', async () => {
392
+ mockedExecFile.mockRejectedValue(new Error('HTTP 401'));
393
+ await expect(ensureGhCli(REPO_URL)).rejects.toThrow(`Your active gh account can't access ${REPO_URL}.`);
394
+ });
395
+ });
396
+ describe('ensureBranchPushed', () => {
397
+ const SHA = 'a'.repeat(40);
398
+ function mockShas(localSha, remoteSha) {
399
+ mockedExec.mockImplementation((cmd) => Promise.resolve({
400
+ stdout: cmd === 'git rev-parse HEAD'
401
+ ? `${localSha}\n`
402
+ : cmd === 'git rev-parse origin/feature'
403
+ ? `${remoteSha}\n`
404
+ : '',
405
+ stderr: '',
406
+ }));
407
+ }
408
+ it('should fetch the branch and return HEAD when it matches origin', async () => {
409
+ mockShas(SHA, SHA);
410
+ await expect(ensureBranchPushed('feature')).resolves.toBe(SHA);
411
+ expect(mockedExec).toHaveBeenCalledWith('git fetch origin feature');
412
+ });
413
+ it('should not require the branch to track origin', async () => {
414
+ mockShas(SHA, SHA);
415
+ await ensureBranchPushed('feature');
416
+ expect(mockedExec).not.toHaveBeenCalledWith(expect.stringContaining('@{u}'));
417
+ });
418
+ it('should throw with the push command when the branch is not on origin', async () => {
419
+ mockedExec.mockImplementation((cmd) => cmd === 'git fetch origin feature'
420
+ ? Promise.reject(new Error("couldn't find remote ref feature"))
421
+ : Promise.resolve({ stdout: '', stderr: '' }));
422
+ await expect(ensureBranchPushed('feature')).rejects.toThrow('Could not fetch origin/feature. Push your branch first: git push -u origin feature');
423
+ });
424
+ it('should throw with the push command when HEAD differs from origin', async () => {
425
+ mockShas(SHA, 'b'.repeat(40));
426
+ await expect(ensureBranchPushed('feature')).rejects.toThrow('Push your branch first: git push -u origin feature');
427
+ });
428
+ });
429
+ describe('findWorkflowRun', () => {
430
+ const SHA = 'a'.repeat(40);
431
+ const RUN = {
432
+ databaseId: 7,
433
+ displayTitle: `Experimental release feature@${SHA}`,
434
+ url: 'https://github.com/test/repo/actions/runs/7',
435
+ };
436
+ it('should return the run whose title contains the sha', async () => {
437
+ mockedExecFile.mockResolvedValue({
438
+ stdout: JSON.stringify([
439
+ { ...RUN, databaseId: 6, displayTitle: 'Experimental release x@b' },
440
+ RUN,
441
+ ]),
442
+ stderr: '',
443
+ });
444
+ await expect(findWorkflowRun('w.yml', SHA, new Set(), 1, 0)).resolves.toEqual(RUN);
445
+ expect(mockedExecFile).toHaveBeenCalledWith('gh', [
446
+ 'run',
447
+ 'list',
448
+ '--workflow',
449
+ 'w.yml',
450
+ '--event',
451
+ 'workflow_dispatch',
452
+ '--json',
453
+ 'databaseId,displayTitle,url',
454
+ '-L',
455
+ '20',
456
+ ]);
457
+ });
458
+ it('should keep polling until the run appears', async () => {
459
+ mockedExecFile
460
+ .mockResolvedValueOnce({ stdout: '[]', stderr: '' })
461
+ .mockResolvedValueOnce({ stdout: JSON.stringify([RUN]), stderr: '' });
462
+ await expect(findWorkflowRun('w.yml', SHA, new Set(), 3, 0)).resolves.toEqual(RUN);
463
+ expect(mockedExecFile).toHaveBeenCalledTimes(2);
464
+ });
465
+ it('should skip runs that existed before the dispatch, even with the same title', async () => {
466
+ const staleRun = { ...RUN, databaseId: 5 };
467
+ mockedExecFile
468
+ .mockResolvedValueOnce({
469
+ stdout: JSON.stringify([staleRun]),
470
+ stderr: '',
471
+ })
472
+ .mockResolvedValueOnce({
473
+ stdout: JSON.stringify([RUN, staleRun]),
474
+ stderr: '',
475
+ });
476
+ await expect(findWorkflowRun('w.yml', SHA, new Set([5]), 3, 0)).resolves.toEqual(RUN);
477
+ expect(mockedExecFile).toHaveBeenCalledTimes(2);
478
+ });
479
+ it('should return undefined after the last attempt', async () => {
480
+ mockedExecFile.mockResolvedValue({ stdout: '[]', stderr: '' });
481
+ await expect(findWorkflowRun('w.yml', SHA, new Set(), 2, 0)).resolves.toBeUndefined();
482
+ expect(mockedExecFile).toHaveBeenCalledTimes(2);
483
+ });
484
+ });
485
+ describe('runExperimentalWorkflow', () => {
486
+ const SHA = 'a'.repeat(40);
487
+ const RUN = {
488
+ databaseId: 7,
489
+ displayTitle: `Experimental release feature@${SHA}`,
490
+ url: 'https://github.com/test/repo/actions/runs/7',
491
+ };
492
+ const BASE_ARGS = {
493
+ workflow: 'experimental-release.yml',
494
+ mainBranch: 'main',
495
+ branch: 'feature',
496
+ sha: SHA,
497
+ packageName: PACKAGE_NAME,
498
+ isDryRun: false,
499
+ };
500
+ beforeEach(() => {
501
+ let isDispatched = false;
502
+ mockedExecFile.mockImplementation((_file, args) => {
503
+ if (args[0] === 'workflow') {
504
+ isDispatched = true;
505
+ }
506
+ return Promise.resolve({
507
+ stdout: args[1] === 'list' ? JSON.stringify(isDispatched ? [RUN] : []) : '',
508
+ stderr: '',
509
+ });
510
+ });
511
+ vi.mocked(fs.mkdtemp).mockResolvedValue('/tmp/exp-1');
512
+ vi.mocked(fs.readFile).mockResolvedValue('1.0.0-experimental.3\n');
513
+ });
514
+ it('should dispatch, watch, download the version, and print the install command', async () => {
515
+ await runExperimentalWorkflow(BASE_ARGS);
516
+ expect(mockedExecSync).toHaveBeenCalledWith('gh run watch 7 --exit-status', { stdio: 'inherit' });
517
+ expect(mockedExecFile).toHaveBeenCalledWith('gh', [
518
+ 'run',
519
+ 'download',
520
+ '7',
521
+ '-n',
522
+ 'experimental-version',
523
+ '-D',
524
+ '/tmp/exp-1',
525
+ ]);
526
+ expect(vi.mocked(fs.readFile)).toHaveBeenCalledWith('/tmp/exp-1/version.txt', 'utf8');
527
+ expect(vi.mocked(fs.remove)).toHaveBeenCalledWith('/tmp/exp-1');
528
+ expect(logger.log).toHaveBeenCalledWith(`Workflow run: ${RUN.url}`);
529
+ expect(logger.success).toHaveBeenCalledWith(`Published ${PACKAGE_NAME}@1.0.0-experimental.3 on the experimental tag`);
530
+ expect(logger.log).toHaveBeenCalledWith(`Install it with: yarn add ${PACKAGE_NAME}@1.0.0-experimental.3`);
531
+ });
532
+ it('should only print the dispatch command on dry run', async () => {
533
+ await runExperimentalWorkflow({ ...BASE_ARGS, isDryRun: true });
534
+ expect(mockedExecFile).not.toHaveBeenCalled();
535
+ expect(logger.log).toHaveBeenCalledWith(` gh workflow run experimental-release.yml --ref main -f branch=feature -f sha=${SHA}`);
536
+ });
537
+ it('should throw an actionable ReleaseError when listing runs fails before the dispatch', async () => {
538
+ mockedExecFile.mockRejectedValue(new Error('HTTP 404'));
539
+ await expect(runExperimentalWorkflow(BASE_ARGS)).rejects.toThrow('Failed to list runs of experimental-release.yml');
540
+ expect(mockedExecFile).not.toHaveBeenCalledWith('gh', expect.arrayContaining(['workflow', 'run']));
541
+ });
542
+ it('should not watch a run of the same commit that finished before the dispatch', async () => {
543
+ mockedExecFile.mockResolvedValue({
544
+ stdout: JSON.stringify([RUN]),
545
+ stderr: '',
546
+ });
547
+ vi.useFakeTimers();
548
+ const result = runExperimentalWorkflow(BASE_ARGS);
549
+ const assertion = expect(result).rejects.toThrow(ReleaseError);
550
+ await vi.runAllTimersAsync();
551
+ await assertion;
552
+ vi.useRealTimers();
553
+ expect(mockedExecSync).not.toHaveBeenCalled();
554
+ });
555
+ it('should throw an actionable ReleaseError when the dispatch fails', async () => {
556
+ mockedExecFile.mockImplementation((_file, args) => args[0] === 'workflow'
557
+ ? Promise.reject(new Error('HTTP 404'))
558
+ : Promise.resolve({ stdout: '[]', stderr: '' }));
559
+ await expect(runExperimentalWorkflow(BASE_ARGS)).rejects.toThrow('Check that the workflow exists on main');
560
+ });
561
+ it('should throw with a gh run list hint when the run cannot be found', async () => {
562
+ mockedExecFile.mockResolvedValue({ stdout: '[]', stderr: '' });
563
+ vi.useFakeTimers();
564
+ const result = runExperimentalWorkflow(BASE_ARGS);
565
+ const assertion = expect(result).rejects.toThrow('gh run list --workflow experimental-release.yml');
566
+ await vi.runAllTimersAsync();
567
+ await assertion;
568
+ vi.useRealTimers();
569
+ expect(mockedExecSync).not.toHaveBeenCalled();
570
+ });
571
+ it('should throw with the run URL when the workflow fails', async () => {
572
+ mockedExecSync.mockImplementation(() => {
573
+ throw new Error('exit 1');
574
+ });
575
+ await expect(runExperimentalWorkflow(BASE_ARGS)).rejects.toThrow(`The experimental release workflow failed. See ${RUN.url}`);
576
+ });
577
+ it('should warn with the run URL but succeed when the version artifact cannot be read', async () => {
578
+ vi.mocked(fs.readFile).mockRejectedValue(new Error('ENOENT'));
579
+ await expect(runExperimentalWorkflow(BASE_ARGS)).resolves.toBeUndefined();
580
+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining(RUN.url));
581
+ expect(vi.mocked(fs.remove)).toHaveBeenCalledWith('/tmp/exp-1');
582
+ });
583
+ });
584
+ describe('openReleasePr', () => {
585
+ const BASE_ARGS = {
586
+ tag: TAG.NEXT,
587
+ newVersion: '1.0.1-beta.0',
588
+ isDryRun: false,
589
+ baseBranch: 'main',
590
+ repositoryUrl: 'https://github.com/test/repo',
591
+ headBranch: 'v1.0.1-beta.0-publish',
592
+ onTempBranch: true,
593
+ tempBranch: 'v1.0.1-beta.0-publish',
594
+ originalBranch: 'main',
595
+ };
596
+ const PR_URL = 'https://github.com/test/repo/pull/42';
597
+ function failOn(prefix) {
598
+ mockedExec.mockImplementation((cmd) => {
599
+ if (cmd.startsWith(prefix)) {
600
+ return Promise.reject(new Error(`${prefix} failed`));
601
+ }
602
+ return Promise.resolve({ stdout: '', stderr: '' });
603
+ });
604
+ }
605
+ beforeEach(() => {
606
+ mockedExecFile.mockResolvedValue({ stdout: `${PR_URL}\n`, stderr: '' });
607
+ });
608
+ it('should bump without a git tag, commit, and push in order', async () => {
609
+ await openReleasePr(BASE_ARGS);
610
+ const calls = mockedExec.mock.calls.map(args => args[0]);
611
+ expect(calls).toEqual([
612
+ 'yarn version --no-git-tag-version --new-version 1.0.1-beta.0',
613
+ 'git add package.json',
614
+ 'git commit -m "chore: release v1.0.1-beta.0"',
615
+ 'git push -u origin v1.0.1-beta.0-publish',
616
+ ]);
617
+ });
618
+ it('should open the PR with gh using an argument list', async () => {
619
+ await openReleasePr({
620
+ ...BASE_ARGS,
621
+ tag: TAG.LATEST,
622
+ newVersion: '1.0.1',
623
+ headBranch: 'v1.0.1-publish',
624
+ tempBranch: 'v1.0.1-publish',
625
+ });
626
+ expect(mockedExecFile).toHaveBeenCalledWith('gh', [
627
+ 'pr',
628
+ 'create',
629
+ '--base',
630
+ 'main',
631
+ '--head',
632
+ 'v1.0.1-publish',
633
+ '--title',
634
+ 'chore: release v1.0.1',
635
+ '--body',
636
+ 'Merging this PR publishes v1.0.1 to npm on the latest tag. The publish runs in CI after the merge.',
637
+ ]);
638
+ });
639
+ it('should open the PR against baseBranch and name the tag in the body', async () => {
640
+ await openReleasePr({
641
+ ...BASE_ARGS,
642
+ tag: TAG.PREVIOUS,
643
+ newVersion: '0.9.1',
644
+ baseBranch: 'previous-branch',
645
+ headBranch: 'v0.9.1-publish',
646
+ tempBranch: 'v0.9.1-publish',
647
+ originalBranch: 'previous-branch',
648
+ });
649
+ expect(mockedExecFile).toHaveBeenCalledWith('gh', expect.arrayContaining([
650
+ '--base',
651
+ 'previous-branch',
652
+ '--body',
653
+ 'Merging this PR publishes v0.9.1 to npm on the previous tag. The publish runs in CI after the merge.',
654
+ ]));
655
+ });
656
+ it('should log the PR URL', async () => {
657
+ await openReleasePr(BASE_ARGS);
658
+ expect(logger.success).toHaveBeenCalledWith(`Release PR opened: ${PR_URL}`);
659
+ });
660
+ it('should push and open the PR from headBranch', async () => {
661
+ await openReleasePr({
662
+ ...BASE_ARGS,
663
+ headBranch: 'feature-branch',
664
+ onTempBranch: false,
665
+ originalBranch: 'feature-branch',
666
+ });
667
+ expect(mockedExec).toHaveBeenCalledWith('git push -u origin feature-branch');
668
+ expect(mockedExecFile).toHaveBeenCalledWith('gh', expect.arrayContaining(['--head', 'feature-branch']));
669
+ });
670
+ it('should never build, publish, or open a browser', async () => {
671
+ await openReleasePr(BASE_ARGS);
672
+ expect(mockedExec).not.toHaveBeenCalledWith('yarn build');
673
+ expect(mockedPublish).not.toHaveBeenCalled();
674
+ expect(vi.mocked(open)).not.toHaveBeenCalled();
675
+ });
676
+ it('should not commit, push, or open a PR on dry run and should revert the bump', async () => {
677
+ await openReleasePr({
678
+ ...BASE_ARGS,
679
+ isDryRun: true,
680
+ onTempBranch: false,
681
+ });
682
+ expect(mockedExec).not.toHaveBeenCalledWith(expect.stringMatching(/^(git commit|git push)/));
683
+ expect(mockedExecFile).not.toHaveBeenCalled();
684
+ expect(mockedGitCleanup).toHaveBeenCalledWith('1.0.1-beta.0', false);
685
+ });
686
+ it('should preview the headBranch on dry run', async () => {
687
+ await openReleasePr({
688
+ ...BASE_ARGS,
689
+ isDryRun: true,
690
+ onTempBranch: false,
691
+ });
692
+ expect(logger.log).toHaveBeenCalledWith(' git push -u origin v1.0.1-beta.0-publish');
693
+ expect(logger.log).toHaveBeenCalledWith(expect.stringContaining('--head v1.0.1-beta.0-publish'));
694
+ });
695
+ it('should roll back to the original branch when the push fails', async () => {
696
+ failOn('git push');
697
+ await expect(openReleasePr(BASE_ARGS)).rejects.toMatchObject({
698
+ message: '',
699
+ });
700
+ expect(mockedExec).toHaveBeenCalledWith('git reset HEAD~');
701
+ expect(mockedGitCleanup).toHaveBeenCalledWith('1.0.1-beta.0', false, 'v1.0.1-beta.0-publish', 'main');
702
+ });
703
+ it('should not reset HEAD when the failure happens before the commit', async () => {
704
+ failOn('yarn version');
705
+ await expect(openReleasePr(BASE_ARGS)).rejects.toThrow(ReleaseError);
706
+ expect(mockedExec).not.toHaveBeenCalledWith('git reset HEAD~');
707
+ expect(mockedGitCleanup).toHaveBeenCalled();
708
+ });
709
+ it('should print manual recovery commands and still throw ReleaseError when the rollback fails', async () => {
710
+ mockedExec.mockImplementation((cmd) => {
711
+ if (cmd.startsWith('git push') || cmd === 'git reset HEAD~') {
712
+ return Promise.reject(new Error(`${cmd} failed`));
713
+ }
714
+ return Promise.resolve({ stdout: '', stderr: '' });
715
+ });
716
+ await expect(openReleasePr(BASE_ARGS)).rejects.toMatchObject({
717
+ name: 'ReleaseError',
718
+ message: '',
719
+ });
720
+ expect(mockedGitCleanup).not.toHaveBeenCalled();
721
+ expect(logger.error).toHaveBeenCalledWith('Automatic cleanup failed. To restore your repository, run: git reset HEAD~ && git checkout . && git checkout main && git branch -D v1.0.1-beta.0-publish');
722
+ });
723
+ it('should print recovery commands when gitCleanup fails', async () => {
724
+ failOn('yarn version');
725
+ mockedGitCleanup.mockRejectedValue(new Error('unmerged paths'));
726
+ await expect(openReleasePr(BASE_ARGS)).rejects.toThrow(ReleaseError);
727
+ expect(logger.error).toHaveBeenCalledWith('Automatic cleanup failed. To restore your repository, run: git checkout . && git checkout main && git branch -D v1.0.1-beta.0-publish');
728
+ });
729
+ it('should tell the user how to finish or undo when PR creation fails after the push', async () => {
730
+ mockedExecFile.mockRejectedValue(new Error('gh pr create failed'));
731
+ await expect(openReleasePr(BASE_ARGS)).rejects.toThrow(ReleaseError);
732
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('git push origin --delete v1.0.1-beta.0-publish'));
733
+ expect(mockedGitCleanup).toHaveBeenCalledWith('1.0.1-beta.0', false, 'v1.0.1-beta.0-publish', 'main');
734
+ });
242
735
  });
243
736
  describe('tryPublish', () => {
244
737
  const BASE_ARGS = {
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect } from 'vitest';
2
- import { validatePreviousBranchConfigured, validateBranchForTag, validateTagIncrementCombination, validateVersionSync, validateNextReleaseIsNotOverIncrement, } from '../validate.js';
2
+ import { validatePreviousBranchConfigured, validateBranchForTag, validateTagIncrementCombination, validateVersionSync, validateNextReleaseIsNotOverIncrement, rejectVersionIncrement, } from '../validate.js';
3
3
  import { ReleaseError } from '../errors.js';
4
4
  import { TAG, INCREMENT } from '../../../constants/release.js';
5
5
  const DIST_TAGS = {
@@ -273,4 +273,12 @@ describe('release/validate', () => {
273
273
  })).toThrow('prerelease');
274
274
  });
275
275
  });
276
+ describe('rejectVersionIncrement', () => {
277
+ it('should pass when no increment is given', () => {
278
+ expect(rejectVersionIncrement({})).toBe(true);
279
+ });
280
+ it('should explain that experimental versions come from latest when -v is given', () => {
281
+ expect(() => rejectVersionIncrement({ versionIncrement: 'minor' })).toThrow("Experimental releases don't take -v");
282
+ });
283
+ });
276
284
  });