• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2022 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15import * as fs from 'fs';
16import { FileDescriptorSet } from 'google-protobuf/google/protobuf/descriptor_pb';
17
18function buildModulePath(rootDir: string, fileName: string): string {
19  const name = `${rootDir}/${fileName}`;
20  return name.replace(/\.proto$/, '_pb');
21}
22
23export default function generateTemplate(
24  outputPath: string,
25  descriptorDataPath: string,
26  templatePath: string,
27  protoRootDir: string,
28) {
29  let template = fs.readFileSync(templatePath).toString();
30
31  const descriptorSetBinary = fs.readFileSync(descriptorDataPath);
32  const base64DescriptorSet = descriptorSetBinary.toString('base64');
33  const fileDescriptorSet = FileDescriptorSet.deserializeBinary(
34    Buffer.from(descriptorSetBinary),
35  );
36
37  const imports = [];
38  const moduleDictionary = [];
39  const fileList = fileDescriptorSet.getFileList();
40  for (let i = 0; i < fileList.length; i++) {
41    const file = fileList[i];
42    const modulePath = buildModulePath('.', file.getName()!);
43    const moduleName = 'proto_' + i;
44    imports.push(`import * as ${moduleName} from '${modulePath}';`);
45    const key = file.getName()!;
46    moduleDictionary.push(`'${key}': ${moduleName},`);
47  }
48
49  template = template.replace(
50    '{TEMPLATE_descriptor_binary}',
51    base64DescriptorSet,
52  );
53  template = template.replace('// TEMPLATE_proto_imports', imports.join('\n'));
54  template = template.replace(
55    '// TEMPLATE_module_map',
56    moduleDictionary.join('\n'),
57  );
58
59  fs.writeFileSync(outputPath, template);
60}
61