Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions scripts/pack-scoped.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
* The archive can be used with `npm install path/to/tgz` to test the package locally.
*/

import * as fs from 'fs';
import * as execa from 'execa';
import * as mpath from 'path';
import * as yargs from 'yargs';
import fs from 'fs';
import execa from 'execa';
import mpath from 'path';
import yargs from 'yargs';
import {
walk,
getLernaModules,
Expand Down
81 changes: 62 additions & 19 deletions scripts/prepare-release.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as assert from 'node:assert';
import assert from 'node:assert';
import { readFileSync, writeFileSync } from 'fs';
import * as path from 'path';
import path from 'path';
import { inc, lt } from 'semver';
import * as yargs from 'yargs';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';

import {
Expand All @@ -15,10 +15,17 @@ import {
LernaModule,
} from './prepareRelease';

function replacePackageScopes(rootDir: string, lernaModules: LernaModule[], targetScope: string): number {
function replacePackageScopes(
rootDir: string,
lernaModules: LernaModule[],
targetScope: string,
): number {
let filesChanged = 0;
// replace all @bitgo packages & source code with alternate SCOPE
const filePaths = [...walk(path.join(rootDir, 'modules')), ...walk(path.join(rootDir, 'webpack'))];
const filePaths = [
...walk(path.join(rootDir, 'modules')),
...walk(path.join(rootDir, 'webpack')),
];
const moduleNames = lernaModules.map(({ name }) => name);

filePaths.forEach((file) => {
Expand All @@ -31,9 +38,14 @@ function replacePackageScopes(rootDir: string, lernaModules: LernaModule[], targ
// we must manually set one
function replaceBitGoPackageScope(rootDir: string, targetScope: string): void {
const cwd = path.join(rootDir, 'modules', 'bitgo');
const json = JSON.parse(readFileSync(path.join(cwd, 'package.json'), { encoding: 'utf-8' }));
const json = JSON.parse(
readFileSync(path.join(cwd, 'package.json'), { encoding: 'utf-8' }),
);
json.name = `${targetScope}/bitgo`;
writeFileSync(path.join(cwd, 'package.json'), JSON.stringify(json, null, 2) + '\n');
writeFileSync(
path.join(cwd, 'package.json'),
JSON.stringify(json, null, 2) + '\n',
);
}

/**
Expand All @@ -42,7 +54,11 @@ function replaceBitGoPackageScope(rootDir: string, targetScope: string): void {
* @returns The parsed package.json content
*/
function readModulePackageJson(module: LernaModule): any {
return JSON.parse(readFileSync(path.join(module.location, 'package.json'), { encoding: 'utf-8' }));
return JSON.parse(
readFileSync(path.join(module.location, 'package.json'), {
encoding: 'utf-8',
}),
);
}

/**
Expand All @@ -51,7 +67,10 @@ function readModulePackageJson(module: LernaModule): any {
* @param json The content to write
*/
function writeModulePackageJson(module: LernaModule, json: any): void {
writeFileSync(path.join(module.location, 'package.json'), JSON.stringify(json, null, 2) + '\n');
writeFileSync(
path.join(module.location, 'package.json'),
JSON.stringify(json, null, 2) + '\n',
);
}

/**
Expand All @@ -67,7 +86,7 @@ function incrementVersionsForModuleLocation(
preid: string,
module: LernaModule,
tags: DistTags | undefined,
allModules: LernaModule[]
allModules: LernaModule[],
): string | undefined {
const json = readModulePackageJson(module);

Expand All @@ -77,15 +96,20 @@ function incrementVersionsForModuleLocation(
if (tags[preid]) {
const version = tags[preid].split('-');
const latest = tags?.latest?.split('-') ?? ['0.0.0'];
prevTag = lt(version[0], latest[0]) ? `${tags.latest}-${preid}` : tags[preid];
prevTag = lt(version[0], latest[0])
? `${tags.latest}-${preid}`
: tags[preid];
} else {
prevTag = `${tags.latest}-${preid}`;
}
}

if (prevTag) {
const next = inc(prevTag, 'prerelease', undefined, preid);
assert(typeof next === 'string', `Failed to increment version for ${json.name} prevTag=${prevTag}`);
assert(
typeof next === 'string',
`Failed to increment version for ${json.name} prevTag=${prevTag}`,
);
console.log(`Setting next version for ${json.name} to ${next}`);
json.version = next;
writeModulePackageJson(module, json);
Expand Down Expand Up @@ -119,15 +143,26 @@ function incrementVersionsForModuleLocation(
* @param {String} preid - The prerelease identifier
* @param {LernaModule[]} lernaModules - The modules to update
*/
async function incrementVersions(preid: string, lernaModules: LernaModule[]): Promise<void> {
async function incrementVersions(
preid: string,
lernaModules: LernaModule[],
): Promise<void> {
const distTags = await getDistTagsForModules(lernaModules);

for (const m of lernaModules) {
try {
incrementVersionsForModuleLocation(preid, m, distTags.get(m), lernaModules);
incrementVersionsForModuleLocation(
preid,
m,
distTags.get(m),
lernaModules,
);
} catch (e) {
// it's not necessarily a blocking error. Let lerna try and publish anyways
console.warn(`Couldn't set next version for ${m.name} at ${m.location}`, e);
console.warn(
`Couldn't set next version for ${m.name} at ${m.location}`,
e,
);
}
}
}
Expand All @@ -151,7 +186,9 @@ yargs(hideBin(process.argv))
.option('root-dir', {
type: 'string',
description: 'Root directory of the repository',
default: process.env.BITGO_PREPARE_RELEASE_ROOT_DIR || path.join(__dirname, '..'),
default:
process.env.BITGO_PREPARE_RELEASE_ROOT_DIR ||
path.join(__dirname, '..'),
});
},
async (argv) => {
Expand All @@ -166,7 +203,11 @@ yargs(hideBin(process.argv))
const lernaModules = await getLernaModules();

// Replace package scopes
const filesChanged = replacePackageScopes(rootDir, lernaModules, targetScope);
const filesChanged = replacePackageScopes(
rootDir,
lernaModules,
targetScope,
);

// Replace BitGo package scope
replaceBitGoPackageScope(rootDir, targetScope);
Expand All @@ -178,14 +219,16 @@ yargs(hideBin(process.argv))
console.log(`Successfully re-targeted ${filesChanged} files.`);
process.exit(0);
} else {
console.error('No files were changed, something must have gone wrong.');
console.error(
'No files were changed, something must have gone wrong.',
);
process.exit(1);
}
} catch (error) {
console.error('Error in prepare-release script:', error);
process.exit(1);
}
}
},
)
.help()
.alias('help', 'h')
Expand Down
2 changes: 1 addition & 1 deletion scripts/prepareRelease/distTags.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { readFileSync, writeFileSync, existsSync } from 'fs';
import * as path from 'path';
import path from 'path';
import { LernaModule } from './getLernaModules';

export type DistTags = Record<string, string>;
Expand Down
10 changes: 7 additions & 3 deletions scripts/prepareRelease/getLernaModules.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as execa from 'execa';
import execa from 'execa';

export type LernaModule = {
name: string;
Expand All @@ -19,7 +19,11 @@ function getLernaRunner(lernaPath: string) {
}

export async function getLernaModules(): Promise<LernaModule[]> {
const { stdout: lernaBinary } = await execa('yarn', ['bin', 'lerna'], { cwd: process.cwd() });
const { stdout: lernaBinary } = await execa('yarn', ['bin', 'lerna'], {
cwd: process.cwd(),
});
const lerna = getLernaRunner(lernaBinary);
return JSON.parse(await lerna('list', ['--loglevel', 'silent', '--json', '--all']));
return JSON.parse(
await lerna('list', ['--loglevel', 'silent', '--json', '--all']),
);
}
2 changes: 1 addition & 1 deletion scripts/prepareRelease/walk.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as path from 'path';
import path from 'path';
import { readdirSync, statSync } from 'fs';

export const walk = (dir: string): string[] => {
Expand Down
48 changes: 34 additions & 14 deletions scripts/tests/prepareRelease/util.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import fs from 'fs';
import path from 'path';
import os from 'os';
import { execFileSync } from 'child_process';
import * as tmp from 'tmp';
import tmp from 'tmp';

/**
* Helper function to execute git commands and return output as string
Expand Down Expand Up @@ -57,9 +57,13 @@ export function symlinkNodeModules(targetDir: string): void {
if (fs.existsSync(sourceNodeModules)) {
// Create symlink
fs.symlinkSync(sourceNodeModules, targetNodeModules, 'junction');
console.log(`Symlinked node_modules from ${sourceNodeModules} to ${targetNodeModules}`);
console.log(
`Symlinked node_modules from ${sourceNodeModules} to ${targetNodeModules}`,
);
} else {
console.warn('Source node_modules directory not found, skipping symlink creation');
console.warn(
'Source node_modules directory not found, skipping symlink creation',
);
}
}

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

if (fs.existsSync(tempDir)) {
console.log(`Directory ${tempDir} already exists, ensuring it's at commit ${commitHash}`);
console.log(
`Directory ${tempDir} already exists, ensuring it's at commit ${commitHash}`,
);

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

console.log(`Successfully updated existing directory to commit ${commitHash}`);
console.log(
`Successfully updated existing directory to commit ${commitHash}`,
);
} catch (error) {
console.error(`Error updating existing directory: ${error}`);
console.log('Removing directory and cloning fresh...');
Expand Down Expand Up @@ -124,14 +132,17 @@ export function applyPrepareReleaseScript(
clonedRepoDir: string,
preid: string,
scope = '@bitgo-beta',
distTagsCachePath?: string
distTagsCachePath?: string,
): string {
const args: string[] = [];
args.push(preid);
args.push(`scope=${scope}`);

// Get the current git repository directory
const currentRepoDir = execGitCapture(['rev-parse', '--show-toplevel']).trim();
const currentRepoDir = execGitCapture([
'rev-parse',
'--show-toplevel',
]).trim();

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

// Write the generated diff to a temporary file
const tempFile = tmp.fileSync({ prefix: 'generated-diff-', postfix: '.diff' });
const tempFile = tmp.fileSync({
prefix: 'generated-diff-',
postfix: '.diff',
});
fs.writeFileSync(tempFile.name, generatedDiff);

try {
Expand Down Expand Up @@ -221,7 +238,10 @@ export function assertEqualDiffs(generatedDiff: string, referenceDiffPath: strin
* @param diff The diff to save as reference
* @param referenceDiffPath The path to save the reference diff to
*/
export function createReferenceDiff(diff: string, referenceDiffPath: string): void {
export function createReferenceDiff(
diff: string,
referenceDiffPath: string,
): void {
const dirPath = path.dirname(referenceDiffPath);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
Expand All @@ -246,7 +266,7 @@ export function runTestAndCompare(
tempDir?: string;
pathFilter?: string;
distTagsCachePath?: string;
}
},
): void {
// Use provided tempDir or create a new one
const tempDir = options?.tempDir || createTempDir();
Expand Down
6 changes: 3 additions & 3 deletions scripts/vendor-github-repo.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { execa, ResultPromise } from 'execa';
import * as fs from 'fs/promises';
import * as tmp from 'tmp';
import * as yargs from 'yargs';
import fs from 'fs/promises';
import tmp from 'tmp';
import yargs from 'yargs';

type GithubSource = {
org: string;
Expand Down
18 changes: 13 additions & 5 deletions scripts/verify-release.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as execa from 'execa';
import execa from 'execa';
import { readFileSync } from 'fs';
import * as path from 'path';
import path from 'path';
import { getLernaModules, getDistTags } from './prepareRelease';

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

async function verifyPackage(dir: string, preid = 'beta'): Promise<boolean> {
const cwd = dir;
const json = JSON.parse(readFileSync(path.join(cwd, 'package.json'), { encoding: 'utf-8' }));
const json = JSON.parse(
readFileSync(path.join(cwd, 'package.json'), { encoding: 'utf-8' }),
);
if (json.private) {
return true;
}

try {
const distTags = await getDistTags(json.name);
if (json.version !== distTags[preid]) {
console.log(`${json.name} missing. Expected ${json.version}, latest is ${distTags[preid]}`);
const { stdout, exitCode } = await execa('npm', ['publish', '--tag', preid], { cwd });
console.log(
`${json.name} missing. Expected ${json.version}, latest is ${distTags[preid]}`,
);
const { stdout, exitCode } = await execa(
'npm',
['publish', '--tag', preid],
{ cwd },
);
console.log(stdout);
return exitCode === 0;
} else {
Expand Down