@hubspot/npm-scripts 0.1.0 → 0.2.0-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.1.0",
3
+ "version": "0.2.0-beta.0",
4
4
  "description": "Scripts for working with npm packages in the HubSpot ecosystem",
5
5
  "author": "",
6
6
  "license": "Apache-2.0",
@@ -15,7 +15,8 @@
15
15
  "prettier:write": "prettier --write './**/*.{ts,js,json}'",
16
16
  "release": "yarn tsx ./scripts/release.ts release",
17
17
  "repo-sync": "yarn tsx ./scripts/repo-sync.ts repo-sync",
18
- "test": "echo \"Error: no test specified\" && exit 1"
18
+ "test": "vitest run",
19
+ "test-dev": "vitest"
19
20
  },
20
21
  "dependencies": {
21
22
  "@inquirer/prompts": "^7.8.6",
@@ -43,7 +44,8 @@
43
44
  "lint-staged": "^15.2.10",
44
45
  "prettier": "^3.6.2",
45
46
  "tsx": "^4.20.5",
46
- "typescript": "^5.6.2"
47
+ "typescript": "^5.6.2",
48
+ "vitest": "^2.1.8"
47
49
  },
48
50
  "lint-staged": {
49
51
  "**/*.{js,ts,tsx,scss,css}": [
@@ -1,4 +1,5 @@
1
- export declare const DEFAULT_MAIN_BRANCH = "master";
1
+ export declare const DEFAULT_INTERNAL_MAIN_BRANCH = "master";
2
+ export declare const DEFAULT_EXTERNAL_MAIN_BRANCH = "main";
2
3
  export declare const SYNC_BRANCH_PREFIX = "hs-repo-sync";
3
4
  export declare const TEMP_SYNC_DIR = "hs-temp-repo-sync";
4
5
  export declare const PUBLIC_README_PATH = "PUBLIC_README.md";
@@ -1,4 +1,5 @@
1
- export const DEFAULT_MAIN_BRANCH = 'master';
1
+ export const DEFAULT_INTERNAL_MAIN_BRANCH = 'master';
2
+ export const DEFAULT_EXTERNAL_MAIN_BRANCH = 'main';
2
3
  export const SYNC_BRANCH_PREFIX = 'hs-repo-sync';
3
4
  export const TEMP_SYNC_DIR = 'hs-temp-repo-sync';
4
5
  export const PUBLIC_README_PATH = 'PUBLIC_README.md';
@@ -1,5 +1,5 @@
1
1
  import { BuildRepoSyncScriptOptions, RepoSyncArguments } from './types.js';
2
- export declare function handleRepoSync({ targetRepositoryUrl, excludePatterns, buildCommitMessage, mainBranch, version, dryRun, sshKeyPath, }: BuildRepoSyncScriptOptions & RepoSyncArguments): Promise<void>;
2
+ export declare function handleRepoSync({ targetRepositoryUrl, excludePatterns, buildCommitMessage, internalMainBranch, externalMainBranch, version, dryRun, sshKeyPath, }: BuildRepoSyncScriptOptions & RepoSyncArguments): Promise<void>;
3
3
  export declare function buildRepoSyncScript({ buildHandlerOptions, }: {
4
4
  buildHandlerOptions: BuildRepoSyncScriptOptions;
5
5
  }): void;
package/src/repo-sync.js CHANGED
@@ -4,14 +4,16 @@ import fs from 'fs-extra';
4
4
  import path from 'path';
5
5
  import { logger } from './utils/logging.js';
6
6
  import { EXIT_CODES } from './utils/process.js';
7
- import { DEFAULT_MAIN_BRANCH, SYNC_BRANCH_PREFIX, TEMP_SYNC_DIR, } from './constants/repo-sync.js';
7
+ import { DEFAULT_INTERNAL_MAIN_BRANCH, DEFAULT_EXTERNAL_MAIN_BRANCH, SYNC_BRANCH_PREFIX, TEMP_SYNC_DIR, } from './constants/repo-sync.js';
8
8
  import { checkoutBranch, cloneRepo, commitChanges, createBranch, getCurrentGitBranch, getGitEnvWithSshKey, pushBranch, } from './utils/git.js';
9
9
  import { copyFiles } from './utils/filesystem.js';
10
10
  import { confirm } from './utils/prompting.js';
11
- export async function handleRepoSync({ targetRepositoryUrl, excludePatterns, buildCommitMessage, mainBranch, version, dryRun, sshKeyPath, }) {
12
- if (!mainBranch) {
13
- logger.error('Main branch is required');
14
- process.exit(EXIT_CODES.ERROR);
11
+ export async function handleRepoSync({ targetRepositoryUrl, excludePatterns, buildCommitMessage, internalMainBranch, externalMainBranch, version, dryRun, sshKeyPath, }) {
12
+ if (!internalMainBranch) {
13
+ internalMainBranch = DEFAULT_INTERNAL_MAIN_BRANCH;
14
+ }
15
+ if (!externalMainBranch) {
16
+ externalMainBranch = DEFAULT_EXTERNAL_MAIN_BRANCH;
15
17
  }
16
18
  const originalRepoPath = process.cwd();
17
19
  let tempDir = '';
@@ -24,12 +26,12 @@ export async function handleRepoSync({ targetRepositoryUrl, excludePatterns, bui
24
26
  }
25
27
  // Ensure we are on the master branch of the current repository (or continue with confirmation)
26
28
  const currentBranch = await getCurrentGitBranch();
27
- if (currentBranch !== mainBranch) {
29
+ if (currentBranch !== internalMainBranch) {
28
30
  const shouldCheckout = await confirm({
29
- message: `You are on ${currentBranch}. Sync from ${mainBranch} branch instead?`,
31
+ message: `You are on ${currentBranch}. Sync from ${internalMainBranch} branch instead?`,
30
32
  });
31
33
  if (shouldCheckout) {
32
- await checkoutBranch(mainBranch, true);
34
+ await checkoutBranch(internalMainBranch, true);
33
35
  }
34
36
  }
35
37
  // Create temporary directory
@@ -64,7 +66,7 @@ export async function handleRepoSync({ targetRepositoryUrl, excludePatterns, bui
64
66
  // Push to target repository
65
67
  await pushBranch(syncBranch, gitEnvironment);
66
68
  // Create pull request
67
- const prUrl = `${targetRepositoryUrl}/compare/${mainBranch}...${syncBranch}?expand=1`;
69
+ const prUrl = `${targetRepositoryUrl}/compare/${externalMainBranch}...${syncBranch}?expand=1`;
68
70
  logger.log();
69
71
  logger.log('Opening target repository sync branch pull request URL in browser...');
70
72
  open(prUrl);
@@ -84,13 +86,14 @@ export async function handleRepoSync({ targetRepositoryUrl, excludePatterns, bui
84
86
  process.chdir(originalRepoPath);
85
87
  }
86
88
  }
87
- function buildHandler({ targetRepositoryUrl, excludePatterns, buildCommitMessage, mainBranch, }) {
89
+ function buildHandler({ targetRepositoryUrl, excludePatterns, buildCommitMessage, internalMainBranch, externalMainBranch, }) {
88
90
  return async function handler({ version, dryRun, sshKeyPath, }) {
89
91
  await handleRepoSync({
90
92
  targetRepositoryUrl,
91
93
  excludePatterns,
92
94
  buildCommitMessage,
93
- mainBranch,
95
+ internalMainBranch,
96
+ externalMainBranch,
94
97
  version,
95
98
  dryRun,
96
99
  sshKeyPath,
@@ -124,10 +127,7 @@ export function buildRepoSyncScript({ buildHandlerOptions, }) {
124
127
  yargs(process.argv.slice(2))
125
128
  .scriptName('yarn')
126
129
  .usage('Hubspot repo sync script')
127
- .command('repo-sync', `Syncs changes from the current repository to a target repository`, builder, buildHandler({
128
- ...buildHandlerOptions,
129
- mainBranch: buildHandlerOptions.mainBranch || DEFAULT_MAIN_BRANCH,
130
- }))
130
+ .command('repo-sync', `Syncs changes from the current repository to a target repository`, builder, buildHandler(buildHandlerOptions))
131
131
  .version(false)
132
132
  .help().argv;
133
133
  }
package/src/types.d.ts CHANGED
@@ -33,7 +33,8 @@ export interface BuildRepoSyncScriptOptions {
33
33
  targetRepositoryUrl: string;
34
34
  buildCommitMessage: (version: string) => string;
35
35
  excludePatterns?: string[];
36
- mainBranch?: string;
36
+ internalMainBranch?: string;
37
+ externalMainBranch?: string;
37
38
  }
38
39
  export interface PackageJson {
39
40
  name: string;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,154 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach, } from 'vitest';
2
+ import { copyFiles } from '../filesystem.js';
3
+ import fs from 'fs-extra';
4
+ import * as path from 'path';
5
+ import { logger } from '../logging.js';
6
+ import { TEMP_SYNC_DIR, PUBLIC_README_PATH, } from '../../constants/repo-sync.js';
7
+ vi.mock('fs-extra');
8
+ vi.mock('../logging.js', () => ({
9
+ logger: {
10
+ log: vi.fn(),
11
+ error: vi.fn(),
12
+ },
13
+ }));
14
+ vi.mock('../process.js', () => ({
15
+ EXIT_CODES: {
16
+ SUCCESS: 0,
17
+ ERROR: 1,
18
+ },
19
+ }));
20
+ const mockedFs = fs;
21
+ describe('filesystem', () => {
22
+ beforeEach(() => {
23
+ vi.resetAllMocks();
24
+ });
25
+ afterEach(() => {
26
+ vi.restoreAllMocks();
27
+ });
28
+ describe('copyFiles', () => {
29
+ it('should copy files from source to destination', async () => {
30
+ const sourcePath = '/source';
31
+ const destPath = '/dest';
32
+ mockedFs.readdir
33
+ .mockImplementationOnce(() => Promise.resolve([])) // First call: clear destination (empty)
34
+ .mockImplementationOnce(() => Promise.resolve(['file1.txt', 'file2.txt'])); // Second call: read source
35
+ mockedFs.stat.mockImplementation(() => Promise.resolve({
36
+ isDirectory: () => false,
37
+ }));
38
+ mockedFs.remove.mockImplementation(() => Promise.resolve(undefined));
39
+ await copyFiles(sourcePath, destPath);
40
+ expect(mockedFs.readdir).toHaveBeenCalledWith(sourcePath);
41
+ expect(mockedFs.readdir).toHaveBeenCalledWith(destPath);
42
+ expect(mockedFs.copyFile).toHaveBeenCalledWith(path.join(sourcePath, 'file1.txt'), path.join(destPath, 'file1.txt'));
43
+ expect(mockedFs.copyFile).toHaveBeenCalledWith(path.join(sourcePath, 'file2.txt'), path.join(destPath, 'file2.txt'));
44
+ });
45
+ it('should handle directories recursively', async () => {
46
+ const sourcePath = '/source';
47
+ const destPath = '/dest';
48
+ mockedFs.readdir
49
+ .mockImplementationOnce(() => Promise.resolve([])) // First call: clear destination (empty)
50
+ .mockImplementationOnce(() => Promise.resolve(['subdir'])) // Second call: read source
51
+ .mockImplementationOnce(() => Promise.resolve(['file.txt']));
52
+ mockedFs.stat
53
+ .mockImplementationOnce(() => Promise.resolve({
54
+ isDirectory: () => true,
55
+ }))
56
+ .mockImplementationOnce(() => Promise.resolve({
57
+ isDirectory: () => false,
58
+ }));
59
+ mockedFs.remove.mockImplementation(() => Promise.resolve(undefined));
60
+ await copyFiles(sourcePath, destPath);
61
+ expect(mockedFs.ensureDir).toHaveBeenCalledWith(path.join(destPath, 'subdir'));
62
+ expect(mockedFs.copyFile).toHaveBeenCalledWith(path.join(sourcePath, 'subdir', 'file.txt'), path.join(destPath, 'subdir', 'file.txt'));
63
+ });
64
+ it('should exclude .git directory', async () => {
65
+ const sourcePath = '/source';
66
+ const destPath = '/dest';
67
+ mockedFs.readdir
68
+ .mockImplementationOnce(() => Promise.resolve([])) // First call: clear destination (empty)
69
+ .mockImplementationOnce(() => Promise.resolve(['.git', 'file.txt'])); // Second call: read source
70
+ mockedFs.stat.mockImplementation(() => Promise.resolve({
71
+ isDirectory: () => false,
72
+ }));
73
+ mockedFs.remove.mockImplementation(() => Promise.resolve(undefined));
74
+ await copyFiles(sourcePath, destPath);
75
+ expect(mockedFs.copyFile).not.toHaveBeenCalledWith(expect.stringContaining('.git'), expect.anything());
76
+ expect(mockedFs.copyFile).toHaveBeenCalledWith(path.join(sourcePath, 'file.txt'), path.join(destPath, 'file.txt'));
77
+ });
78
+ it('should exclude TEMP_SYNC_DIR', async () => {
79
+ const sourcePath = '/source';
80
+ const destPath = '/dest';
81
+ mockedFs.readdir
82
+ .mockImplementationOnce(() => Promise.resolve([])) // First call: clear destination (empty)
83
+ .mockImplementationOnce(() => Promise.resolve([TEMP_SYNC_DIR, 'file.txt'])); // Second call: read source
84
+ mockedFs.stat.mockImplementation(() => Promise.resolve({
85
+ isDirectory: () => false,
86
+ }));
87
+ mockedFs.remove.mockImplementation(() => Promise.resolve(undefined));
88
+ await copyFiles(sourcePath, destPath);
89
+ expect(mockedFs.copyFile).not.toHaveBeenCalledWith(expect.stringContaining(TEMP_SYNC_DIR), expect.anything());
90
+ });
91
+ it('should rename PUBLIC_README.md to README.md', async () => {
92
+ const sourcePath = '/source';
93
+ const destPath = '/dest';
94
+ mockedFs.readdir
95
+ .mockImplementationOnce(() => Promise.resolve([])) // First call: clear destination (empty)
96
+ .mockImplementationOnce(() => Promise.resolve([PUBLIC_README_PATH])); // Second call: read source
97
+ mockedFs.stat.mockImplementation(() => Promise.resolve({
98
+ isDirectory: () => false,
99
+ }));
100
+ mockedFs.remove.mockImplementation(() => Promise.resolve(undefined));
101
+ await copyFiles(sourcePath, destPath);
102
+ expect(mockedFs.copyFile).toHaveBeenCalledWith(path.join(sourcePath, PUBLIC_README_PATH), path.join(destPath, 'README.md'));
103
+ });
104
+ it('should respect exclude patterns', async () => {
105
+ const sourcePath = '/source';
106
+ const destPath = '/dest';
107
+ const excludePatterns = ['*.log', '*.tmp'];
108
+ mockedFs.readdir
109
+ .mockImplementationOnce(() => Promise.resolve([])) // First call: clear destination (empty)
110
+ .mockImplementationOnce(() => Promise.resolve(['file.log', 'file.txt', 'file.tmp'])); // Second call: read source
111
+ mockedFs.stat.mockImplementation(() => Promise.resolve({
112
+ isDirectory: () => false,
113
+ }));
114
+ mockedFs.remove.mockImplementation(() => Promise.resolve(undefined));
115
+ await copyFiles(sourcePath, destPath, excludePatterns);
116
+ expect(mockedFs.copyFile).not.toHaveBeenCalledWith(expect.stringContaining('file.log'), expect.anything());
117
+ expect(mockedFs.copyFile).not.toHaveBeenCalledWith(expect.stringContaining('file.tmp'), expect.anything());
118
+ expect(mockedFs.copyFile).toHaveBeenCalledWith(path.join(sourcePath, 'file.txt'), path.join(destPath, 'file.txt'));
119
+ });
120
+ it('should not remove .git from destination', async () => {
121
+ const sourcePath = '/source';
122
+ const destPath = '/dest';
123
+ mockedFs.readdir
124
+ .mockImplementationOnce(() => Promise.resolve(['.git', 'file.txt'])) // First call: clear destination (has .git)
125
+ .mockImplementationOnce(() => Promise.resolve(['file.txt'])); // Second call: read source
126
+ mockedFs.stat.mockImplementation(() => Promise.resolve({
127
+ isDirectory: () => false,
128
+ }));
129
+ mockedFs.remove.mockImplementation(() => Promise.resolve(undefined));
130
+ await copyFiles(sourcePath, destPath);
131
+ expect(mockedFs.remove).not.toHaveBeenCalledWith(path.join(destPath, '.git'));
132
+ expect(mockedFs.remove).toHaveBeenCalledWith(path.join(destPath, 'file.txt'));
133
+ });
134
+ it('should handle errors and exit with error code', async () => {
135
+ const sourcePath = '/source';
136
+ const destPath = '/dest';
137
+ const error = new Error('Copy failed');
138
+ // First readdir succeeds (for clearing dest), then copyToDest fails
139
+ mockedFs.readdir
140
+ .mockImplementationOnce(() => Promise.resolve([])) // First call: clear destination (empty)
141
+ .mockImplementationOnce(() => Promise.reject(error)); // Second call: read source (fails)
142
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
143
+ throw new Error('process.exit called');
144
+ });
145
+ try {
146
+ await expect(copyFiles(sourcePath, destPath)).rejects.toThrow('process.exit called');
147
+ expect(vi.mocked(logger.error)).toHaveBeenCalledWith('Error copying files:', error);
148
+ }
149
+ finally {
150
+ exitSpy.mockRestore();
151
+ }
152
+ });
153
+ });
154
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,267 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { getCurrentGitBranch, gitCleanup, getGitEnvWithSshKey, cloneRepo, checkoutBranch, createBranch, commitChanges, pushBranch, } from '../git.js';
3
+ import { exec as _exec } from 'node:child_process';
4
+ import fs from 'fs-extra';
5
+ import { logger } from '../logging.js';
6
+ import { input } from '../prompting.js';
7
+ vi.mock('util', () => ({
8
+ promisify: vi.fn(fn => fn),
9
+ }));
10
+ vi.mock('node:child_process', () => ({
11
+ exec: vi.fn(),
12
+ }));
13
+ vi.mock('fs-extra', () => ({
14
+ default: {
15
+ remove: vi.fn(),
16
+ },
17
+ remove: vi.fn(),
18
+ }));
19
+ vi.mock('../logging.js', () => ({
20
+ logger: {
21
+ log: vi.fn(),
22
+ error: vi.fn(),
23
+ },
24
+ }));
25
+ vi.mock('../process.js', () => ({
26
+ EXIT_CODES: {
27
+ SUCCESS: 0,
28
+ ERROR: 1,
29
+ },
30
+ }));
31
+ vi.mock('../prompting.js', () => ({
32
+ input: vi.fn(),
33
+ }));
34
+ const mockedExec = vi.mocked(_exec);
35
+ describe('git', () => {
36
+ beforeEach(() => {
37
+ vi.resetAllMocks();
38
+ });
39
+ describe('getCurrentGitBranch', () => {
40
+ it('should return the current git branch name', async () => {
41
+ mockedExec.mockImplementation(() => Promise.resolve({
42
+ stdout: ' main \n',
43
+ stderr: '',
44
+ }));
45
+ const result = await getCurrentGitBranch();
46
+ expect(mockedExec).toHaveBeenCalledWith('git rev-parse --abbrev-ref HEAD');
47
+ expect(result).toBe('main');
48
+ });
49
+ it('should trim whitespace from branch name', async () => {
50
+ mockedExec.mockImplementation(() => Promise.resolve({
51
+ stdout: ' feature-branch \n',
52
+ stderr: '',
53
+ }));
54
+ const result = await getCurrentGitBranch();
55
+ expect(result).toBe('feature-branch');
56
+ });
57
+ });
58
+ describe('gitCleanup', () => {
59
+ it('should reset HEAD and checkout files', async () => {
60
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
61
+ await gitCleanup('1.0.0', false);
62
+ expect(mockedExec).toHaveBeenCalledWith('git reset HEAD~');
63
+ expect(mockedExec).toHaveBeenCalledWith('git checkout .');
64
+ expect(mockedExec).not.toHaveBeenCalledWith(expect.stringContaining('git tag -d'));
65
+ });
66
+ it('should delete tag when deleteTag is true', async () => {
67
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
68
+ await gitCleanup('1.0.0', true);
69
+ expect(mockedExec).toHaveBeenCalledWith('git reset HEAD~');
70
+ expect(mockedExec).toHaveBeenCalledWith('git checkout .');
71
+ expect(mockedExec).toHaveBeenCalledWith('git tag -d v1.0.0');
72
+ });
73
+ });
74
+ describe('getGitEnvWithSshKey', () => {
75
+ it('should return process.env when sshKeyPath is not provided and user leaves blank', async () => {
76
+ vi.mocked(input).mockResolvedValue('');
77
+ const result = await getGitEnvWithSshKey();
78
+ expect(result).toBe(process.env);
79
+ expect(input).toHaveBeenCalled();
80
+ });
81
+ it('should return process.env with GIT_SSH_COMMAND when sshKeyPath is provided', async () => {
82
+ const result = await getGitEnvWithSshKey('/path/to/key');
83
+ expect(result).toEqual({
84
+ ...process.env,
85
+ GIT_SSH_COMMAND: 'ssh -i /path/to/key -o IdentitiesOnly=yes',
86
+ });
87
+ expect(input).not.toHaveBeenCalled();
88
+ });
89
+ it('should prompt for sshKeyPath when not provided', async () => {
90
+ vi.mocked(input).mockResolvedValue('/custom/path/key');
91
+ const result = await getGitEnvWithSshKey();
92
+ expect(input).toHaveBeenCalledWith({
93
+ message: 'Enter the SSH key path to use (leave blank to use the default):',
94
+ });
95
+ expect(result).toEqual({
96
+ ...process.env,
97
+ GIT_SSH_COMMAND: 'ssh -i /custom/path/key -o IdentitiesOnly=yes',
98
+ });
99
+ });
100
+ });
101
+ describe('cloneRepo', () => {
102
+ it('should clone repository with correct git URL format', async () => {
103
+ const repoUrl = 'https://git.mycorp.com/Org/repo-name';
104
+ const destinationDir = '/tmp';
105
+ const targetRepoPath = '/tmp/repo-name';
106
+ vi.mocked(fs.remove).mockResolvedValue();
107
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
108
+ const result = await cloneRepo(repoUrl, destinationDir);
109
+ expect(vi.mocked(fs.remove)).toHaveBeenCalledWith(targetRepoPath);
110
+ expect(mockedExec).toHaveBeenCalledWith('git clone git@git.mycorp.com:Org/repo-name.git /tmp/repo-name', { env: undefined });
111
+ expect(result).toBe(targetRepoPath);
112
+ });
113
+ it('should handle repo URL without protocol', async () => {
114
+ const repoUrl = 'git.mycorp.com/Org/repo-name';
115
+ const destinationDir = '/tmp';
116
+ vi.mocked(fs.remove).mockResolvedValue();
117
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
118
+ await cloneRepo(repoUrl, destinationDir);
119
+ expect(mockedExec).toHaveBeenCalledWith('git clone git@git.mycorp.com:Org/repo-name.git /tmp/repo-name', { env: undefined });
120
+ });
121
+ it('should use provided git environment', async () => {
122
+ const repoUrl = 'https://git.mycorp.com/Org/repo-name';
123
+ const destinationDir = '/tmp';
124
+ const gitEnv = { GIT_SSH_COMMAND: 'ssh -i /path/to/key' };
125
+ vi.mocked(fs.remove).mockResolvedValue();
126
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
127
+ await cloneRepo(repoUrl, destinationDir, gitEnv);
128
+ expect(mockedExec).toHaveBeenCalledWith('git clone git@git.mycorp.com:Org/repo-name.git /tmp/repo-name', { env: gitEnv });
129
+ });
130
+ it('should handle errors and exit with error code', async () => {
131
+ const repoUrl = 'https://git.mycorp.com/Org/repo-name';
132
+ const destinationDir = '/tmp';
133
+ const error = new Error('Clone failed');
134
+ vi.mocked(fs.remove).mockResolvedValue();
135
+ mockedExec.mockImplementation(() => Promise.reject(error));
136
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
137
+ throw new Error('process.exit called');
138
+ });
139
+ try {
140
+ await expect(cloneRepo(repoUrl, destinationDir)).rejects.toThrow('process.exit called');
141
+ expect(vi.mocked(logger.error)).toHaveBeenCalledWith('Error cloning repository:', error);
142
+ }
143
+ finally {
144
+ exitSpy.mockRestore();
145
+ }
146
+ });
147
+ });
148
+ describe('checkoutBranch', () => {
149
+ it('should checkout branch without pulling', async () => {
150
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
151
+ await checkoutBranch('feature-branch', false);
152
+ expect(mockedExec).toHaveBeenCalledWith('git checkout feature-branch');
153
+ expect(mockedExec).not.toHaveBeenCalledWith(expect.stringContaining('git pull'));
154
+ });
155
+ it('should checkout branch and pull when pullLatest is true', async () => {
156
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
157
+ await checkoutBranch('feature-branch', true);
158
+ expect(mockedExec).toHaveBeenCalledWith('git checkout feature-branch');
159
+ expect(mockedExec).toHaveBeenCalledWith('git pull origin feature-branch');
160
+ });
161
+ it('should handle errors and exit with error code', async () => {
162
+ const error = new Error('Checkout failed');
163
+ mockedExec.mockImplementation(() => Promise.reject(error));
164
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
165
+ throw new Error('process.exit called');
166
+ });
167
+ try {
168
+ await expect(checkoutBranch('feature-branch')).rejects.toThrow('process.exit called');
169
+ expect(vi.mocked(logger.error)).toHaveBeenCalledWith('Error checking out branch feature-branch:', error);
170
+ }
171
+ finally {
172
+ exitSpy.mockRestore();
173
+ }
174
+ });
175
+ });
176
+ describe('createBranch', () => {
177
+ it('should create and checkout new branch', async () => {
178
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
179
+ await createBranch('new-branch');
180
+ expect(mockedExec).toHaveBeenCalledWith('git checkout -b new-branch');
181
+ });
182
+ it('should handle errors and exit with error code', async () => {
183
+ const error = new Error('Create branch failed');
184
+ mockedExec.mockImplementation(() => Promise.reject(error));
185
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
186
+ throw new Error('process.exit called');
187
+ });
188
+ try {
189
+ await expect(createBranch('new-branch')).rejects.toThrow('process.exit called');
190
+ expect(vi.mocked(logger.error)).toHaveBeenCalledWith('Error creating branch new-branch:', error);
191
+ }
192
+ finally {
193
+ exitSpy.mockRestore();
194
+ }
195
+ });
196
+ });
197
+ describe('commitChanges', () => {
198
+ it('should commit changes when there are staged changes', async () => {
199
+ mockedExec
200
+ .mockImplementationOnce(() => Promise.resolve({ stdout: '', stderr: '' }))
201
+ .mockImplementationOnce(() => Promise.resolve({ stdout: 'M file.txt', stderr: '' }))
202
+ .mockImplementationOnce(() => Promise.resolve({ stdout: '', stderr: '' }));
203
+ await commitChanges('Test commit message');
204
+ expect(mockedExec).toHaveBeenCalledWith('git add .');
205
+ expect(mockedExec).toHaveBeenCalledWith('git status --porcelain');
206
+ expect(mockedExec).toHaveBeenCalledWith('git commit -m "Test commit message"');
207
+ });
208
+ it('should not commit when there are no changes', async () => {
209
+ mockedExec
210
+ .mockImplementationOnce(() => Promise.resolve({ stdout: '', stderr: '' }))
211
+ .mockImplementationOnce(() => Promise.resolve({ stdout: '', stderr: '' }));
212
+ await commitChanges('Test commit message');
213
+ expect(mockedExec).toHaveBeenCalledWith('git add .');
214
+ expect(mockedExec).toHaveBeenCalledWith('git status --porcelain');
215
+ expect(mockedExec).not.toHaveBeenCalledWith(expect.stringContaining('git commit'));
216
+ expect(vi.mocked(logger.log)).toHaveBeenCalledWith('No changes to commit');
217
+ });
218
+ it('should handle errors and exit with error code', async () => {
219
+ const error = new Error('Status check failed');
220
+ mockedExec
221
+ .mockImplementationOnce(() => Promise.resolve({ stdout: '', stderr: '' }))
222
+ .mockImplementationOnce(() => Promise.reject(error));
223
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
224
+ throw new Error('process.exit called');
225
+ });
226
+ try {
227
+ await expect(commitChanges('Test commit message')).rejects.toThrow('process.exit called');
228
+ expect(vi.mocked(logger.error)).toHaveBeenCalledWith('Error checking git status');
229
+ }
230
+ finally {
231
+ exitSpy.mockRestore();
232
+ }
233
+ });
234
+ });
235
+ describe('pushBranch', () => {
236
+ it('should push branch to origin', async () => {
237
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
238
+ await pushBranch('feature-branch');
239
+ expect(vi.mocked(logger.log)).toHaveBeenCalledWith('Pushing branch feature-branch...');
240
+ expect(mockedExec).toHaveBeenCalledWith('git push origin feature-branch', {
241
+ env: undefined,
242
+ });
243
+ });
244
+ it('should use provided git environment', async () => {
245
+ const gitEnv = { GIT_SSH_COMMAND: 'ssh -i /path/to/key' };
246
+ mockedExec.mockImplementation(() => Promise.resolve({ stdout: '', stderr: '' }));
247
+ await pushBranch('feature-branch', gitEnv);
248
+ expect(mockedExec).toHaveBeenCalledWith('git push origin feature-branch', {
249
+ env: gitEnv,
250
+ });
251
+ });
252
+ it('should handle errors and exit with error code', async () => {
253
+ const error = new Error('Push failed');
254
+ mockedExec.mockImplementation(() => Promise.reject(error));
255
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
256
+ throw new Error('process.exit called');
257
+ });
258
+ try {
259
+ await expect(pushBranch('feature-branch')).rejects.toThrow('process.exit called');
260
+ expect(vi.mocked(logger.error)).toHaveBeenCalledWith('Error pushing branch feature-branch:', error);
261
+ }
262
+ finally {
263
+ exitSpy.mockRestore();
264
+ }
265
+ });
266
+ });
267
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,64 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { logger } from '../logging.js';
3
+ describe('logging', () => {
4
+ const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => { });
5
+ beforeEach(() => {
6
+ consoleLogSpy.mockClear();
7
+ });
8
+ afterEach(() => {
9
+ consoleLogSpy.mockClear();
10
+ });
11
+ describe('logger.log', () => {
12
+ it('should call console.log with provided arguments', () => {
13
+ logger.log('test message', 123);
14
+ expect(consoleLogSpy).toHaveBeenCalledWith('test message', 123);
15
+ });
16
+ });
17
+ describe('logger.info', () => {
18
+ it('should call console.log with [INFO] prefix', () => {
19
+ logger.info('info message');
20
+ expect(consoleLogSpy).toHaveBeenCalled();
21
+ const callArgs = consoleLogSpy.mock.calls[0];
22
+ expect(callArgs[0]).toContain('[INFO]');
23
+ expect(callArgs[1]).toBe('info message');
24
+ });
25
+ });
26
+ describe('logger.success', () => {
27
+ it('should call console.log with [SUCCESS] prefix', () => {
28
+ logger.success('success message');
29
+ expect(consoleLogSpy).toHaveBeenCalled();
30
+ const callArgs = consoleLogSpy.mock.calls[0];
31
+ expect(callArgs[0]).toContain('[SUCCESS]');
32
+ expect(callArgs[1]).toBe('success message');
33
+ });
34
+ });
35
+ describe('logger.warn', () => {
36
+ it('should call console.log with [WARN] prefix', () => {
37
+ logger.warn('warning message');
38
+ expect(consoleLogSpy).toHaveBeenCalled();
39
+ const callArgs = consoleLogSpy.mock.calls[0];
40
+ expect(callArgs[0]).toContain('[WARN]');
41
+ expect(callArgs[1]).toBe('warning message');
42
+ });
43
+ });
44
+ describe('logger.error', () => {
45
+ it('should call console.log with [ERROR] prefix', () => {
46
+ logger.error('error message');
47
+ expect(consoleLogSpy).toHaveBeenCalled();
48
+ const callArgs = consoleLogSpy.mock.calls[0];
49
+ expect(callArgs[0]).toContain('[ERROR]');
50
+ expect(callArgs[1]).toBe('error message');
51
+ });
52
+ });
53
+ describe('logger.table', () => {
54
+ it('should call console.table with provided arguments', () => {
55
+ const consoleTableSpy = vi
56
+ .spyOn(console, 'table')
57
+ .mockImplementation(() => { });
58
+ const data = { a: 1, b: 2 };
59
+ logger.table(data);
60
+ expect(consoleTableSpy).toHaveBeenCalledWith(data);
61
+ consoleTableSpy.mockRestore();
62
+ });
63
+ });
64
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,165 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { getDistTags, publish, updateNextTag } from '../npm.js';
3
+ import { exec as _exec, spawn } from 'node:child_process';
4
+ import { logger } from '../logging.js';
5
+ import { EXIT_CODES } from '../process.js';
6
+ import { TAG } from '../../constants/release.js';
7
+ vi.mock('util', () => ({
8
+ promisify: vi.fn(fn => fn),
9
+ }));
10
+ vi.mock('node:child_process', () => ({
11
+ exec: vi.fn(),
12
+ spawn: vi.fn(),
13
+ }));
14
+ vi.mock('../logging.js', () => ({
15
+ logger: {
16
+ log: vi.fn(),
17
+ success: vi.fn(),
18
+ },
19
+ }));
20
+ vi.mock('../process.js', () => ({
21
+ EXIT_CODES: {
22
+ SUCCESS: 0,
23
+ ERROR: 1,
24
+ },
25
+ }));
26
+ const mockedExec = vi.mocked(_exec);
27
+ const mockedSpawn = vi.mocked(spawn);
28
+ describe('npm', () => {
29
+ beforeEach(() => {
30
+ vi.resetAllMocks();
31
+ });
32
+ describe('getDistTags', () => {
33
+ it('should return parsed dist tags from npm view', async () => {
34
+ const mockDistTags = {
35
+ latest: '1.0.0',
36
+ next: '1.1.0-beta.1',
37
+ experimental: '1.2.0-experimental.1',
38
+ };
39
+ mockedExec.mockImplementation(() => Promise.resolve({
40
+ stdout: JSON.stringify(mockDistTags),
41
+ stderr: '',
42
+ }));
43
+ const result = await getDistTags('@hubspot/test-package');
44
+ expect(mockedExec).toHaveBeenCalledWith('npm view @hubspot/test-package dist-tags --json');
45
+ expect(result).toEqual(mockDistTags);
46
+ });
47
+ it('should handle whitespace in stdout', async () => {
48
+ const mockDistTags = {
49
+ latest: '1.0.0',
50
+ next: '1.1.0-beta.1',
51
+ };
52
+ mockedExec.mockImplementation(() => Promise.resolve({
53
+ stdout: `\n${JSON.stringify(mockDistTags)}\n`,
54
+ stderr: '',
55
+ }));
56
+ const result = await getDistTags('@hubspot/test-package');
57
+ expect(result).toEqual(mockDistTags);
58
+ });
59
+ });
60
+ describe('publish', () => {
61
+ it('should publish with correct arguments', async () => {
62
+ const mockChildProcess = {
63
+ on: vi.fn((event, callback) => {
64
+ if (event === 'close') {
65
+ setTimeout(() => callback(EXIT_CODES.SUCCESS), 0);
66
+ }
67
+ return mockChildProcess;
68
+ }),
69
+ };
70
+ mockedSpawn.mockImplementation(() => mockChildProcess);
71
+ await publish(TAG.LATEST, '123456', false, 'https://registry.npmjs.org/');
72
+ expect(mockedSpawn).toHaveBeenCalledWith('npm', [
73
+ 'publish',
74
+ '--tag',
75
+ TAG.LATEST,
76
+ '--registry',
77
+ 'https://registry.npmjs.org/',
78
+ '--otp',
79
+ '123456',
80
+ ], {
81
+ stdio: 'inherit',
82
+ cwd: './dist',
83
+ });
84
+ });
85
+ it('should include --dry-run flag when isDryRun is true', async () => {
86
+ const mockChildProcess = {
87
+ on: vi.fn((event, callback) => {
88
+ if (event === 'close') {
89
+ setTimeout(() => callback(EXIT_CODES.SUCCESS), 0);
90
+ }
91
+ return mockChildProcess;
92
+ }),
93
+ };
94
+ mockedSpawn.mockImplementation(() => mockChildProcess);
95
+ await publish(TAG.NEXT, '123456', true, 'https://registry.npmjs.org/');
96
+ expect(mockedSpawn).toHaveBeenCalledWith('npm', [
97
+ 'publish',
98
+ '--tag',
99
+ TAG.NEXT,
100
+ '--registry',
101
+ 'https://registry.npmjs.org/',
102
+ '--otp',
103
+ '123456',
104
+ '--dry-run',
105
+ ], {
106
+ stdio: 'inherit',
107
+ cwd: './dist',
108
+ });
109
+ });
110
+ it('should reject on non-zero exit code', async () => {
111
+ const mockChildProcess = {
112
+ on: vi.fn((event, callback) => {
113
+ if (event === 'close') {
114
+ setTimeout(() => callback(EXIT_CODES.ERROR), 0);
115
+ }
116
+ return mockChildProcess;
117
+ }),
118
+ };
119
+ mockedSpawn.mockImplementation(() => mockChildProcess);
120
+ await expect(publish(TAG.LATEST, '123456', false, 'https://registry.npmjs.org/')).rejects.toThrow('npm publish failed with exit code 1');
121
+ });
122
+ });
123
+ describe('updateNextTag', () => {
124
+ it('should update next tag with correct arguments', async () => {
125
+ const mockChildProcess = {
126
+ on: vi.fn((event, callback) => {
127
+ if (event === 'close') {
128
+ setTimeout(() => callback(EXIT_CODES.SUCCESS), 0);
129
+ }
130
+ return mockChildProcess;
131
+ }),
132
+ };
133
+ mockedSpawn.mockImplementation(() => mockChildProcess);
134
+ await updateNextTag('@hubspot/test-package', '1.0.0', '123456', false, 'https://registry.npmjs.org/');
135
+ expect(mockedSpawn).toHaveBeenCalledWith('npm', [
136
+ 'dist-tag',
137
+ 'add',
138
+ '@hubspot/test-package@1.0.0',
139
+ TAG.NEXT,
140
+ '--registry',
141
+ 'https://registry.npmjs.org/',
142
+ '--otp',
143
+ '123456',
144
+ ], { stdio: 'inherit' });
145
+ expect(vi.mocked(logger.success)).toHaveBeenCalledWith(`${TAG.NEXT} tag updated successfully`);
146
+ });
147
+ it('should skip execution and log dry run message when isDryRun is true', async () => {
148
+ await updateNextTag('@hubspot/test-package', '1.0.0', '123456', true, 'https://registry.npmjs.org/');
149
+ expect(mockedSpawn).not.toHaveBeenCalled();
150
+ expect(vi.mocked(logger.log)).toHaveBeenCalledWith(expect.stringContaining('Dry run: skipping run of'));
151
+ });
152
+ it('should reject on non-zero exit code', async () => {
153
+ const mockChildProcess = {
154
+ on: vi.fn((event, callback) => {
155
+ if (event === 'close') {
156
+ setTimeout(() => callback(EXIT_CODES.ERROR), 0);
157
+ }
158
+ return mockChildProcess;
159
+ }),
160
+ };
161
+ mockedSpawn.mockImplementation(() => mockChildProcess);
162
+ await expect(updateNextTag('@hubspot/test-package', '1.0.0', '123456', false, 'https://registry.npmjs.org/')).rejects.toThrow('npm dist-tag add failed with exit code 1');
163
+ });
164
+ });
165
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { EXIT_CODES } from '../process.js';
3
+ describe('process', () => {
4
+ describe('EXIT_CODES', () => {
5
+ it('should have SUCCESS equal to 0', () => {
6
+ expect(EXIT_CODES.SUCCESS).toBe(0);
7
+ });
8
+ it('should have ERROR equal to 1', () => {
9
+ expect(EXIT_CODES.ERROR).toBe(1);
10
+ });
11
+ });
12
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,100 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { confirm, input, checkbox } from '../prompting.js';
3
+ import { logger } from '../logging.js';
4
+ import _confirm from '@inquirer/confirm';
5
+ import _input from '@inquirer/input';
6
+ import _checkbox from '@inquirer/checkbox';
7
+ vi.mock('@inquirer/confirm', () => ({
8
+ default: vi.fn(),
9
+ }));
10
+ vi.mock('@inquirer/input', () => ({
11
+ default: vi.fn(),
12
+ }));
13
+ vi.mock('@inquirer/checkbox', () => ({
14
+ default: vi.fn(),
15
+ }));
16
+ vi.mock('../logging.js', () => ({
17
+ logger: {
18
+ log: vi.fn(),
19
+ },
20
+ }));
21
+ describe('prompting', () => {
22
+ beforeEach(() => {
23
+ vi.clearAllMocks();
24
+ });
25
+ describe('confirm', () => {
26
+ it('should return the result from inquirer confirm', async () => {
27
+ const mockConfirmFn = vi.mocked(_confirm);
28
+ mockConfirmFn.mockResolvedValue(true);
29
+ const result = await confirm({ message: 'Are you sure?' });
30
+ expect(result).toBe(true);
31
+ expect(mockConfirmFn).toHaveBeenCalledWith({ message: 'Are you sure?' });
32
+ });
33
+ it('should exit on ExitPromptError', async () => {
34
+ const mockConfirmFn = vi.mocked(_confirm);
35
+ const exitError = new Error('User exited');
36
+ exitError.name = 'ExitPromptError';
37
+ mockConfirmFn.mockRejectedValue(exitError);
38
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
39
+ throw new Error('process.exit called');
40
+ });
41
+ await expect(confirm({ message: 'Test' })).rejects.toThrow('process.exit called');
42
+ expect(vi.mocked(logger.log)).toHaveBeenCalledWith('Exiting...');
43
+ exitSpy.mockRestore();
44
+ });
45
+ it('should rethrow non-ExitPromptError', async () => {
46
+ const mockConfirmFn = vi.mocked(_confirm);
47
+ const otherError = new Error('Other error');
48
+ mockConfirmFn.mockRejectedValue(otherError);
49
+ await expect(confirm({ message: 'Test' })).rejects.toThrow('Other error');
50
+ });
51
+ });
52
+ describe('input', () => {
53
+ it('should return the result from inquirer input', async () => {
54
+ const mockInputFn = vi.mocked(_input);
55
+ mockInputFn.mockResolvedValue('test input');
56
+ const result = await input({ message: 'Enter value:' });
57
+ expect(result).toBe('test input');
58
+ expect(mockInputFn).toHaveBeenCalledWith({ message: 'Enter value:' });
59
+ });
60
+ it('should exit on ExitPromptError', async () => {
61
+ const mockInputFn = vi.mocked(_input);
62
+ const exitError = new Error('User exited');
63
+ exitError.name = 'ExitPromptError';
64
+ mockInputFn.mockRejectedValue(exitError);
65
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
66
+ throw new Error('process.exit called');
67
+ });
68
+ await expect(input({ message: 'Test' })).rejects.toThrow('process.exit called');
69
+ expect(vi.mocked(logger.log)).toHaveBeenCalledWith('Exiting...');
70
+ exitSpy.mockRestore();
71
+ });
72
+ });
73
+ describe('checkbox', () => {
74
+ it('should return the result from inquirer checkbox', async () => {
75
+ const mockCheckboxFn = vi.mocked(_checkbox);
76
+ mockCheckboxFn.mockResolvedValue(['option1', 'option2']);
77
+ const result = await checkbox({
78
+ message: 'Select options:',
79
+ choices: [{ value: 'option1' }, { value: 'option2' }],
80
+ });
81
+ expect(result).toEqual(['option1', 'option2']);
82
+ expect(mockCheckboxFn).toHaveBeenCalledWith({
83
+ message: 'Select options:',
84
+ choices: [{ value: 'option1' }, { value: 'option2' }],
85
+ });
86
+ });
87
+ it('should exit on ExitPromptError', async () => {
88
+ const mockCheckboxFn = vi.mocked(_checkbox);
89
+ const exitError = new Error('User exited');
90
+ exitError.name = 'ExitPromptError';
91
+ mockCheckboxFn.mockRejectedValue(exitError);
92
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
93
+ throw new Error('process.exit called');
94
+ });
95
+ await expect(checkbox({ message: 'Test', choices: [{ value: 'option1' }] })).rejects.toThrow('process.exit called');
96
+ expect(vi.mocked(logger.log)).toHaveBeenCalledWith('Exiting...');
97
+ exitSpy.mockRestore();
98
+ });
99
+ });
100
+ });
package/src/utils/npm.js CHANGED
@@ -32,7 +32,7 @@ export async function publish(tag, otp, isDryRun, registry) {
32
32
  });
33
33
  childProcess.on('close', code => {
34
34
  if (code !== EXIT_CODES.SUCCESS) {
35
- reject();
35
+ reject(new Error(`npm publish failed with exit code ${code}`));
36
36
  }
37
37
  else {
38
38
  resolve();
@@ -63,7 +63,7 @@ export async function updateNextTag(packageName, newVersion, otp, isDryRun, regi
63
63
  const childProcess = spawn('npm', commandArgs, { stdio: 'inherit' });
64
64
  childProcess.on('close', code => {
65
65
  if (code !== EXIT_CODES.SUCCESS) {
66
- reject();
66
+ reject(new Error(`npm dist-tag add failed with exit code ${code}`));
67
67
  }
68
68
  else {
69
69
  logger.success(`${TAG.NEXT} tag updated successfully`);