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(outputPath: string, descriptorDataPath: string, templatePath: string, protoRootDir: string) { 24 let template = fs.readFileSync(templatePath).toString(); 25 26 const descriptorSetBinary = fs.readFileSync(descriptorDataPath); 27 const base64DescriptorSet = descriptorSetBinary.toString('base64'); 28 const fileDescriptorSet = FileDescriptorSet.deserializeBinary( 29 Buffer.from(descriptorSetBinary) 30 ); 31 32 const imports = []; 33 const moduleDictionary = []; 34 const fileList = fileDescriptorSet.getFileList(); 35 for (let i = 0; i < fileList.length; i++) { 36 const file = fileList[i]; 37 const modulePath = buildModulePath(".", file.getName()!); 38 const moduleName = 'proto_' + i; 39 imports.push(`import * as ${moduleName} from '${modulePath}';`); 40 const key = file.getName()!; 41 moduleDictionary.push(`['${key}', ${moduleName}],`); 42 } 43 44 template = template.replace( 45 '{TEMPLATE_descriptor_binary}', 46 base64DescriptorSet 47 ); 48 template = template.replace('// TEMPLATE_proto_imports', imports.join('\n')); 49 template = template.replace( 50 '// TEMPLATE_module_map', 51 moduleDictionary.join('\n') 52 ); 53 54 fs.writeFileSync(outputPath, template); 55} 56