github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/tools/go_marshal/main.go (about)

     1  // Copyright 2019 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://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,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // go_marshal is a code generation utility for automatically generating code to
    16  // marshal go data structures to memory.
    17  //
    18  // This binary is typically run as part of the build process, and is invoked by
    19  // the go_marshal bazel rule defined in defs.bzl.
    20  //
    21  // See README.md.
    22  package main
    23  
    24  import (
    25  	"flag"
    26  	"fmt"
    27  	"os"
    28  	"strings"
    29  
    30  	"github.com/SagerNet/gvisor/tools/go_marshal/gomarshal"
    31  )
    32  
    33  var (
    34  	pkg                     = flag.String("pkg", "", "output package")
    35  	output                  = flag.String("output", "", "output file")
    36  	outputTest              = flag.String("output_test", "", "output file for tests")
    37  	outputTestUnconditional = flag.String("output_test_unconditional", "", "output file for unconditional tests")
    38  	imports                 = flag.String("imports", "", "comma-separated list of extra packages to import in generated code")
    39  )
    40  
    41  func main() {
    42  	flag.Usage = func() {
    43  		fmt.Fprintf(os.Stderr, "Usage: %s <input go src files>\n", os.Args[0])
    44  		flag.PrintDefaults()
    45  	}
    46  	flag.Parse()
    47  	if len(flag.Args()) == 0 {
    48  		flag.Usage()
    49  		os.Exit(1)
    50  	}
    51  
    52  	if *pkg == "" {
    53  		flag.Usage()
    54  		fmt.Fprint(os.Stderr, "Flag -pkg must be provided.\n")
    55  		os.Exit(1)
    56  	}
    57  
    58  	var extraImports []string
    59  	if len(*imports) > 0 {
    60  		// Note: strings.Split(s, sep) returns s if sep doesn't exist in s. Thus
    61  		// we check for an empty imports list to avoid emitting an empty string
    62  		// as an import.
    63  		extraImports = strings.Split(*imports, ",")
    64  	}
    65  	g, err := gomarshal.NewGenerator(flag.Args(), *output, *outputTest, *outputTestUnconditional, *pkg, extraImports)
    66  	if err != nil {
    67  		panic(err)
    68  	}
    69  
    70  	if err := g.Run(); err != nil {
    71  		panic(err)
    72  	}
    73  }