@hubspot/npm-scripts 0.0.4-experimental.1 → 0.0.4-experimental.2

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.
@@ -0,0 +1,266 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { getDistTags, publish, updateDistTag, updateNextTag, updatePreviousTag, } 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, 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, false, '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 include --ignore-scripts flag when ignoreScripts is true', async () => {
111
+ const mockChildProcess = {
112
+ on: vi.fn((event, callback) => {
113
+ if (event === 'close') {
114
+ setTimeout(() => callback(EXIT_CODES.SUCCESS), 0);
115
+ }
116
+ return mockChildProcess;
117
+ }),
118
+ };
119
+ mockedSpawn.mockImplementation(() => mockChildProcess);
120
+ await publish(TAG.LATEST, '123456', false, true, 'https://registry.npmjs.org/');
121
+ expect(mockedSpawn).toHaveBeenCalledWith('npm', [
122
+ 'publish',
123
+ '--tag',
124
+ TAG.LATEST,
125
+ '--registry',
126
+ 'https://registry.npmjs.org/',
127
+ '--otp',
128
+ '123456',
129
+ '--ignore-scripts',
130
+ ], {
131
+ stdio: 'inherit',
132
+ cwd: './dist',
133
+ });
134
+ });
135
+ it('should include both --dry-run and --ignore-scripts flags when both are true', async () => {
136
+ const mockChildProcess = {
137
+ on: vi.fn((event, callback) => {
138
+ if (event === 'close') {
139
+ setTimeout(() => callback(EXIT_CODES.SUCCESS), 0);
140
+ }
141
+ return mockChildProcess;
142
+ }),
143
+ };
144
+ mockedSpawn.mockImplementation(() => mockChildProcess);
145
+ await publish(TAG.LATEST, '123456', true, true, 'https://registry.npmjs.org/');
146
+ expect(mockedSpawn).toHaveBeenCalledWith('npm', [
147
+ 'publish',
148
+ '--tag',
149
+ TAG.LATEST,
150
+ '--registry',
151
+ 'https://registry.npmjs.org/',
152
+ '--otp',
153
+ '123456',
154
+ '--dry-run',
155
+ '--ignore-scripts',
156
+ ], {
157
+ stdio: 'inherit',
158
+ cwd: './dist',
159
+ });
160
+ });
161
+ it('should reject on non-zero exit code', async () => {
162
+ const mockChildProcess = {
163
+ on: vi.fn((event, callback) => {
164
+ if (event === 'close') {
165
+ setTimeout(() => callback(EXIT_CODES.ERROR), 0);
166
+ }
167
+ return mockChildProcess;
168
+ }),
169
+ };
170
+ mockedSpawn.mockImplementation(() => mockChildProcess);
171
+ await expect(publish(TAG.LATEST, '123456', false, false, 'https://registry.npmjs.org/')).rejects.toThrow('npm publish failed with exit code 1');
172
+ });
173
+ });
174
+ describe('updateDistTag', () => {
175
+ it('should update dist tag with correct arguments', async () => {
176
+ const mockChildProcess = {
177
+ on: vi.fn((event, callback) => {
178
+ if (event === 'close') {
179
+ setTimeout(() => callback(EXIT_CODES.SUCCESS), 0);
180
+ }
181
+ return mockChildProcess;
182
+ }),
183
+ };
184
+ mockedSpawn.mockImplementation(() => mockChildProcess);
185
+ await updateDistTag('@hubspot/test-package', '1.0.0', 'custom-tag', '123456', false, 'https://registry.npmjs.org/');
186
+ expect(mockedSpawn).toHaveBeenCalledWith('npm', [
187
+ 'dist-tag',
188
+ 'add',
189
+ '@hubspot/test-package@1.0.0',
190
+ 'custom-tag',
191
+ '--registry',
192
+ 'https://registry.npmjs.org/',
193
+ '--otp',
194
+ '123456',
195
+ ], { stdio: 'inherit' });
196
+ expect(vi.mocked(logger.success)).toHaveBeenCalledWith('custom-tag tag updated successfully');
197
+ });
198
+ it('should skip execution and log dry run message when isDryRun is true', async () => {
199
+ await updateDistTag('@hubspot/test-package', '1.0.0', 'custom-tag', '123456', true, 'https://registry.npmjs.org/');
200
+ expect(mockedSpawn).not.toHaveBeenCalled();
201
+ expect(vi.mocked(logger.log)).toHaveBeenCalledWith(expect.stringContaining('Dry run: skipping run of'));
202
+ });
203
+ it('should reject on non-zero exit code', async () => {
204
+ const mockChildProcess = {
205
+ on: vi.fn((event, callback) => {
206
+ if (event === 'close') {
207
+ setTimeout(() => callback(EXIT_CODES.ERROR), 0);
208
+ }
209
+ return mockChildProcess;
210
+ }),
211
+ };
212
+ mockedSpawn.mockImplementation(() => mockChildProcess);
213
+ await expect(updateDistTag('@hubspot/test-package', '1.0.0', 'custom-tag', '123456', false, 'https://registry.npmjs.org/')).rejects.toThrow('npm dist-tag add failed with exit code 1');
214
+ });
215
+ });
216
+ describe('updateNextTag', () => {
217
+ it('should call updateDistTag with TAG.NEXT', async () => {
218
+ const mockChildProcess = {
219
+ on: vi.fn((event, callback) => {
220
+ if (event === 'close') {
221
+ setTimeout(() => callback(EXIT_CODES.SUCCESS), 0);
222
+ }
223
+ return mockChildProcess;
224
+ }),
225
+ };
226
+ mockedSpawn.mockImplementation(() => mockChildProcess);
227
+ await updateNextTag('@hubspot/test-package', '1.0.0', '123456', false, 'https://registry.npmjs.org/');
228
+ expect(mockedSpawn).toHaveBeenCalledWith('npm', [
229
+ 'dist-tag',
230
+ 'add',
231
+ '@hubspot/test-package@1.0.0',
232
+ TAG.NEXT,
233
+ '--registry',
234
+ 'https://registry.npmjs.org/',
235
+ '--otp',
236
+ '123456',
237
+ ], { stdio: 'inherit' });
238
+ expect(vi.mocked(logger.success)).toHaveBeenCalledWith(`${TAG.NEXT} tag updated successfully`);
239
+ });
240
+ });
241
+ describe('updatePreviousTag', () => {
242
+ it('should call updateDistTag with TAG.PREVIOUS', async () => {
243
+ const mockChildProcess = {
244
+ on: vi.fn((event, callback) => {
245
+ if (event === 'close') {
246
+ setTimeout(() => callback(EXIT_CODES.SUCCESS), 0);
247
+ }
248
+ return mockChildProcess;
249
+ }),
250
+ };
251
+ mockedSpawn.mockImplementation(() => mockChildProcess);
252
+ await updatePreviousTag('@hubspot/test-package', '8.3.6', '123456', false, 'https://registry.npmjs.org/');
253
+ expect(mockedSpawn).toHaveBeenCalledWith('npm', [
254
+ 'dist-tag',
255
+ 'add',
256
+ '@hubspot/test-package@8.3.6',
257
+ TAG.PREVIOUS,
258
+ '--registry',
259
+ 'https://registry.npmjs.org/',
260
+ '--otp',
261
+ '123456',
262
+ ], { stdio: 'inherit' });
263
+ expect(vi.mocked(logger.success)).toHaveBeenCalledWith(`${TAG.PREVIOUS} tag updated successfully`);
264
+ });
265
+ });
266
+ });
@@ -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
+ });
@@ -0,0 +1 @@
1
+ export declare function copyFiles(sourcePath: string, destPath: string, excludePatterns?: string[]): Promise<void>;
@@ -0,0 +1,72 @@
1
+ import path from 'path';
2
+ import fs from 'fs-extra';
3
+ import { minimatch } from 'minimatch';
4
+ import { logger } from './logging.js';
5
+ import { PUBLIC_README_PATH, TEMP_SYNC_DIR } from '../constants/repo-sync.js';
6
+ import { EXIT_CODES } from './process.js';
7
+ function getDestItemPath(destPath, item) {
8
+ // Rename PUBLIC_README.md to README.md
9
+ if (item === PUBLIC_README_PATH) {
10
+ return path.join(destPath, 'README.md');
11
+ }
12
+ return path.join(destPath, item);
13
+ }
14
+ function shouldExclude(relativePath, excludePatterns) {
15
+ // Always exclude the temporary sync directory
16
+ if (relativePath === TEMP_SYNC_DIR ||
17
+ relativePath.startsWith(TEMP_SYNC_DIR + '/')) {
18
+ return true;
19
+ }
20
+ // Always exclude .git directory
21
+ if (relativePath === '.git' || relativePath.startsWith('.git/')) {
22
+ return true;
23
+ }
24
+ if (!excludePatterns) {
25
+ return false;
26
+ }
27
+ return excludePatterns.some(pattern => {
28
+ // Use minimatch for proper glob pattern matching
29
+ // matchBase: true allows patterns like "*.log" to match at any level if no "/" is in pattern
30
+ // dot: true allows matching dotfiles
31
+ return minimatch(relativePath, pattern, { matchBase: true, dot: true });
32
+ });
33
+ }
34
+ async function copyToDest(sourcePath, destPath, sourceRoot, excludePatterns) {
35
+ const items = await fs.readdir(sourcePath);
36
+ for (const item of items) {
37
+ const sourceItem = path.join(sourcePath, item);
38
+ const destItem = getDestItemPath(destPath, item);
39
+ // Calculate relative path from the source root for pattern matching
40
+ const relativePath = path.relative(sourceRoot, sourceItem);
41
+ // Skip excluded patterns and temp directories
42
+ if (shouldExclude(relativePath, excludePatterns)) {
43
+ continue;
44
+ }
45
+ const stats = await fs.stat(sourceItem);
46
+ if (stats.isDirectory()) {
47
+ await fs.ensureDir(destItem);
48
+ await copyToDest(sourceItem, destItem, sourceRoot, excludePatterns);
49
+ }
50
+ else {
51
+ await fs.copyFile(sourceItem, destItem);
52
+ }
53
+ }
54
+ }
55
+ export async function copyFiles(sourcePath, destPath, excludePatterns) {
56
+ logger.log(`Copying files from ${sourcePath} to ${destPath}...`);
57
+ // Clear the destination directory first (except .git)
58
+ const items = await fs.readdir(destPath);
59
+ for (const item of items) {
60
+ if (item !== '.git') {
61
+ const itemPath = path.join(destPath, item);
62
+ await fs.remove(itemPath);
63
+ }
64
+ }
65
+ try {
66
+ await copyToDest(sourcePath, destPath, sourcePath, excludePatterns);
67
+ }
68
+ catch (error) {
69
+ logger.error('Error copying files:', error);
70
+ process.exit(EXIT_CODES.ERROR);
71
+ }
72
+ }
@@ -1,2 +1,8 @@
1
1
  export declare function getCurrentGitBranch(): Promise<string>;
2
2
  export declare function gitCleanup(newVersion: string, deleteTag: boolean): Promise<void>;
3
+ export declare function getGitEnvWithSshKey(sshKeyPath?: string): Promise<typeof process.env | undefined>;
4
+ export declare function cloneRepo(repoUrl: string, destinationDir: string, gitEnvironment?: typeof process.env): Promise<string>;
5
+ export declare function checkoutBranch(branchName: string, pullLatest?: boolean): Promise<void>;
6
+ export declare function createBranch(branchName: string): Promise<void>;
7
+ export declare function commitChanges(commitMessage: string): Promise<void>;
8
+ export declare function pushBranch(branchName: string, gitEnvironment?: typeof process.env): Promise<void>;
package/src/utils/git.js CHANGED
@@ -1,6 +1,17 @@
1
1
  import { promisify } from 'util';
2
+ import path from 'path';
3
+ import fs from 'fs-extra';
2
4
  import { exec as _exec } from 'node:child_process';
5
+ import { logger } from './logging.js';
6
+ import { EXIT_CODES } from './process.js';
7
+ import { input } from './prompting.js';
3
8
  const exec = promisify(_exec);
9
+ function getRepoPartsFromUrl(repoUrl) {
10
+ // Strip protocol if present, e.g. "https://git.mycorp.com/Org/repo-name" -> "git.mycorp.com/Org/repo-name"
11
+ const withoutProtocol = repoUrl.trim().replace(/^[a-z]+:\/\//i, '');
12
+ const [host, org, repo] = withoutProtocol.split('/');
13
+ return { host, org, repo };
14
+ }
4
15
  export async function getCurrentGitBranch() {
5
16
  const { stdout } = await exec('git rev-parse --abbrev-ref HEAD');
6
17
  return stdout.trim();
@@ -12,3 +23,92 @@ export async function gitCleanup(newVersion, deleteTag) {
12
23
  await exec(`git tag -d v${newVersion}`);
13
24
  }
14
25
  }
26
+ export async function getGitEnvWithSshKey(sshKeyPath) {
27
+ if (!sshKeyPath) {
28
+ sshKeyPath = await input({
29
+ message: 'Enter the SSH key path to use (leave blank to use the default):',
30
+ });
31
+ if (!sshKeyPath) {
32
+ return process.env;
33
+ }
34
+ }
35
+ return {
36
+ ...process.env,
37
+ GIT_SSH_COMMAND: `ssh -i ${sshKeyPath} -o IdentitiesOnly=yes`,
38
+ };
39
+ }
40
+ export async function cloneRepo(repoUrl, destinationDir, gitEnvironment) {
41
+ logger.log(`Cloning repository into ${destinationDir}...`);
42
+ const { host, org, repo } = getRepoPartsFromUrl(repoUrl);
43
+ const targetRepoPath = path.join(destinationDir, repo);
44
+ // Remove existing directory if it exists
45
+ try {
46
+ await fs.remove(targetRepoPath);
47
+ }
48
+ catch (error) {
49
+ // Ignore error if directory doesn't exist
50
+ }
51
+ try {
52
+ await exec(`git clone git@${host}:${org}/${repo}.git ${targetRepoPath}`, {
53
+ env: gitEnvironment,
54
+ });
55
+ }
56
+ catch (error) {
57
+ logger.error(`Error cloning repository:`, error);
58
+ process.exit(EXIT_CODES.ERROR);
59
+ }
60
+ return targetRepoPath;
61
+ }
62
+ export async function checkoutBranch(branchName, pullLatest = false) {
63
+ try {
64
+ await exec(`git checkout ${branchName}`);
65
+ if (pullLatest) {
66
+ await exec(`git pull origin ${branchName}`);
67
+ }
68
+ }
69
+ catch (error) {
70
+ logger.error(`Error checking out branch ${branchName}:`, error);
71
+ process.exit(EXIT_CODES.ERROR);
72
+ }
73
+ }
74
+ export async function createBranch(branchName) {
75
+ try {
76
+ await exec(`git checkout -b ${branchName}`);
77
+ }
78
+ catch (error) {
79
+ logger.error(`Error creating branch ${branchName}:`, error);
80
+ process.exit(EXIT_CODES.ERROR);
81
+ }
82
+ }
83
+ export async function commitChanges(commitMessage) {
84
+ // Add all changes
85
+ await exec('git add .');
86
+ // Check if there are any changes to commit
87
+ try {
88
+ const { stdout } = await exec('git status --porcelain');
89
+ if (!stdout.trim()) {
90
+ logger.log('No changes to commit');
91
+ return;
92
+ }
93
+ }
94
+ catch (error) {
95
+ logger.error('Error checking git status');
96
+ process.exit(EXIT_CODES.ERROR);
97
+ }
98
+ await exec(`git commit -m "${commitMessage}"`);
99
+ }
100
+ // ssh url: git@github.com:HubSpotEngineering/Dev-Experience-Fe-Scripts.git
101
+ // targetRepositoryOrg = https://github.com/HubSpotEngineering
102
+ // targetRepositoryName = Dev-Experience-Fe-Scripts.git
103
+ export async function pushBranch(branchName, gitEnvironment) {
104
+ logger.log(`Pushing branch ${branchName}...`);
105
+ try {
106
+ await exec(`git push origin ${branchName}`, {
107
+ env: gitEnvironment,
108
+ });
109
+ }
110
+ catch (error) {
111
+ logger.error(`Error pushing branch ${branchName}:`, error);
112
+ process.exit(EXIT_CODES.ERROR);
113
+ }
114
+ }
@@ -4,10 +4,10 @@ export const logger = {
4
4
  console.log(...args);
5
5
  },
6
6
  info(...args) {
7
- console.log(`${chalk.bold('[INFO]')}`, ...args);
7
+ console.log(`${chalk.cyan('[INFO]')}`, ...args);
8
8
  },
9
9
  success(...args) {
10
- console.log(`${chalk.cyan('[SUCCESS]')}`, ...args);
10
+ console.log(`${chalk.green('[SUCCESS]')}`, ...args);
11
11
  },
12
12
  warn(...args) {
13
13
  console.log(`${chalk.yellow('[WARN]')}`, ...args);
@@ -1,4 +1,6 @@
1
1
  import { DistTags, Tag } from '../types.js';
2
2
  export declare function getDistTags(packageName: string): Promise<DistTags>;
3
- export declare function publish(tag: Tag, otp: string, isDryRun: boolean, registry: string): Promise<void>;
3
+ export declare function publish(tag: Tag, otp: string, isDryRun: boolean, ignoreScripts: boolean, registry: string): Promise<void>;
4
+ export declare function updateDistTag(packageName: string, version: string, tag: string, otp: string, isDryRun: boolean, registry: string): Promise<void>;
4
5
  export declare function updateNextTag(packageName: string, newVersion: string, otp: string, isDryRun: boolean, registry: string): Promise<void>;
6
+ export declare function updatePreviousTag(packageName: string, oldLatestVersion: string, otp: string, isDryRun: boolean, registry: string): Promise<void>;
package/src/utils/npm.js CHANGED
@@ -9,7 +9,7 @@ export async function getDistTags(packageName) {
9
9
  const distTags = stdout.trim();
10
10
  return JSON.parse(distTags);
11
11
  }
12
- export async function publish(tag, otp, isDryRun, registry) {
12
+ export async function publish(tag, otp, isDryRun, ignoreScripts, registry) {
13
13
  logger.log(`\nPublishing to ${tag}...`);
14
14
  logger.log('-'.repeat(50));
15
15
  logger.log('\n');
@@ -25,6 +25,9 @@ export async function publish(tag, otp, isDryRun, registry) {
25
25
  if (isDryRun) {
26
26
  commandArgs.push('--dry-run');
27
27
  }
28
+ if (ignoreScripts) {
29
+ commandArgs.push('--ignore-scripts');
30
+ }
28
31
  return new Promise((resolve, reject) => {
29
32
  const childProcess = spawn('npm', commandArgs, {
30
33
  stdio: 'inherit',
@@ -32,7 +35,7 @@ export async function publish(tag, otp, isDryRun, registry) {
32
35
  });
33
36
  childProcess.on('close', code => {
34
37
  if (code !== EXIT_CODES.SUCCESS) {
35
- reject();
38
+ reject(new Error(`npm publish failed with exit code ${code}`));
36
39
  }
37
40
  else {
38
41
  resolve();
@@ -40,14 +43,14 @@ export async function publish(tag, otp, isDryRun, registry) {
40
43
  });
41
44
  });
42
45
  }
43
- export async function updateNextTag(packageName, newVersion, otp, isDryRun, registry) {
46
+ export async function updateDistTag(packageName, version, tag, otp, isDryRun, registry) {
44
47
  logger.log();
45
- logger.log(`Updating ${TAG.NEXT} tag...`);
48
+ logger.log(`Updating ${tag} tag to ${version}...`);
46
49
  const commandArgs = [
47
50
  'dist-tag',
48
51
  'add',
49
- `${packageName}@${newVersion}`,
50
- TAG.NEXT,
52
+ `${packageName}@${version}`,
53
+ tag,
51
54
  '--registry',
52
55
  registry,
53
56
  '--otp',
@@ -63,13 +66,19 @@ export async function updateNextTag(packageName, newVersion, otp, isDryRun, regi
63
66
  const childProcess = spawn('npm', commandArgs, { stdio: 'inherit' });
64
67
  childProcess.on('close', code => {
65
68
  if (code !== EXIT_CODES.SUCCESS) {
66
- reject();
69
+ reject(new Error(`npm dist-tag add failed with exit code ${code}`));
67
70
  }
68
71
  else {
69
- logger.success(`${TAG.NEXT} tag updated successfully`);
72
+ logger.success(`${tag} tag updated successfully`);
70
73
  resolve();
71
74
  }
72
75
  });
73
76
  }
74
77
  });
75
78
  }
79
+ export async function updateNextTag(packageName, newVersion, otp, isDryRun, registry) {
80
+ return updateDistTag(packageName, newVersion, TAG.NEXT, otp, isDryRun, registry);
81
+ }
82
+ export async function updatePreviousTag(packageName, oldLatestVersion, otp, isDryRun, registry) {
83
+ return updateDistTag(packageName, oldLatestVersion, TAG.PREVIOUS, otp, isDryRun, registry);
84
+ }