Skip to content

Commit

Permalink
fix: Use a hashed id for default root name (#1575)
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
orgads and sofisl authored Jul 8, 2024
1 parent 76dd049 commit e3cf430
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
9 changes: 6 additions & 3 deletions tools/src/compileProtos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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<string>} Resolves to a unique name for protobuf root to use in the JS static module, or 'default'.
* @return {Promise<string>} 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<string> {
// 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');
Expand All @@ -373,7 +374,9 @@ export async function generateRootName(directories: string[]): Promise<string> {
}
}
}
return 'default';
const sha1 = crypto.createHash('sha1');
sha1.update(directories.join(','));
return `default_${sha1.digest('hex').slice(0, 8)}`;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion tools/test/compileProtos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down

0 comments on commit e3cf430

Please sign in to comment.