Skip to content

Commit 2020d2c

Browse files
Merge pull request #6789 from BitGo/BTC-2411
feat: replace CommonJS imports with ES module imports
2 parents 6d00970 + 3a4148d commit 2020d2c

File tree

8 files changed

+125
-50
lines changed

8 files changed

+125
-50
lines changed

scripts/pack-scoped.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44
* The archive can be used with `npm install path/to/tgz` to test the package locally.
55
*/
66

7-
import * as fs from 'fs';
8-
import * as execa from 'execa';
9-
import * as mpath from 'path';
10-
import * as yargs from 'yargs';
7+
import fs from 'fs';
8+
import execa from 'execa';
9+
import mpath from 'path';
10+
import yargs from 'yargs';
1111
import {
1212
walk,
1313
getLernaModules,

scripts/prepare-release.ts

Lines changed: 62 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import * as assert from 'node:assert';
1+
import assert from 'node:assert';
22
import { readFileSync, writeFileSync } from 'fs';
3-
import * as path from 'path';
3+
import path from 'path';
44
import { inc, lt } from 'semver';
5-
import * as yargs from 'yargs';
5+
import yargs from 'yargs';
66
import { hideBin } from 'yargs/helpers';
77

88
import {
@@ -15,10 +15,17 @@ import {
1515
LernaModule,
1616
} from './prepareRelease';
1717

18-
function replacePackageScopes(rootDir: string, lernaModules: LernaModule[], targetScope: string): number {
18+
function replacePackageScopes(
19+
rootDir: string,
20+
lernaModules: LernaModule[],
21+
targetScope: string,
22+
): number {
1923
let filesChanged = 0;
2024
// replace all @bitgo packages & source code with alternate SCOPE
21-
const filePaths = [...walk(path.join(rootDir, 'modules')), ...walk(path.join(rootDir, 'webpack'))];
25+
const filePaths = [
26+
...walk(path.join(rootDir, 'modules')),
27+
...walk(path.join(rootDir, 'webpack')),
28+
];
2229
const moduleNames = lernaModules.map(({ name }) => name);
2330

2431
filePaths.forEach((file) => {
@@ -31,9 +38,14 @@ function replacePackageScopes(rootDir: string, lernaModules: LernaModule[], targ
3138
// we must manually set one
3239
function replaceBitGoPackageScope(rootDir: string, targetScope: string): void {
3340
const cwd = path.join(rootDir, 'modules', 'bitgo');
34-
const json = JSON.parse(readFileSync(path.join(cwd, 'package.json'), { encoding: 'utf-8' }));
41+
const json = JSON.parse(
42+
readFileSync(path.join(cwd, 'package.json'), { encoding: 'utf-8' }),
43+
);
3544
json.name = `${targetScope}/bitgo`;
36-
writeFileSync(path.join(cwd, 'package.json'), JSON.stringify(json, null, 2) + '\n');
45+
writeFileSync(
46+
path.join(cwd, 'package.json'),
47+
JSON.stringify(json, null, 2) + '\n',
48+
);
3749
}
3850

3951
/**
@@ -42,7 +54,11 @@ function replaceBitGoPackageScope(rootDir: string, targetScope: string): void {
4254
* @returns The parsed package.json content
4355
*/
4456
function readModulePackageJson(module: LernaModule): any {
45-
return JSON.parse(readFileSync(path.join(module.location, 'package.json'), { encoding: 'utf-8' }));
57+
return JSON.parse(
58+
readFileSync(path.join(module.location, 'package.json'), {
59+
encoding: 'utf-8',
60+
}),
61+
);
4662
}
4763

4864
/**
@@ -51,7 +67,10 @@ function readModulePackageJson(module: LernaModule): any {
5167
* @param json The content to write
5268
*/
5369
function writeModulePackageJson(module: LernaModule, json: any): void {
54-
writeFileSync(path.join(module.location, 'package.json'), JSON.stringify(json, null, 2) + '\n');
70+
writeFileSync(
71+
path.join(module.location, 'package.json'),
72+
JSON.stringify(json, null, 2) + '\n',
73+
);
5574
}
5675

5776
/**
@@ -67,7 +86,7 @@ function incrementVersionsForModuleLocation(
6786
preid: string,
6887
module: LernaModule,
6988
tags: DistTags | undefined,
70-
allModules: LernaModule[]
89+
allModules: LernaModule[],
7190
): string | undefined {
7291
const json = readModulePackageJson(module);
7392

@@ -77,15 +96,20 @@ function incrementVersionsForModuleLocation(
7796
if (tags[preid]) {
7897
const version = tags[preid].split('-');
7998
const latest = tags?.latest?.split('-') ?? ['0.0.0'];
80-
prevTag = lt(version[0], latest[0]) ? `${tags.latest}-${preid}` : tags[preid];
99+
prevTag = lt(version[0], latest[0])
100+
? `${tags.latest}-${preid}`
101+
: tags[preid];
81102
} else {
82103
prevTag = `${tags.latest}-${preid}`;
83104
}
84105
}
85106

86107
if (prevTag) {
87108
const next = inc(prevTag, 'prerelease', undefined, preid);
88-
assert(typeof next === 'string', `Failed to increment version for ${json.name} prevTag=${prevTag}`);
109+
assert(
110+
typeof next === 'string',
111+
`Failed to increment version for ${json.name} prevTag=${prevTag}`,
112+
);
89113
console.log(`Setting next version for ${json.name} to ${next}`);
90114
json.version = next;
91115
writeModulePackageJson(module, json);
@@ -119,15 +143,26 @@ function incrementVersionsForModuleLocation(
119143
* @param {String} preid - The prerelease identifier
120144
* @param {LernaModule[]} lernaModules - The modules to update
121145
*/
122-
async function incrementVersions(preid: string, lernaModules: LernaModule[]): Promise<void> {
146+
async function incrementVersions(
147+
preid: string,
148+
lernaModules: LernaModule[],
149+
): Promise<void> {
123150
const distTags = await getDistTagsForModules(lernaModules);
124151

125152
for (const m of lernaModules) {
126153
try {
127-
incrementVersionsForModuleLocation(preid, m, distTags.get(m), lernaModules);
154+
incrementVersionsForModuleLocation(
155+
preid,
156+
m,
157+
distTags.get(m),
158+
lernaModules,
159+
);
128160
} catch (e) {
129161
// it's not necessarily a blocking error. Let lerna try and publish anyways
130-
console.warn(`Couldn't set next version for ${m.name} at ${m.location}`, e);
162+
console.warn(
163+
`Couldn't set next version for ${m.name} at ${m.location}`,
164+
e,
165+
);
131166
}
132167
}
133168
}
@@ -151,7 +186,9 @@ yargs(hideBin(process.argv))
151186
.option('root-dir', {
152187
type: 'string',
153188
description: 'Root directory of the repository',
154-
default: process.env.BITGO_PREPARE_RELEASE_ROOT_DIR || path.join(__dirname, '..'),
189+
default:
190+
process.env.BITGO_PREPARE_RELEASE_ROOT_DIR ||
191+
path.join(__dirname, '..'),
155192
});
156193
},
157194
async (argv) => {
@@ -166,7 +203,11 @@ yargs(hideBin(process.argv))
166203
const lernaModules = await getLernaModules();
167204

168205
// Replace package scopes
169-
const filesChanged = replacePackageScopes(rootDir, lernaModules, targetScope);
206+
const filesChanged = replacePackageScopes(
207+
rootDir,
208+
lernaModules,
209+
targetScope,
210+
);
170211

171212
// Replace BitGo package scope
172213
replaceBitGoPackageScope(rootDir, targetScope);
@@ -178,14 +219,16 @@ yargs(hideBin(process.argv))
178219
console.log(`Successfully re-targeted ${filesChanged} files.`);
179220
process.exit(0);
180221
} else {
181-
console.error('No files were changed, something must have gone wrong.');
222+
console.error(
223+
'No files were changed, something must have gone wrong.',
224+
);
182225
process.exit(1);
183226
}
184227
} catch (error) {
185228
console.error('Error in prepare-release script:', error);
186229
process.exit(1);
187230
}
188-
}
231+
},
189232
)
190233
.help()
191234
.alias('help', 'h')

scripts/prepareRelease/distTags.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { readFileSync, writeFileSync, existsSync } from 'fs';
2-
import * as path from 'path';
2+
import path from 'path';
33
import { LernaModule } from './getLernaModules';
44

55
export type DistTags = Record<string, string>;

scripts/prepareRelease/getLernaModules.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import * as execa from 'execa';
1+
import execa from 'execa';
22

33
export type LernaModule = {
44
name: string;
@@ -19,7 +19,11 @@ function getLernaRunner(lernaPath: string) {
1919
}
2020

2121
export async function getLernaModules(): Promise<LernaModule[]> {
22-
const { stdout: lernaBinary } = await execa('yarn', ['bin', 'lerna'], { cwd: process.cwd() });
22+
const { stdout: lernaBinary } = await execa('yarn', ['bin', 'lerna'], {
23+
cwd: process.cwd(),
24+
});
2325
const lerna = getLernaRunner(lernaBinary);
24-
return JSON.parse(await lerna('list', ['--loglevel', 'silent', '--json', '--all']));
26+
return JSON.parse(
27+
await lerna('list', ['--loglevel', 'silent', '--json', '--all']),
28+
);
2529
}

scripts/prepareRelease/walk.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import * as path from 'path';
1+
import path from 'path';
22
import { readdirSync, statSync } from 'fs';
33

44
export const walk = (dir: string): string[] => {

scripts/tests/prepareRelease/util.ts

Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import * as fs from 'fs';
2-
import * as path from 'path';
3-
import * as os from 'os';
1+
import fs from 'fs';
2+
import path from 'path';
3+
import os from 'os';
44
import { execFileSync } from 'child_process';
5-
import * as tmp from 'tmp';
5+
import tmp from 'tmp';
66

77
/**
88
* Helper function to execute git commands and return output as string
@@ -57,9 +57,13 @@ export function symlinkNodeModules(targetDir: string): void {
5757
if (fs.existsSync(sourceNodeModules)) {
5858
// Create symlink
5959
fs.symlinkSync(sourceNodeModules, targetNodeModules, 'junction');
60-
console.log(`Symlinked node_modules from ${sourceNodeModules} to ${targetNodeModules}`);
60+
console.log(
61+
`Symlinked node_modules from ${sourceNodeModules} to ${targetNodeModules}`,
62+
);
6163
} else {
62-
console.warn('Source node_modules directory not found, skipping symlink creation');
64+
console.warn(
65+
'Source node_modules directory not found, skipping symlink creation',
66+
);
6367
}
6468
}
6569

@@ -74,7 +78,9 @@ export function createShallowClone(commitHash: string, tempDir: string): void {
7478
const repoDir = execGitCapture(['rev-parse', '--show-toplevel']).trim();
7579

7680
if (fs.existsSync(tempDir)) {
77-
console.log(`Directory ${tempDir} already exists, ensuring it's at commit ${commitHash}`);
81+
console.log(
82+
`Directory ${tempDir} already exists, ensuring it's at commit ${commitHash}`,
83+
);
7884

7985
try {
8086
// Check if it's a git repository
@@ -89,7 +95,9 @@ export function createShallowClone(commitHash: string, tempDir: string): void {
8995
// Clean the working directory to remove any untracked files
9096
execGit(['clean', '-fdx'], tempDir);
9197

92-
console.log(`Successfully updated existing directory to commit ${commitHash}`);
98+
console.log(
99+
`Successfully updated existing directory to commit ${commitHash}`,
100+
);
93101
} catch (error) {
94102
console.error(`Error updating existing directory: ${error}`);
95103
console.log('Removing directory and cloning fresh...');
@@ -124,14 +132,17 @@ export function applyPrepareReleaseScript(
124132
clonedRepoDir: string,
125133
preid: string,
126134
scope = '@bitgo-beta',
127-
distTagsCachePath?: string
135+
distTagsCachePath?: string,
128136
): string {
129137
const args: string[] = [];
130138
args.push(preid);
131139
args.push(`scope=${scope}`);
132140

133141
// Get the current git repository directory
134-
const currentRepoDir = execGitCapture(['rev-parse', '--show-toplevel']).trim();
142+
const currentRepoDir = execGitCapture([
143+
'rev-parse',
144+
'--show-toplevel',
145+
]).trim();
135146

136147
// Use the script from the current repo, not the cloned one
137148
const scriptPath = path.join(currentRepoDir, 'scripts', 'prepare-release.ts');
@@ -180,13 +191,19 @@ export function generateGitDiff(repoDir: string, pathFilter?: string): string {
180191
* @param referenceDiffPath The path to the reference diff file
181192
* @throws AssertionError if the diffs don't match
182193
*/
183-
export function assertEqualDiffs(generatedDiff: string, referenceDiffPath: string): void {
194+
export function assertEqualDiffs(
195+
generatedDiff: string,
196+
referenceDiffPath: string,
197+
): void {
184198
if (!fs.existsSync(referenceDiffPath)) {
185199
throw new Error(`Reference diff file does not exist: ${referenceDiffPath}`);
186200
}
187201

188202
// Write the generated diff to a temporary file
189-
const tempFile = tmp.fileSync({ prefix: 'generated-diff-', postfix: '.diff' });
203+
const tempFile = tmp.fileSync({
204+
prefix: 'generated-diff-',
205+
postfix: '.diff',
206+
});
190207
fs.writeFileSync(tempFile.name, generatedDiff);
191208

192209
try {
@@ -221,7 +238,10 @@ export function assertEqualDiffs(generatedDiff: string, referenceDiffPath: strin
221238
* @param diff The diff to save as reference
222239
* @param referenceDiffPath The path to save the reference diff to
223240
*/
224-
export function createReferenceDiff(diff: string, referenceDiffPath: string): void {
241+
export function createReferenceDiff(
242+
diff: string,
243+
referenceDiffPath: string,
244+
): void {
225245
const dirPath = path.dirname(referenceDiffPath);
226246
if (!fs.existsSync(dirPath)) {
227247
fs.mkdirSync(dirPath, { recursive: true });
@@ -246,7 +266,7 @@ export function runTestAndCompare(
246266
tempDir?: string;
247267
pathFilter?: string;
248268
distTagsCachePath?: string;
249-
}
269+
},
250270
): void {
251271
// Use provided tempDir or create a new one
252272
const tempDir = options?.tempDir || createTempDir();

scripts/vendor-github-repo.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { execa, ResultPromise } from 'execa';
2-
import * as fs from 'fs/promises';
3-
import * as tmp from 'tmp';
4-
import * as yargs from 'yargs';
2+
import fs from 'fs/promises';
3+
import tmp from 'tmp';
4+
import yargs from 'yargs';
55

66
type GithubSource = {
77
org: string;

scripts/verify-release.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import * as execa from 'execa';
1+
import execa from 'execa';
22
import { readFileSync } from 'fs';
3-
import * as path from 'path';
3+
import path from 'path';
44
import { getLernaModules, getDistTags } from './prepareRelease';
55

66
let lernaModuleLocations: string[] = [];
@@ -12,16 +12,24 @@ async function getLernaModuleLocations(): Promise<void> {
1212

1313
async function verifyPackage(dir: string, preid = 'beta'): Promise<boolean> {
1414
const cwd = dir;
15-
const json = JSON.parse(readFileSync(path.join(cwd, 'package.json'), { encoding: 'utf-8' }));
15+
const json = JSON.parse(
16+
readFileSync(path.join(cwd, 'package.json'), { encoding: 'utf-8' }),
17+
);
1618
if (json.private) {
1719
return true;
1820
}
1921

2022
try {
2123
const distTags = await getDistTags(json.name);
2224
if (json.version !== distTags[preid]) {
23-
console.log(`${json.name} missing. Expected ${json.version}, latest is ${distTags[preid]}`);
24-
const { stdout, exitCode } = await execa('npm', ['publish', '--tag', preid], { cwd });
25+
console.log(
26+
`${json.name} missing. Expected ${json.version}, latest is ${distTags[preid]}`,
27+
);
28+
const { stdout, exitCode } = await execa(
29+
'npm',
30+
['publish', '--tag', preid],
31+
{ cwd },
32+
);
2533
console.log(stdout);
2634
return exitCode === 0;
2735
} else {

0 commit comments

Comments
 (0)