kythe.io@v0.0.68-0.20240422202219-7225dbc01741/kythe/go/util/tools/write_extra_action/write_extra_action.go (about) 1 /* 2 * Copyright 2019 The Kythe Authors. All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://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, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 // Binary write_extra_action reads a textproto ExtraActionInfo, wire-encodes it, 18 // and writes it to another file. 19 // 20 // Usage: 21 // 22 // write_extra_action <text_proto_file> <output_path> 23 package main 24 25 import ( 26 "context" 27 "flag" 28 "fmt" 29 "io/ioutil" 30 "os" 31 "path/filepath" 32 33 "kythe.io/kythe/go/platform/vfs" 34 "kythe.io/kythe/go/util/log" 35 36 "google.golang.org/protobuf/encoding/prototext" 37 "google.golang.org/protobuf/proto" 38 39 xapb "kythe.io/third_party/bazel/extra_actions_base_go_proto" 40 ) 41 42 func main() { 43 flag.Parse() 44 45 if flag.NArg() < 2 || (flag.NArg() > 2 && flag.Arg(2) != "--") { 46 fmt.Printf("usage: %s <text_proto_file> <output_path> [-- <arg>...]\n", filepath.Base(os.Args[0])) 47 os.Exit(2) 48 } 49 50 ctx := context.Background() 51 textFile := flag.Arg(0) 52 outFile := flag.Arg(1) 53 54 in, err := vfs.Open(ctx, textFile) 55 if err != nil { 56 log.Fatal(err) 57 } 58 59 txt, err := ioutil.ReadAll(in) 60 in.Close() 61 if err != nil { 62 log.Fatal(err) 63 } 64 65 var xa xapb.ExtraActionInfo 66 if err := prototext.Unmarshal(txt, &xa); err != nil { 67 log.Fatal(err) 68 } 69 70 // C++ command line arguments are not available in Starlark, so the extension cannot 71 // be completed populated there and must delegate to an external binary. 72 if cc := proto.GetExtension(&xa, xapb.E_CppCompileInfo_CppCompileInfo).(*xapb.CppCompileInfo); cc != nil { 73 populateCppCompileInfo(cc) 74 } 75 76 rec, err := proto.Marshal(&xa) 77 if err != nil { 78 log.Fatal(err) 79 } 80 81 f, err := vfs.Create(ctx, outFile) 82 if err != nil { 83 log.Fatal(err) 84 } else if _, err := f.Write(rec); err != nil { 85 log.Fatal(err) 86 } else if err := f.Close(); err != nil { 87 log.Fatal(err) 88 } 89 } 90 91 func populateCppCompileInfo(cc *xapb.CppCompileInfo) { 92 if flag.NArg() <= 3 || flag.Arg(2) != "--" { 93 return // No additional flags, end early. 94 } 95 cc.Tool = proto.String(flag.Arg(3)) 96 cc.CompilerOption = flag.Args()[4:flag.NArg()] 97 for i, arg := range cc.CompilerOption { 98 if arg == "-c" && i+1 < len(cc.CompilerOption) { 99 cc.SourceFile = proto.String(cc.CompilerOption[i+1]) 100 break 101 } 102 } 103 }