-
Notifications
You must be signed in to change notification settings - Fork 61
feat(ng-dev): add sync-module-bazel command to update pnpm and typescript versions and integrity in MODULE.bazel
#3340
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
65e50e2
feat(ng-dev): add `sync-module-bazel` command to update `pnpm` and `t…
alan-agius4 e2c8384
fixup! feat(ng-dev): add `sync-module-bazel` command to update `pnpm`…
alan-agius4 3964af9
fixup! feat(ng-dev): add `sync-module-bazel` command to update `pnpm`…
alan-agius4 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| /** | ||
alan-agius4 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| * @license | ||
| * Copyright Google LLC | ||
| * | ||
| * Use of this source code is governed by an MIT-style license that can be | ||
| * found in the LICENSE file at https://angular.io/license | ||
| */ | ||
|
|
||
| import {Argv, CommandModule} from 'yargs'; | ||
| import {readFileSync, writeFileSync} from 'node:fs'; | ||
| import {join} from 'node:path'; | ||
| import {determineRepoBaseDirFromCwd} from '../../utils/repo-directory'; | ||
| import {PackageJson, syncNodeJs, syncPnpm, syncTypeScript} from './sync-module-bazel'; | ||
| import {ChildProcess} from '../../utils/child-process'; | ||
| import {formatFiles} from '../../format/format'; | ||
|
|
||
| async function builder(argv: Argv) { | ||
| return argv; | ||
| } | ||
|
|
||
| async function handler() { | ||
| const rootDir = determineRepoBaseDirFromCwd(); | ||
| const packageJsonPath = join(rootDir, 'package.json'); | ||
| const moduleBazelPath = join(rootDir, 'MODULE.bazel'); | ||
| const nvmrcPath = join(rootDir, '.nvmrc'); | ||
|
|
||
| // Read package.json | ||
| const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as PackageJson; | ||
| const pnpmVersion = packageJson.engines?.pnpm; | ||
| const tsVersion = packageJson.dependencies?.typescript || packageJson.devDependencies?.typescript; | ||
|
|
||
| // Read .nvmrc | ||
| let nvmrcVersion: string | undefined; | ||
| try { | ||
| nvmrcVersion = readFileSync(nvmrcPath, 'utf8').trim().replace(/^v/, ''); | ||
| } catch { | ||
| // .nvmrc is optional. | ||
| } | ||
|
|
||
| if (!pnpmVersion) { | ||
| throw new Error('Could find engines.pnpm in package.json'); | ||
| } | ||
|
|
||
| if (!tsVersion) { | ||
| throw new Error('Could not find typescript in dependencies or devDependencies in package.json'); | ||
| } | ||
|
|
||
| // Read MODULE.bazel | ||
| const originalBazelContent = readFileSync(moduleBazelPath, 'utf8'); | ||
| let moduleBazelContent = originalBazelContent; | ||
|
|
||
| moduleBazelContent = await syncPnpm(moduleBazelContent, pnpmVersion); | ||
| moduleBazelContent = await syncTypeScript(moduleBazelContent, tsVersion); | ||
| moduleBazelContent = await syncNodeJs(moduleBazelContent, nvmrcVersion); | ||
|
|
||
| if (originalBazelContent !== moduleBazelContent) { | ||
| writeFileSync(moduleBazelPath, moduleBazelContent); | ||
|
|
||
| await formatFiles(['MODULE.bazel']); | ||
|
|
||
| ChildProcess.spawnSync('pnpm', ['bazel', 'mod', 'deps', '--lockfile_mode=update'], { | ||
| suppressErrorOnFailingExitCode: true, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| /** CLI command module. */ | ||
| export const SyncModuleBazelModule: CommandModule = { | ||
| builder, | ||
| handler, | ||
| command: 'sync-module-bazel', | ||
| describe: | ||
| 'Sync node.js, pnpm and typescript versions in MODULE.bazel with package.json and .nvmrc.', | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,239 @@ | ||
| /** | ||
| * @license | ||
| * Copyright Google LLC | ||
| * | ||
| * Use of this source code is governed by an MIT-style license that can be | ||
| * found in the LICENSE file at https://angular.io/license | ||
| */ | ||
|
|
||
| import {Log} from '../../utils/logging'; | ||
|
|
||
| export interface PackageJson { | ||
| engines?: { | ||
| pnpm?: string; | ||
| node?: string; | ||
| }; | ||
| dependencies?: { | ||
| typescript?: string; | ||
| }; | ||
| devDependencies?: { | ||
| typescript?: string; | ||
| }; | ||
| } | ||
|
|
||
| interface RepositoryInfo { | ||
| filename: string; | ||
| sha: string; | ||
| type: string; | ||
| } | ||
|
|
||
| const REPOSITORY_TYPES: Record<string, string> = { | ||
| 'darwin-arm64.tar.gz': 'darwin_arm64', | ||
| 'darwin-x64.tar.gz': 'darwin_amd64', | ||
| 'linux-x64.tar.xz': 'linux_amd64', | ||
| 'linux-arm64.tar.xz': 'linux_arm64', | ||
| 'linux-s390x.tar.xz': 'linux_s390x', | ||
| 'win-x64.zip': 'windows_amd64', | ||
| 'linux-ppc64le.tar.xz': 'linux_ppc64le', | ||
| }; | ||
|
|
||
| /** RegExp that matches the pnpm version assignment in MODULE.bazel. */ | ||
| const PNPM_VERSION_REGEXP = /pnpm_version(?:_from)? = ".*?"/; | ||
| /** RegExp that matches the pnpm integrity assignment in MODULE.bazel. */ | ||
| const PNPM_INTEGRITY_REGEXP = /pnpm_version_integrity = ".*?"/; | ||
| /** RegExp that matches the TypeScript version assignment in MODULE.bazel. */ | ||
| const TS_VERSION_REGEXP = /ts_version(?:_from)? = ".*?"/; | ||
| /** RegExp that matches the TypeScript integrity assignment in MODULE.bazel. */ | ||
| const TS_INTEGRITY_REGEXP = /ts_integrity = ".*?"/; | ||
| /** RegExp that matches the Node.js version assignment in MODULE.bazel. */ | ||
| const NODE_VERSION_REGEXP = /node_version = "(.*?)"/; | ||
| /** RegExp that matches the Node.js repositories assignment in MODULE.bazel. */ | ||
| const NODE_REPOSITORIES_REGEXP = /node_repositories = \{[\s\S]*?\}/; | ||
|
|
||
| /** Fetches the integrity for a given package version from the npm registry. */ | ||
| async function getNpmPackageIntegrity(pkg: string, version: string): Promise<string> { | ||
| const response = await fetch(`https://registry.npmjs.org/${pkg}/${version}`); | ||
| if (!response.ok) { | ||
| throw new Error(`Failed to request ${pkg}@${version}: ${response.statusText}`); | ||
| } | ||
|
|
||
| const {dist} = (await response.json()) as {dist: {integrity: string}}; | ||
|
|
||
| return dist.integrity; | ||
| } | ||
|
|
||
| /** Fetches the repository information for a given Node.js version. */ | ||
| async function getNodeJsRepositories(version: string): Promise<RepositoryInfo[]> { | ||
| const response = await fetch(`https://nodejs.org/dist/v${version}/SHASUMS256.txt`); | ||
| if (!response.ok) { | ||
| throw new Error(`Failed to get SHASUMS for Node.js v${version}: ${response.statusText}`); | ||
| } | ||
| const text = await response.text(); | ||
|
|
||
| return text | ||
| .split('\n') | ||
| .filter(Boolean) | ||
| .map((line: string): RepositoryInfo | undefined => { | ||
| const [sha, filename] = line.trim().split(/\s+/); | ||
| if (!filename) return undefined; | ||
|
|
||
| const fileTypeSuffix = filename.replace(/^node-v[\d.]+-/, ''); | ||
| const type = REPOSITORY_TYPES[fileTypeSuffix]; | ||
|
|
||
| return type ? {filename, sha, type} : undefined; | ||
| }) | ||
| .filter((repo): repo is RepositoryInfo => repo !== undefined); | ||
| } | ||
|
|
||
| /** Updates the version and integrity in the MODULE.bazel content for PNPM/TS. */ | ||
| function updateVersionAndIntegrity( | ||
| content: string, | ||
| version: string, | ||
| integrity: string, | ||
| versionRegExp: RegExp, | ||
| integrityRegExp: RegExp, | ||
| versionKey: string, | ||
| integrityKey: string, | ||
| ): string { | ||
| const newVal = `${versionKey} = "${version}"`; | ||
| const result = content.replace(versionRegExp, newVal); | ||
|
|
||
| return integrityRegExp.test(result) | ||
| ? result.replace(integrityRegExp, `${integrityKey} = "${integrity}"`) | ||
| : result.replace(newVal, `${newVal},\n ${integrityKey} = "${integrity}"`); | ||
| } | ||
|
|
||
| /** | ||
| * Processes a `node.toolchain` block args string and updates it with | ||
| * the correct versions and repositories. | ||
| */ | ||
| async function processNodeToolchainArgs( | ||
| args: string, | ||
| nvmrcVersion: string | undefined, | ||
| ): Promise<string> { | ||
| const useVersionFromNvm = args.includes('node_version_from_nvmrc'); | ||
| const versionMatch = args.match(NODE_VERSION_REGEXP); | ||
| let effectiveVersion = versionMatch?.[1]; | ||
|
|
||
| if (useVersionFromNvm) { | ||
| if (!nvmrcVersion) { | ||
| throw new Error('node_version_from_nvmrc used but .nvmrc not found'); | ||
| } | ||
|
|
||
| effectiveVersion = nvmrcVersion; | ||
| } else if (effectiveVersion && effectiveVersion !== nvmrcVersion) { | ||
| args = args.replace(NODE_VERSION_REGEXP, `node_version = "${nvmrcVersion}"`); | ||
| effectiveVersion = nvmrcVersion; | ||
| } | ||
| if (!effectiveVersion) { | ||
| return args; | ||
| } | ||
|
|
||
| Log.info(`Resolving Node.js repositories for v${effectiveVersion}...`); | ||
| const repositories = await getNodeJsRepositories(effectiveVersion); | ||
| const lines = repositories.map(({filename, sha, type}) => { | ||
| const strippedFilename = filename.replace(/(\.tar)?\.[^.]+$/, ''); | ||
|
|
||
| return ` "${effectiveVersion}-${type}": ("${filename}", "${strippedFilename}", "${sha}"),`; | ||
| }); | ||
|
|
||
| const reposDict = `{\n${lines.join('\n')}\n }`; | ||
|
|
||
| if (NODE_REPOSITORIES_REGEXP.test(args)) { | ||
| return args.replace(NODE_REPOSITORIES_REGEXP, `node_repositories = ${reposDict}`); | ||
| } | ||
|
|
||
| const separator = args.trim().endsWith(',') ? '' : ','; | ||
| return `${args.trim()}${separator}\n node_repositories = ${reposDict}\n`; | ||
| } | ||
|
|
||
| /** Synchronizes the PNPM version and integrity in MODULE.bazel. */ | ||
| export async function syncPnpm(content: string, version: string): Promise<string> { | ||
| if (!PNPM_VERSION_REGEXP.test(content)) { | ||
| return content; | ||
| } | ||
|
|
||
| Log.info(`Resolving integrity for pnpm@${version}...`); | ||
| const pnpmIntegrity = await getNpmPackageIntegrity('pnpm', version); | ||
|
|
||
| return updateVersionAndIntegrity( | ||
| content, | ||
| version, | ||
| pnpmIntegrity, | ||
| PNPM_VERSION_REGEXP, | ||
| PNPM_INTEGRITY_REGEXP, | ||
| 'pnpm_version', | ||
| 'pnpm_version_integrity', | ||
| ); | ||
| } | ||
|
|
||
| /** Synchronizes the TypeScript version and integrity in MODULE.bazel. */ | ||
| export async function syncTypeScript(content: string, version: string): Promise<string> { | ||
| if (!TS_VERSION_REGEXP.test(content)) { | ||
| return content; | ||
| } | ||
|
|
||
| Log.info(`Resolving integrity for typescript@${version}...`); | ||
| const tsIntegrity = await getNpmPackageIntegrity('typescript', version); | ||
|
|
||
| return updateVersionAndIntegrity( | ||
| content, | ||
| version, | ||
| tsIntegrity, | ||
| TS_VERSION_REGEXP, | ||
| TS_INTEGRITY_REGEXP, | ||
| 'ts_version', | ||
| 'ts_integrity', | ||
| ); | ||
| } | ||
|
|
||
| /** Finds the index of the closing parenthesis for a balanced block. */ | ||
| function findClosedParenIndex(content: string, startIndex: number): number { | ||
| let balance = 1; | ||
|
|
||
| for (let i = startIndex + 1; i < content.length; i++) { | ||
| if (content[i] === '(') { | ||
| balance++; | ||
| } else if (content[i] === ')') { | ||
| balance--; | ||
| } | ||
|
|
||
| if (balance === 0) { | ||
| return i; | ||
| } | ||
| } | ||
|
|
||
| return -1; | ||
| } | ||
|
|
||
| /** Synchronizes the Node.js toolchain versions and repositories in MODULE.bazel. */ | ||
| export async function syncNodeJs( | ||
| content: string, | ||
| nvmrcVersion: string | undefined, | ||
| ): Promise<string> { | ||
| const parts: string[] = []; | ||
| let lastIndex = 0; | ||
| let startIndex = 0; | ||
|
|
||
| while ((startIndex = content.indexOf('node.toolchain(', startIndex)) !== -1) { | ||
| const openParenIndex = startIndex + 'node.toolchain('.length - 1; | ||
| const endIndex = findClosedParenIndex(content, openParenIndex); | ||
|
|
||
| if (endIndex === -1) { | ||
| break; | ||
| } | ||
|
|
||
| parts.push(content.slice(lastIndex, startIndex)); | ||
|
|
||
| const args = content.slice(openParenIndex + 1, endIndex); | ||
| const updatedArgs = await processNodeToolchainArgs(args, nvmrcVersion); | ||
| parts.push(`node.toolchain(${updatedArgs})`); | ||
|
|
||
| lastIndex = endIndex + 1; | ||
| startIndex = lastIndex; | ||
| } | ||
|
|
||
| parts.push(content.slice(lastIndex)); | ||
|
|
||
| return parts.join(''); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using
node_version_from_nvmrcin dev-infra causes build failures becausepnpm ng-dev sync-module-bazelexecutes inside Bazel. To prevent errors during syncing, we must ensure the Node.js toolchain is correctly configured before actually syncing. Thus, we update thenode_versionwith that inside the.nvmrcduring syncing.