gopkg.in/docker/docker.v23@v23.0.11/pkg/plugins/pluginrpc-gen/main.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"flag"
     6  	"fmt"
     7  	"go/format"
     8  	"os"
     9  	"unicode"
    10  	"unicode/utf8"
    11  )
    12  
    13  type stringSet struct {
    14  	values map[string]struct{}
    15  }
    16  
    17  func (s stringSet) String() string {
    18  	return ""
    19  }
    20  
    21  func (s stringSet) Set(value string) error {
    22  	s.values[value] = struct{}{}
    23  	return nil
    24  }
    25  func (s stringSet) GetValues() map[string]struct{} {
    26  	return s.values
    27  }
    28  
    29  var (
    30  	typeName   = flag.String("type", "", "interface type to generate plugin rpc proxy for")
    31  	rpcName    = flag.String("name", *typeName, "RPC name, set if different from type")
    32  	inputFile  = flag.String("i", "", "input file path")
    33  	outputFile = flag.String("o", *inputFile+"_proxy.go", "output file path")
    34  
    35  	skipFuncs   map[string]struct{}
    36  	flSkipFuncs = stringSet{make(map[string]struct{})}
    37  
    38  	flBuildTags = stringSet{make(map[string]struct{})}
    39  )
    40  
    41  func errorOut(msg string, err error) {
    42  	if err == nil {
    43  		return
    44  	}
    45  	fmt.Fprintf(os.Stderr, "%s: %v\n", msg, err)
    46  	os.Exit(1)
    47  }
    48  
    49  func checkFlags() error {
    50  	if *outputFile == "" {
    51  		return fmt.Errorf("missing required flag `-o`")
    52  	}
    53  	if *inputFile == "" {
    54  		return fmt.Errorf("missing required flag `-i`")
    55  	}
    56  	return nil
    57  }
    58  
    59  func main() {
    60  	flag.Var(flSkipFuncs, "skip", "skip parsing for function")
    61  	flag.Var(flBuildTags, "tag", "build tags to add to generated files")
    62  	flag.Parse()
    63  	skipFuncs = flSkipFuncs.GetValues()
    64  
    65  	errorOut("error", checkFlags())
    66  
    67  	pkg, err := Parse(*inputFile, *typeName)
    68  	errorOut(fmt.Sprintf("error parsing requested type %s", *typeName), err)
    69  
    70  	var analysis = struct {
    71  		InterfaceType string
    72  		RPCName       string
    73  		BuildTags     map[string]struct{}
    74  		*ParsedPkg
    75  	}{toLower(*typeName), *rpcName, flBuildTags.GetValues(), pkg}
    76  	var buf bytes.Buffer
    77  
    78  	errorOut("parser error", generatedTempl.Execute(&buf, analysis))
    79  	src, err := format.Source(buf.Bytes())
    80  	errorOut("error formatting generated source:\n"+buf.String(), err)
    81  	errorOut("error writing file", os.WriteFile(*outputFile, src, 0644))
    82  }
    83  
    84  func toLower(s string) string {
    85  	if s == "" {
    86  		return ""
    87  	}
    88  	r, n := utf8.DecodeRuneInString(s)
    89  	return string(unicode.ToLower(r)) + s[n:]
    90  }