1#!/usr/bin/env node 2// Copyright 2020 The Pigweed Authors 3// 4// Licensed under the Apache License, Version 2.0 (the "License"); you may not 5// use this file except in compliance with the License. You may obtain a copy of 6// the License at 7// 8// https://www.apache.org/licenses/LICENSE-2.0 9// 10// Unless required by applicable law or agreed to in writing, software 11// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13// License for the specific language governing permissions and limitations under 14// the License. 15 16import * as fs from 'fs'; 17import {ArgumentParser} from 'argparse'; 18import {FileDescriptorSet} from 'google-protobuf/google/protobuf/descriptor_pb'; 19// import {Message} from 'google-protobuf'; 20 21const parser = new ArgumentParser({}); 22parser.add_argument('--output', { 23 action: 'store', 24 required: true, 25 type: String, 26}); 27parser.add_argument('--descriptor_data', { 28 action: 'store', 29 required: true, 30 type: String, 31}); 32parser.add_argument('--template', { 33 action: 'store', 34 required: true, 35 type: String, 36}); 37parser.add_argument('--proto_root_dir', { 38 action: 'store', 39 required: true, 40 type: String, 41}); 42 43const args = parser.parse_args(); 44let template = fs.readFileSync(args.template).toString(); 45 46function buildModulePath(rootDir: string, fileName: string): string { 47 const name = `${rootDir}/${fileName}`; 48 return name.replace(/\.proto$/, '_pb'); 49} 50 51const descriptorSetBinary = fs.readFileSync(args.descriptor_data); 52const base64DescriptorSet = descriptorSetBinary.toString('base64'); 53const fileDescriptorSet = FileDescriptorSet.deserializeBinary( 54 new Buffer(descriptorSetBinary) 55); 56 57const imports = []; 58const moduleDictionary = []; 59const fileList = fileDescriptorSet.getFileList(); 60for (let i = 0; i < fileList.length; i++) { 61 const file = fileList[i]; 62 const modulePath = buildModulePath(args.proto_root_dir, file.getName()!); 63 const moduleName = 'proto_' + i; 64 imports.push(`import * as ${moduleName} from '${modulePath}';`); 65 const key = file.getName()!; 66 moduleDictionary.push(`['${key}', ${moduleName}],`); 67} 68 69template = template.replace( 70 '{TEMPLATE_descriptor_binary}', 71 base64DescriptorSet 72); 73template = template.replace('// TEMPLATE_proto_imports', imports.join('\n')); 74template = template.replace( 75 '// TEMPLATE_module_map', 76 moduleDictionary.join('\n') 77); 78 79fs.writeFileSync(args.output, template); 80