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 {exec, ExecException} from 'child_process'; 16import fs from 'fs'; 17 18const run = function (executable: string, args: string[]) { 19 console.log(args) 20 return new Promise<void>(resolve => { 21 exec(`${executable} ${args.join(" ")}`, {cwd: process.cwd()}, (error: ExecException | null, stdout: string | Buffer) => { 22 if (error) { 23 throw error; 24 } 25 26 console.log(stdout); 27 resolve(); 28 }); 29 }); 30}; 31 32const protos = [ 33 'pw_transfer/transfer.proto', 34 'pw_rpc/ts/test.proto', 35 'pw_rpc/echo.proto', 36 'pw_protobuf/pw_protobuf_protos/status.proto', 37 'pw_protobuf/pw_protobuf_protos/common.proto', 38 'pw_tokenizer/options.proto', 39 'pw_log/log.proto', 40 'pw_rpc/ts/test2.proto', 41 'pw_rpc/internal/packet.proto', 42 'pw_protobuf_compiler/pw_protobuf_compiler_protos/nested/more_nesting/test.proto', 43 'pw_protobuf_compiler/pw_protobuf_compiler_protos/test.proto' 44]; 45 46// Replace these import statements so they are actual paths to proto files. 47const remapImports = { 48 'pw_protobuf_protos/common.proto': 'pw_protobuf/pw_protobuf_protos/common.proto', 49 'pw_tokenizer/proto/options.proto': 'pw_tokenizer/options.proto' 50} 51 52// Only modify the .proto files when running this builder and then restore any 53// modified .proto files to their original states after the builder has finished 54// running. 55let restoreProtoList = []; 56protos.forEach((protoPath) => { 57 const protoData = fs.readFileSync(protoPath, 'utf-8'); 58 let newProtoData = protoData; 59 Object.keys(remapImports).forEach((remapImportFrom) => { 60 if (protoData.indexOf(`import "${remapImportFrom}"`) !== -1) { 61 newProtoData = newProtoData 62 .replaceAll(remapImportFrom, remapImports[remapImportFrom]); 63 } 64 }); 65 if (protoData !== newProtoData) { 66 restoreProtoList.push([protoPath, protoData]); 67 fs.writeFileSync(protoPath, newProtoData); 68 } 69}); 70 71run('ts-node', [ 72 `./pw_protobuf_compiler/ts/build.ts`, 73 `--out dist/protos` 74].concat( 75 protos.map(proto => `-p ${proto}`) 76)) 77 .then(() => { 78 restoreProtoList.forEach((restoreProtoData) => { 79 fs.writeFileSync(restoreProtoData[0], restoreProtoData[1]); 80 }); 81 }); 82