kythe.io@v0.0.68-0.20240422202219-7225dbc01741/kythe/go/util/tools/vnames/convert.go (about) 1 /* 2 * Copyright 2020 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 package main 18 19 import ( 20 "context" 21 "flag" 22 "io" 23 "os" 24 "strings" 25 26 "kythe.io/kythe/go/platform/vfs" 27 "kythe.io/kythe/go/util/cmdutil" 28 29 "github.com/google/subcommands" 30 ) 31 32 type convertRulesCmd struct { 33 cmdutil.Info 34 35 rulesPath, outputPath string 36 fromFormat, toFormat string 37 } 38 39 var convertRulesInfo = cmdutil.NewInfo("convert-rules", `convert VName rewrite rules (formats: {"JSON", "PROTO"})`, 40 `Usage: convert-rules --from <format> --to <format>`) 41 42 func (c *convertRulesCmd) SetFlags(flag *flag.FlagSet) { 43 flag.StringVar(&c.fromFormat, "from", "", "Source format of VName rewrite rules") 44 flag.StringVar(&c.rulesPath, "rules", "", "Path to VName rewrite rules file (default: read from stdin)") 45 flag.StringVar(&c.toFormat, "to", "", "Target format of VName rewrite rules") 46 flag.StringVar(&c.outputPath, "output", "", "Output path to write converted VName rewrite rules (default: write to stdout)") 47 } 48 func (c *convertRulesCmd) Execute(ctx context.Context, flag *flag.FlagSet, args ...any) subcommands.ExitStatus { 49 if c.fromFormat == "" { 50 return cmdErrorf("--from <format> must be specified") 51 } else if c.toFormat == "" { 52 return cmdErrorf("--to <format> must be specified") 53 } 54 55 var in io.Reader 56 if c.rulesPath == "" { 57 in = os.Stdin 58 } else { 59 f, err := vfs.Open(ctx, c.rulesPath) 60 if err != nil { 61 return cmdErrorf("opening %q: %v", c.rulesPath, err) 62 } 63 defer f.Close() 64 in = f 65 } 66 67 var out io.WriteCloser 68 if c.outputPath == "" { 69 out = os.Stdout 70 } else { 71 f, err := vfs.Create(ctx, c.outputPath) 72 if err != nil { 73 return cmdErrorf("creating %q: %v", c.outputPath, err) 74 } 75 out = f 76 } 77 78 rules, err := rulesFormat(strings.ToUpper(c.fromFormat)).readRules(in) 79 if err != nil { 80 return cmdErrorf("reading rules: %v", err) 81 } else if err := rulesFormat(strings.ToUpper(c.toFormat)).writeRules(rules, out); err != nil { 82 return cmdErrorf("writing rules: %v", err) 83 } else if err := out.Close(); err != nil { 84 return cmdErrorf("closing output: %v", err) 85 } 86 87 return subcommands.ExitSuccess 88 }