@hubspot/npm-scripts 0.0.6-beta.0 → 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.
package/src/release.js CHANGED
@@ -7,31 +7,50 @@ import fs from 'fs-extra';
7
7
  import { logger } from './utils/logging.js';
8
8
  import { EXIT_CODES } from './utils/process.js';
9
9
  import { DEFAULT_MAIN_BRANCH, INCREMENT, PRERELEASE_IDENTIFIER, TAG, TAG_OPTIONS, VERSION_INCREMENT_OPTIONS, } from './constants/release.js';
10
- import { gitCleanup, getCurrentGitBranch } from './utils/git.js';
11
- import { getDistTags, publish, updateNextTag } from './utils/npm.js';
10
+ import { getCurrentGitBranch, gitCleanup } from './utils/git.js';
11
+ import { getDistTags, publish, updateNextTag, updatePreviousTag, } from './utils/npm.js';
12
12
  import { confirm, input } from './utils/prompting.js';
13
13
  const exec = promisify(_exec);
14
- function buildHandler({ build, postLatestRelease, packageName, localVersion, registry, repositoryUrl, mainBranch, }) {
15
- return async function handler({ versionIncrement, tag, dryRun, }) {
14
+ function buildHandler({ build, postLatestRelease, packageName, localVersion, registry, repositoryUrl, mainBranch, previousBranch, ignoreScripts, }) {
15
+ return async function handler({ versionIncrement, tag, dryRun, skipBranchValidation, skipVersionCheck, }) {
16
16
  const branch = await getCurrentGitBranch();
17
17
  const isExperimental = tag === TAG.EXPERIMENTAL;
18
+ const isPrevious = tag === TAG.PREVIOUS;
18
19
  const isDryRun = Boolean(dryRun);
19
- if (isExperimental && branch === mainBranch) {
20
- logger.error(`Releases to experimental tag cannot be published from the ${mainBranch} branch`);
20
+ if (isPrevious && !previousBranch) {
21
+ logger.error('Cannot release to previous tag: previousBranch is not configured');
21
22
  process.exit(EXIT_CODES.ERROR);
22
23
  }
23
- else if (!isExperimental && branch !== mainBranch) {
24
- logger.error(`Releases to latest and next tags can only be published from the ${mainBranch} branch`);
25
- process.exit(EXIT_CODES.ERROR);
24
+ if (!skipBranchValidation) {
25
+ if (isExperimental &&
26
+ (branch === mainBranch || branch === previousBranch)) {
27
+ logger.error(`Releases to experimental tag cannot be published from the ${branch} branch`);
28
+ process.exit(EXIT_CODES.ERROR);
29
+ }
30
+ else if (isPrevious && branch !== previousBranch) {
31
+ logger.error(`Releases to previous tag can only be published from the ${previousBranch} branch`);
32
+ process.exit(EXIT_CODES.ERROR);
33
+ }
34
+ else if (!isExperimental && !isPrevious && branch !== mainBranch) {
35
+ logger.error(`Releases to latest and next tags can only be published from the ${mainBranch} branch`);
36
+ process.exit(EXIT_CODES.ERROR);
37
+ }
26
38
  }
27
- if (tag === TAG.LATEST && versionIncrement === INCREMENT.PRERELEASE) {
28
- logger.error('Invalid release: cannot increment prerelease number on latest tag.');
39
+ if ((tag === TAG.LATEST || tag === TAG.PREVIOUS) &&
40
+ versionIncrement === INCREMENT.PRERELEASE) {
41
+ logger.error(`Invalid release: cannot increment prerelease number on ${tag} tag.`);
29
42
  process.exit(EXIT_CODES.ERROR);
30
43
  }
31
- const { next: currentNextTag, experimental: currentExperimentalTag } = await getDistTags(packageName);
32
- if (!isExperimental && currentNextTag !== localVersion) {
33
- logger.error(`Local package.json version ${localVersion} is out of sync with published version ${currentNextTag}`);
34
- process.exit(EXIT_CODES.ERROR);
44
+ const { latest: currentLatestTag, next: currentNextTag, experimental: currentExperimentalTag, previous: currentPreviousTag, } = await getDistTags(packageName);
45
+ if (!skipVersionCheck) {
46
+ if (!isExperimental && !isPrevious && currentNextTag !== localVersion) {
47
+ logger.error(`Local package.json version ${localVersion} is out of sync with published version ${currentNextTag}`);
48
+ process.exit(EXIT_CODES.ERROR);
49
+ }
50
+ if (isPrevious && currentPreviousTag !== localVersion) {
51
+ logger.error(`Local package.json version ${localVersion} is out of sync with published version ${currentPreviousTag}`);
52
+ process.exit(EXIT_CODES.ERROR);
53
+ }
35
54
  }
36
55
  const currentVersion = isExperimental
37
56
  ? currentExperimentalTag
@@ -39,7 +58,9 @@ function buildHandler({ build, postLatestRelease, packageName, localVersion, reg
39
58
  const prereleaseIdentifier = isExperimental
40
59
  ? PRERELEASE_IDENTIFIER.EXPERIMENTAL
41
60
  : PRERELEASE_IDENTIFIER.NEXT;
42
- const incrementType = tag === TAG.LATEST || versionIncrement === INCREMENT.PRERELEASE
61
+ const incrementType = tag === TAG.LATEST ||
62
+ tag === TAG.PREVIOUS ||
63
+ versionIncrement === INCREMENT.PRERELEASE
43
64
  ? versionIncrement
44
65
  : `pre${versionIncrement}`;
45
66
  const newVersion = semver.inc(currentVersion, incrementType, prereleaseIdentifier);
@@ -59,10 +80,6 @@ function buildHandler({ build, postLatestRelease, packageName, localVersion, reg
59
80
  if (!shouldRelease) {
60
81
  process.exit(EXIT_CODES.SUCCESS);
61
82
  }
62
- if (branch === mainBranch && !dryRun) {
63
- logger.log(`Creating a temporary branch '${tempBranch}' for the release`);
64
- await exec(`git checkout -b ${tempBranch}`);
65
- }
66
83
  if (tag === TAG.LATEST &&
67
84
  !localVersion.includes(PRERELEASE_IDENTIFIER.NEXT)) {
68
85
  const proceedWithoutBetaRelease = await confirm({
@@ -74,6 +91,11 @@ function buildHandler({ build, postLatestRelease, packageName, localVersion, reg
74
91
  process.exit(EXIT_CODES.SUCCESS);
75
92
  }
76
93
  }
94
+ if ((branch === mainBranch || branch === previousBranch) && !dryRun) {
95
+ logger.log(`Creating a temporary branch '${tempBranch}' for the release`);
96
+ await exec(`git checkout -b ${tempBranch}`);
97
+ }
98
+ const onTempBranch = (branch === mainBranch || branch === previousBranch) && !isDryRun;
77
99
  logger.log(`\nUpdating version to ${newVersion}...`);
78
100
  if (isExperimental) {
79
101
  await exec(`yarn version --no-git-tag-version --new-version ${newVersion}`);
@@ -82,11 +104,22 @@ function buildHandler({ build, postLatestRelease, packageName, localVersion, reg
82
104
  await exec(`yarn version --new-version ${newVersion}`);
83
105
  }
84
106
  logger.success('Version updated successfully \n');
85
- if (build && typeof build === 'function') {
86
- await build();
107
+ try {
108
+ if (build && typeof build === 'function') {
109
+ await build();
110
+ }
111
+ else {
112
+ logger.log('Installing dependencies...');
113
+ await exec('yarn');
114
+ logger.log('Building...');
115
+ await exec(`yarn build`);
116
+ }
87
117
  }
88
- else {
89
- await exec(`yarn build`);
118
+ catch (e) {
119
+ logger.error(e);
120
+ logger.error('Build failed. Cleaning up...');
121
+ await gitCleanup(newVersion, !isExperimental, onTempBranch ? tempBranch : undefined, onTempBranch ? branch : undefined);
122
+ process.exit(EXIT_CODES.ERROR);
90
123
  }
91
124
  let otp = '';
92
125
  if (!isDryRun) {
@@ -110,12 +143,12 @@ function buildHandler({ build, postLatestRelease, packageName, localVersion, reg
110
143
  logger.log('\nDry run: skipping one-time password entry');
111
144
  }
112
145
  try {
113
- await publish(tag, otp, isDryRun, registry);
146
+ await publish(tag, otp, isDryRun, ignoreScripts || false, registry);
114
147
  }
115
148
  catch (e) {
116
149
  logger.error(e);
117
- logger.error('An error occurred while releasing the CLI. Correct the error and re-run `yarn build`.');
118
- await gitCleanup(newVersion, !isExperimental);
150
+ logger.error('An error occurred while releasing this package. Correct the error and re-run `yarn build`.');
151
+ await gitCleanup(newVersion, !isExperimental, onTempBranch ? tempBranch : undefined, onTempBranch ? branch : undefined);
119
152
  process.exit(EXIT_CODES.ERROR);
120
153
  }
121
154
  const gitCommand = `git push --atomic origin ${tempBranch} v${newVersion}`;
@@ -128,6 +161,15 @@ function buildHandler({ build, postLatestRelease, packageName, localVersion, reg
128
161
  logger.log(`npm dist-tag add ${packageName}@${newVersion} ${TAG.NEXT}`);
129
162
  logger.log(gitCommand);
130
163
  }
164
+ if (versionIncrement === INCREMENT.MAJOR) {
165
+ try {
166
+ await updatePreviousTag(packageName, currentLatestTag, otp, isDryRun, registry);
167
+ }
168
+ catch (e) {
169
+ logger.error(`An error occurred while updating the ${TAG.PREVIOUS} tag. To finish this release, run the following command:`);
170
+ logger.log(`npm dist-tag add ${packageName}@${currentLatestTag} ${TAG.PREVIOUS}`);
171
+ }
172
+ }
131
173
  }
132
174
  if (isDryRun) {
133
175
  await gitCleanup(newVersion, !isExperimental);
@@ -144,14 +186,17 @@ function buildHandler({ build, postLatestRelease, packageName, localVersion, reg
144
186
  logger.log(`\nPushing changes to Github...`);
145
187
  await exec(gitCommand);
146
188
  logger.log(`Changes pushed successfully`);
147
- await open(`${repositoryUrl}/compare/${mainBranch}...${tempBranch}`);
189
+ const baseBranch = isPrevious ? previousBranch : mainBranch;
190
+ await open(`${repositoryUrl}/compare/${baseBranch}...${tempBranch}`);
148
191
  }
149
192
  logger.success(`${packageName} version ${newVersion} published successfully`);
150
193
  logger.log(`https://www.npmjs.com/package/${packageName}?activeTab=versions`);
151
- if (tag === TAG.LATEST) {
194
+ if (tag === TAG.LATEST || tag === TAG.PREVIOUS) {
152
195
  logger.log(`\nRemember to create a new release on Github!`);
153
196
  await open(`${repositoryUrl}/releases/new`);
154
- if (postLatestRelease && typeof postLatestRelease === 'function') {
197
+ if (tag === TAG.LATEST &&
198
+ postLatestRelease &&
199
+ typeof postLatestRelease === 'function') {
155
200
  await postLatestRelease({ newVersion, dryRun });
156
201
  }
157
202
  }
@@ -177,6 +222,16 @@ async function builder(yargs) {
177
222
  default: false,
178
223
  type: 'boolean',
179
224
  },
225
+ skipBranchValidation: {
226
+ describe: 'Bypass the branch validation check',
227
+ default: false,
228
+ type: 'boolean',
229
+ },
230
+ skipVersionCheck: {
231
+ describe: 'Bypass checking that the local version matches the published version',
232
+ default: false,
233
+ type: 'boolean',
234
+ },
180
235
  });
181
236
  }
182
237
  export function buildReleaseScript({ packageJsonLocation, buildHandlerOptions, }) {
@@ -0,0 +1,5 @@
1
+ import { BuildRepoSyncScriptOptions, RepoSyncArguments } from './types.js';
2
+ export declare function handleRepoSync({ sourceDirectory, targetRepositoryUrl, excludePatterns, buildCommitMessage, internalMainBranch, externalMainBranch, version, dryRun, sshKeyPath, }: BuildRepoSyncScriptOptions & RepoSyncArguments): Promise<void>;
3
+ export declare function buildRepoSyncScript({ buildHandlerOptions, }: {
4
+ buildHandlerOptions: BuildRepoSyncScriptOptions;
5
+ }): void;
@@ -0,0 +1,141 @@
1
+ import yargs from 'yargs';
2
+ import open from 'open';
3
+ import fs from 'fs-extra';
4
+ import path from 'path';
5
+ import { logger } from './utils/logging.js';
6
+ import { EXIT_CODES } from './utils/process.js';
7
+ import { DEFAULT_INTERNAL_MAIN_BRANCH, DEFAULT_EXTERNAL_MAIN_BRANCH, SYNC_BRANCH_PREFIX, TEMP_SYNC_DIR, } from './constants/repo-sync.js';
8
+ import { checkoutBranch, cloneRepo, commitChanges, createBranch, getCurrentGitBranch, getGitEnvWithSshKey, pushBranch, } from './utils/git.js';
9
+ import { copyFiles } from './utils/filesystem.js';
10
+ import { confirm } from './utils/prompting.js';
11
+ export async function handleRepoSync({ sourceDirectory, 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;
17
+ }
18
+ const originalRepoPath = sourceDirectory
19
+ ? path.resolve(sourceDirectory)
20
+ : process.cwd();
21
+ let tempDir = '';
22
+ try {
23
+ logger.log(`Starting sync to target repository: ${targetRepositoryUrl}...`);
24
+ if (dryRun) {
25
+ logger.log();
26
+ logger.info('(DRY RUN) The script will not push any changes.');
27
+ logger.log();
28
+ }
29
+ // Ensure we are on the master branch of the current repository (or continue with confirmation)
30
+ const currentBranch = await getCurrentGitBranch();
31
+ if (currentBranch !== internalMainBranch) {
32
+ const shouldCheckout = await confirm({
33
+ message: `You are on ${currentBranch}. Sync from ${internalMainBranch} branch instead?`,
34
+ });
35
+ if (shouldCheckout) {
36
+ await checkoutBranch(internalMainBranch, true);
37
+ }
38
+ }
39
+ // Create temporary directory
40
+ tempDir = path.join(originalRepoPath, TEMP_SYNC_DIR);
41
+ await fs.ensureDir(tempDir);
42
+ // Get git environment with ssh key to use for target repository operations
43
+ const gitEnvironment = await getGitEnvWithSshKey(sshKeyPath);
44
+ // Clone target repo
45
+ const targetRepoPath = await cloneRepo(targetRepositoryUrl, tempDir, gitEnvironment);
46
+ // Change to target repo directory
47
+ process.chdir(targetRepoPath);
48
+ // Create sync branch
49
+ const syncBranch = `${SYNC_BRANCH_PREFIX}-${version}`;
50
+ await createBranch(syncBranch);
51
+ // Copy files from current repository to target repository tmep dir
52
+ await copyFiles(originalRepoPath, targetRepoPath, excludePatterns);
53
+ // Commit changes
54
+ await commitChanges(buildCommitMessage(version));
55
+ if (dryRun) {
56
+ logger.log();
57
+ logger.info(`(DRY RUN) Exiting without pushing changes to ${targetRepositoryUrl}. Preview the files in ${tempDir}`);
58
+ process.exit(EXIT_CODES.SUCCESS);
59
+ }
60
+ const pushConfirmation = await confirm({
61
+ message: `Push changes to ${targetRepositoryUrl}?`,
62
+ default: true,
63
+ });
64
+ if (!pushConfirmation) {
65
+ logger.log(`Exiting without pushing changes to ${targetRepositoryUrl}.`);
66
+ process.exit(EXIT_CODES.SUCCESS);
67
+ }
68
+ // Push to target repository
69
+ await pushBranch(syncBranch, gitEnvironment);
70
+ // Create pull request
71
+ const prUrl = `${targetRepositoryUrl}/compare/${externalMainBranch}...${syncBranch}?expand=1`;
72
+ logger.log();
73
+ logger.log('Opening target repository sync branch pull request URL in browser...');
74
+ open(prUrl);
75
+ logger.log();
76
+ logger.log(`Pull Request URL: ${prUrl}`);
77
+ logger.success('Sync to target repository completed successfully');
78
+ }
79
+ catch (error) {
80
+ logger.error('Error syncing to target repository:', error);
81
+ process.exit(EXIT_CODES.ERROR);
82
+ }
83
+ finally {
84
+ // Cleanup
85
+ if (tempDir && !dryRun) {
86
+ await fs.remove(tempDir);
87
+ }
88
+ process.chdir(originalRepoPath);
89
+ }
90
+ }
91
+ function buildHandler({ sourceDirectory, targetRepositoryUrl, excludePatterns, buildCommitMessage, internalMainBranch, externalMainBranch, }) {
92
+ return async function handler({ version, dryRun, sshKeyPath, }) {
93
+ await handleRepoSync({
94
+ sourceDirectory,
95
+ targetRepositoryUrl,
96
+ excludePatterns,
97
+ buildCommitMessage,
98
+ internalMainBranch,
99
+ externalMainBranch,
100
+ version,
101
+ dryRun,
102
+ sshKeyPath,
103
+ });
104
+ };
105
+ }
106
+ async function builder(yargs) {
107
+ return yargs.options({
108
+ version: {
109
+ alias: 'v',
110
+ demandOption: true,
111
+ describe: 'Version label for the sync branch',
112
+ type: 'string',
113
+ },
114
+ dryRun: {
115
+ alias: 'd',
116
+ describe: 'Run through the sync process without pushing changes',
117
+ default: false,
118
+ type: 'boolean',
119
+ },
120
+ sshKeyPath: {
121
+ alias: 'ssh-key',
122
+ describe: 'Path to the SSH key to use for commands targeting the destination repository',
123
+ type: 'string',
124
+ },
125
+ });
126
+ }
127
+ export function buildRepoSyncScript({ buildHandlerOptions, }) {
128
+ try {
129
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
130
+ yargs(process.argv.slice(2))
131
+ .scriptName('yarn')
132
+ .usage('Hubspot repo sync script')
133
+ .command('repo-sync', `Syncs changes from the current repository to a target repository`, builder, buildHandler(buildHandlerOptions))
134
+ .version(false)
135
+ .help().argv;
136
+ }
137
+ catch (e) {
138
+ logger.error(e);
139
+ process.exit(EXIT_CODES.ERROR);
140
+ }
141
+ }
package/src/types.d.ts CHANGED
@@ -3,11 +3,19 @@ export type ReleaseArguments = {
3
3
  versionIncrement: (typeof VERSION_INCREMENT_OPTIONS)[number];
4
4
  tag: (typeof TAG_OPTIONS)[number];
5
5
  dryRun: boolean;
6
+ skipBranchValidation: boolean;
7
+ skipVersionCheck: boolean;
8
+ };
9
+ export type RepoSyncArguments = {
10
+ version: string;
11
+ dryRun: boolean;
12
+ sshKeyPath?: string;
6
13
  };
7
14
  export type DistTags = {
8
15
  [TAG.LATEST]: string;
9
16
  [TAG.NEXT]: string;
10
17
  [TAG.EXPERIMENTAL]: string;
18
+ [TAG.PREVIOUS]: string;
11
19
  };
12
20
  export type Tag = (typeof TAG_OPTIONS)[number];
13
21
  export interface BuildReleaseScriptBase {
@@ -17,13 +25,23 @@ export interface BuildReleaseScriptBase {
17
25
  dryRun: boolean;
18
26
  }) => Promise<void> | void;
19
27
  repositoryUrl: string;
28
+ ignoreScripts?: boolean;
20
29
  mainBranch?: string;
30
+ previousBranch?: string;
21
31
  }
22
32
  export interface BuildReleaseScriptOptions extends BuildReleaseScriptBase {
23
33
  packageName: string;
24
34
  localVersion: string;
25
35
  registry: string;
26
36
  }
37
+ export interface BuildRepoSyncScriptOptions {
38
+ sourceDirectory?: string;
39
+ targetRepositoryUrl: string;
40
+ buildCommitMessage: (version: string) => string;
41
+ excludePatterns?: string[];
42
+ internalMainBranch?: string;
43
+ externalMainBranch?: string;
44
+ }
27
45
  export interface PackageJson {
28
46
  name: string;
29
47
  version: 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 {};