From e3cf430d02bc855df27edf3e0f93454ca8196fdf Mon Sep 17 00:00:00 2001 From: Orgad Shaneh Date: Tue, 9 Jul 2024 00:21:20 +0300 Subject: [PATCH] fix: Use a hashed id for default root name (#1575) When multiple packages are imported, and all of them were generated in a way that uses default as the root name, each imported package overwrites the definitions of the previous ones. Solve by assigning a hashed (fallback) name to each generated package. Co-authored-by: sofisl <55454395+sofisl@users.noreply.github.com> --- tools/src/compileProtos.ts | 9 ++++++--- tools/test/compileProtos.ts | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/tools/src/compileProtos.ts b/tools/src/compileProtos.ts index 4c09d32fe..6543a54b5 100644 --- a/tools/src/compileProtos.ts +++ b/tools/src/compileProtos.ts @@ -21,6 +21,7 @@ import * as path from 'path'; import * as util from 'util'; import * as pbjs from 'protobufjs-cli/pbjs'; import * as pbts from 'protobufjs-cli/pbts'; +import * as crypto from 'crypto'; import {walkUp} from 'walk-up-path'; export const gaxProtos = path.join( @@ -353,13 +354,13 @@ async function compileProtos( * * @param directories List of directories to process. Normally, just the * `./src` folder of the given client library. - * @return {Promise} Resolves to a unique name for protobuf root to use in the JS static module, or 'default'. + * @return {Promise} Resolves to a unique name for protobuf root to use in the JS static module, or a hashed id. */ export async function generateRootName(directories: string[]): Promise { // We need to provide `-r root` option to `pbjs -t static-module`, otherwise // we'll have big problems if two different libraries are used together. // It's OK to play some guessing game here: if we locate `package.json` - // with a package name, we'll use it; otherwise, we'll fallback to 'default'. + // with a package name, we'll use it; otherwise, we'll fallback to a hashed id. for (const directory of directories) { for (const p of walkUp(path.resolve(directory, '..'))) { const packageJson = path.join(p, 'package.json'); @@ -373,7 +374,9 @@ export async function generateRootName(directories: string[]): Promise { } } } - return 'default'; + const sha1 = crypto.createHash('sha1'); + sha1.update(directories.join(',')); + return `default_${sha1.digest('hex').slice(0, 8)}`; } /** diff --git a/tools/test/compileProtos.ts b/tools/test/compileProtos.ts index 6c5fbf15d..3faebad21 100644 --- a/tools/test/compileProtos.ts +++ b/tools/test/compileProtos.ts @@ -292,7 +292,7 @@ describe('compileProtos tool', () => { const rootName = await compileProtos.generateRootName([ '/nonexistent/empty', ]); - assert.strictEqual(rootName, 'default'); + assert.strictEqual(rootName, 'default_371767bb'); }); it('reformat the JSDOC link in the JS and TS file', async function () {