@hubspot/npm-scripts 0.0.6 → 0.1.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/README.md CHANGED
@@ -11,6 +11,7 @@ The linking tool helps manage symlinked HubSpot packages in your development env
11
11
  #### Usage
12
12
 
13
13
  It can be used via npx
14
+
14
15
  ```bash
15
16
  npx @hubspot/npm-scripts hubspot-linking
16
17
  ```
@@ -64,8 +65,8 @@ buildReleaseScript({
64
65
  },
65
66
  postLatestRelease: async () => {
66
67
  // Optional function to run after latest releases
67
- }
68
- }
68
+ },
69
+ },
69
70
  });
70
71
  ```
71
72
 
@@ -113,3 +114,67 @@ yarn release -v=patch -t=latest -d
113
114
  - **GitHub integration**: Opens PR and release pages automatically
114
115
  - **Rollback support**: Cleans up on failure
115
116
 
117
+ ### Repo Sync Script Builder (`buildRepoSyncScript`)
118
+
119
+ A utility function that creates a script to sync changes from an internal repository to a target repository (e.g., syncing internal packages to public GitHub).
120
+
121
+ #### Usage
122
+
123
+ Create a repo sync script file (e.g., `scripts/repo-sync.ts`):
124
+
125
+ ```typescript
126
+ import { buildRepoSyncScript } from '@hubspot/npm-scripts';
127
+
128
+ buildRepoSyncScript({
129
+ buildHandlerOptions: {
130
+ targetRepositoryOrg: 'https://github.com/your-org',
131
+ targetRepositoryName: 'public-repo',
132
+ buildCommitMessage: version =>
133
+ `Sync changes from internal repo for version ${version}`,
134
+ mainBranch: 'main', // optional, defaults to 'master'
135
+ excludePatterns: [
136
+ // optional, custom patterns to exclude from sync
137
+ 'internal-only-file.ts',
138
+ 'tests',
139
+ 'tests/**',
140
+ ],
141
+ },
142
+ });
143
+ ```
144
+
145
+ **NOTE:** The sync script will always ignore the `hs-temp-repo-sync` and `.git` directories
146
+
147
+ Then add to your `package.json`:
148
+
149
+ ```json
150
+ {
151
+ "scripts": {
152
+ "repo-sync": "tsx ./scripts/repo-sync.ts repo-sync"
153
+ }
154
+ }
155
+ ```
156
+
157
+ #### Repo Sync Commands
158
+
159
+ ```bash
160
+ # Sync changes to target repository
161
+ yarn repo-sync -v=1.0.0 --ssh-key=~/.ssh/id_rsa
162
+
163
+ # Dry run (test without pushing)
164
+ yarn repo-sync -v=1.0.0 -d
165
+ ```
166
+
167
+ #### Parameters
168
+
169
+ - `-v, --version`: Version to label the sync branch (required)
170
+ - `-d, --dryRun`: Run without pushing changes
171
+ - `--ssh-key`: Path to SSH key for target repository operations
172
+
173
+ #### Features
174
+
175
+ - **Branch protection**: Ensures sync happens from the correct branch
176
+ - **Automatic branching**: Creates a sync branch in the target repository
177
+ - **GitHub integration**: Opens PR page automatically after push
178
+ - **Cleanup support**: Removes temporary directories after completion
179
+
180
+ This script supports a `PUBLIC_README.md` pattern that allows you to maintain an internal readme file that does not sync to the target repo. The `PUBLIC_README.md` file will sync into the target repo as `README.md`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/npm-scripts",
3
- "version": "0.0.6",
3
+ "version": "0.1.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",
@@ -14,6 +14,7 @@
14
14
  "local-dev": "yarn build && cd dist && yarn link && cd .. && tsc -w",
15
15
  "prettier:write": "prettier --write './**/*.{ts,js,json}'",
16
16
  "release": "yarn tsx ./scripts/release.ts release",
17
+ "repo-sync": "yarn tsx ./scripts/repo-sync.ts repo-sync",
17
18
  "test": "echo \"Error: no test specified\" && exit 1"
18
19
  },
19
20
  "dependencies": {
@@ -21,6 +22,7 @@
21
22
  "chalk": "^5.6.2",
22
23
  "findup-sync": "^5.0.0",
23
24
  "fs-extra": "^11.3.2",
25
+ "minimatch": "^10.0.1",
24
26
  "open": "^10.2.0",
25
27
  "semver": "^7.7.2",
26
28
  "yargs": "17.7.2"
@@ -29,7 +31,7 @@
29
31
  "@eslint/js": "^9.36.0",
30
32
  "@types/findup-sync": "^4.0.5",
31
33
  "@types/fs-extra": "^11.0.4",
32
- "@types/node": "^24.5.2",
34
+ "@types/node": "^25.0.3",
33
35
  "@types/semver": "^7.7.1",
34
36
  "@types/yargs": "^17.0.33",
35
37
  "@typescript-eslint/eslint-plugin": "^8.44.1",
@@ -0,0 +1,4 @@
1
+ export declare const DEFAULT_MAIN_BRANCH = "master";
2
+ export declare const SYNC_BRANCH_PREFIX = "hs-repo-sync";
3
+ export declare const TEMP_SYNC_DIR = "hs-temp-repo-sync";
4
+ export declare const PUBLIC_README_PATH = "PUBLIC_README.md";
@@ -0,0 +1,4 @@
1
+ export const DEFAULT_MAIN_BRANCH = 'master';
2
+ export const SYNC_BRANCH_PREFIX = 'hs-repo-sync';
3
+ export const TEMP_SYNC_DIR = 'hs-temp-repo-sync';
4
+ export const PUBLIC_README_PATH = 'PUBLIC_README.md';
@@ -0,0 +1,5 @@
1
+ import { BuildRepoSyncScriptOptions, RepoSyncArguments } from './types.js';
2
+ export declare function handleRepoSync({ targetRepositoryUrl, excludePatterns, buildCommitMessage, mainBranch, version, dryRun, sshKeyPath, }: BuildRepoSyncScriptOptions & RepoSyncArguments): Promise<void>;
3
+ export declare function buildRepoSyncScript({ buildHandlerOptions, }: {
4
+ buildHandlerOptions: BuildRepoSyncScriptOptions;
5
+ }): void;
@@ -0,0 +1,138 @@
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_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({ targetRepositoryUrl, excludePatterns, buildCommitMessage, mainBranch, version, dryRun, sshKeyPath, }) {
12
+ if (!mainBranch) {
13
+ logger.error('Main branch is required');
14
+ process.exit(EXIT_CODES.ERROR);
15
+ }
16
+ const originalRepoPath = process.cwd();
17
+ let tempDir = '';
18
+ try {
19
+ logger.log(`Starting sync to target repository: ${targetRepositoryUrl}...`);
20
+ if (dryRun) {
21
+ logger.log();
22
+ logger.info('(DRY RUN) The script will not push any changes.');
23
+ logger.log();
24
+ }
25
+ // Ensure we are on the master branch of the current repository (or continue with confirmation)
26
+ const currentBranch = await getCurrentGitBranch();
27
+ if (currentBranch !== mainBranch) {
28
+ const shouldCheckout = await confirm({
29
+ message: `You are on ${currentBranch}. Sync from ${mainBranch} branch instead?`,
30
+ });
31
+ if (shouldCheckout) {
32
+ await checkoutBranch(mainBranch, true);
33
+ }
34
+ }
35
+ // Create temporary directory
36
+ tempDir = path.join(originalRepoPath, TEMP_SYNC_DIR);
37
+ await fs.ensureDir(tempDir);
38
+ // Get git environment with ssh key to use for target repository operations
39
+ const gitEnvironment = await getGitEnvWithSshKey(sshKeyPath);
40
+ // Clone target repo
41
+ const targetRepoPath = await cloneRepo(targetRepositoryUrl, tempDir, gitEnvironment);
42
+ // Change to target repo directory
43
+ process.chdir(targetRepoPath);
44
+ // Create sync branch
45
+ const syncBranch = `${SYNC_BRANCH_PREFIX}-${version}`;
46
+ await createBranch(syncBranch);
47
+ // Copy files from current repository to target repository tmep dir
48
+ await copyFiles(originalRepoPath, targetRepoPath, excludePatterns);
49
+ // Commit changes
50
+ await commitChanges(buildCommitMessage(version));
51
+ if (dryRun) {
52
+ logger.log();
53
+ logger.info(`(DRY RUN) Exiting without pushing changes to ${targetRepositoryUrl}. Preview the files in ${tempDir}`);
54
+ process.exit(EXIT_CODES.SUCCESS);
55
+ }
56
+ const pushConfirmation = await confirm({
57
+ message: `Push changes to ${targetRepositoryUrl}?`,
58
+ default: true,
59
+ });
60
+ if (!pushConfirmation) {
61
+ logger.log(`Exiting without pushing changes to ${targetRepositoryUrl}.`);
62
+ process.exit(EXIT_CODES.SUCCESS);
63
+ }
64
+ // Push to target repository
65
+ await pushBranch(syncBranch, gitEnvironment);
66
+ // Create pull request
67
+ const prUrl = `${targetRepositoryUrl}/compare/${mainBranch}...${syncBranch}?expand=1`;
68
+ logger.log();
69
+ logger.log('Opening target repository sync branch pull request URL in browser...');
70
+ open(prUrl);
71
+ logger.log();
72
+ logger.log(`Pull Request URL: ${prUrl}`);
73
+ logger.success('Sync to target repository completed successfully');
74
+ }
75
+ catch (error) {
76
+ logger.error('Error syncing to target repository:', error);
77
+ process.exit(EXIT_CODES.ERROR);
78
+ }
79
+ finally {
80
+ // Cleanup
81
+ if (tempDir && !dryRun) {
82
+ await fs.remove(tempDir);
83
+ }
84
+ process.chdir(originalRepoPath);
85
+ }
86
+ }
87
+ function buildHandler({ targetRepositoryUrl, excludePatterns, buildCommitMessage, mainBranch, }) {
88
+ return async function handler({ version, dryRun, sshKeyPath, }) {
89
+ await handleRepoSync({
90
+ targetRepositoryUrl,
91
+ excludePatterns,
92
+ buildCommitMessage,
93
+ mainBranch,
94
+ version,
95
+ dryRun,
96
+ sshKeyPath,
97
+ });
98
+ };
99
+ }
100
+ async function builder(yargs) {
101
+ return yargs.options({
102
+ version: {
103
+ alias: 'v',
104
+ demandOption: true,
105
+ describe: 'Version label for the sync branch',
106
+ type: 'string',
107
+ },
108
+ dryRun: {
109
+ alias: 'd',
110
+ describe: 'Run through the sync process without pushing changes',
111
+ default: false,
112
+ type: 'boolean',
113
+ },
114
+ sshKeyPath: {
115
+ alias: 'ssh-key',
116
+ describe: 'Path to the SSH key to use for commands targeting the destination repository',
117
+ type: 'string',
118
+ },
119
+ });
120
+ }
121
+ export function buildRepoSyncScript({ buildHandlerOptions, }) {
122
+ try {
123
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
124
+ yargs(process.argv.slice(2))
125
+ .scriptName('yarn')
126
+ .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
+ }))
131
+ .version(false)
132
+ .help().argv;
133
+ }
134
+ catch (e) {
135
+ logger.error(e);
136
+ process.exit(EXIT_CODES.ERROR);
137
+ }
138
+ }
package/src/types.d.ts CHANGED
@@ -4,6 +4,11 @@ export type ReleaseArguments = {
4
4
  tag: (typeof TAG_OPTIONS)[number];
5
5
  dryRun: boolean;
6
6
  };
7
+ export type RepoSyncArguments = {
8
+ version: string;
9
+ dryRun: boolean;
10
+ sshKeyPath?: string;
11
+ };
7
12
  export type DistTags = {
8
13
  [TAG.LATEST]: string;
9
14
  [TAG.NEXT]: string;
@@ -24,6 +29,12 @@ export interface BuildReleaseScriptOptions extends BuildReleaseScriptBase {
24
29
  localVersion: string;
25
30
  registry: string;
26
31
  }
32
+ export interface BuildRepoSyncScriptOptions {
33
+ targetRepositoryUrl: string;
34
+ buildCommitMessage: (version: string) => string;
35
+ excludePatterns?: string[];
36
+ mainBranch?: string;
37
+ }
27
38
  export interface PackageJson {
28
39
  name: string;
29
40
  version: string;
@@ -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);