@hubspot/npm-scripts 0.0.5 → 0.0.6-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.
@@ -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
- export declare function gitCleanup(newVersion: string, deleteTag: boolean): Promise<void>;
2
+ export declare function gitCleanup(newVersion: string, deleteTag: boolean, tempBranch?: string, originalBranch?: string): Promise<void>;
3
+ 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,14 +1,123 @@
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();
7
18
  }
8
- export async function gitCleanup(newVersion, deleteTag) {
19
+ export async function gitCleanup(newVersion, deleteTag, tempBranch, originalBranch) {
9
20
  await exec(`git reset HEAD~`);
10
21
  await exec(`git checkout .`);
11
22
  if (deleteTag) {
12
23
  await exec(`git tag -d v${newVersion}`);
13
24
  }
25
+ if (tempBranch && originalBranch) {
26
+ try {
27
+ await exec(`git checkout ${originalBranch}`);
28
+ await exec(`git branch -D ${tempBranch}`);
29
+ }
30
+ catch (e) {
31
+ logger.error(`Failed to clean up temporary branch '${tempBranch}'. You may need to delete it manually with: git branch -D ${tempBranch}`);
32
+ }
33
+ }
34
+ }
35
+ export async function getGitEnvWithSshKey(sshKeyPath) {
36
+ if (!sshKeyPath) {
37
+ sshKeyPath = await input({
38
+ message: 'Enter the SSH key path to use (leave blank to use the default):',
39
+ });
40
+ if (!sshKeyPath) {
41
+ return process.env;
42
+ }
43
+ }
44
+ return {
45
+ ...process.env,
46
+ GIT_SSH_COMMAND: `ssh -i ${sshKeyPath} -o IdentitiesOnly=yes`,
47
+ };
48
+ }
49
+ export async function cloneRepo(repoUrl, destinationDir, gitEnvironment) {
50
+ logger.log(`Cloning repository into ${destinationDir}...`);
51
+ const { host, org, repo } = getRepoPartsFromUrl(repoUrl);
52
+ const targetRepoPath = path.join(destinationDir, repo);
53
+ // Remove existing directory if it exists
54
+ try {
55
+ await fs.remove(targetRepoPath);
56
+ }
57
+ catch (error) {
58
+ // Ignore error if directory doesn't exist
59
+ }
60
+ try {
61
+ await exec(`git clone git@${host}:${org}/${repo}.git ${targetRepoPath}`, {
62
+ env: gitEnvironment,
63
+ });
64
+ }
65
+ catch (error) {
66
+ logger.error(`Error cloning repository:`, error);
67
+ process.exit(EXIT_CODES.ERROR);
68
+ }
69
+ return targetRepoPath;
70
+ }
71
+ export async function checkoutBranch(branchName, pullLatest = false) {
72
+ try {
73
+ await exec(`git checkout ${branchName}`);
74
+ if (pullLatest) {
75
+ await exec(`git pull origin ${branchName}`);
76
+ }
77
+ }
78
+ catch (error) {
79
+ logger.error(`Error checking out branch ${branchName}:`, error);
80
+ process.exit(EXIT_CODES.ERROR);
81
+ }
82
+ }
83
+ export async function createBranch(branchName) {
84
+ try {
85
+ await exec(`git checkout -b ${branchName}`);
86
+ }
87
+ catch (error) {
88
+ logger.error(`Error creating branch ${branchName}:`, error);
89
+ process.exit(EXIT_CODES.ERROR);
90
+ }
91
+ }
92
+ export async function commitChanges(commitMessage) {
93
+ // Add all changes
94
+ await exec('git add .');
95
+ // Check if there are any changes to commit
96
+ try {
97
+ const { stdout } = await exec('git status --porcelain');
98
+ if (!stdout.trim()) {
99
+ logger.log('No changes to commit');
100
+ return;
101
+ }
102
+ }
103
+ catch (error) {
104
+ logger.error('Error checking git status');
105
+ process.exit(EXIT_CODES.ERROR);
106
+ }
107
+ await exec(`git commit -m "${commitMessage}"`);
108
+ }
109
+ // ssh url: git@github.com:HubSpotEngineering/Dev-Experience-Fe-Scripts.git
110
+ // targetRepositoryOrg = https://github.com/HubSpotEngineering
111
+ // targetRepositoryName = Dev-Experience-Fe-Scripts.git
112
+ export async function pushBranch(branchName, gitEnvironment) {
113
+ logger.log(`Pushing branch ${branchName}...`);
114
+ try {
115
+ await exec(`git push origin ${branchName}`, {
116
+ env: gitEnvironment,
117
+ });
118
+ }
119
+ catch (error) {
120
+ logger.error(`Error pushing branch ${branchName}:`, error);
121
+ process.exit(EXIT_CODES.ERROR);
122
+ }
14
123
  }
@@ -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
+ }