github.com/yoheimuta/protolint@v0.49.8-0.20240515023657-4ecaebb7575d/internal/cmd/subcmds/pluginFlag.go (about)

     1  package subcmds
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  	"strings"
     7  
     8  	"github.com/hashicorp/go-hclog"
     9  
    10  	"github.com/yoheimuta/protolint/internal/addon/plugin/shared"
    11  
    12  	"github.com/hashicorp/go-plugin"
    13  )
    14  
    15  // PluginFlag manages a flag for plugins.
    16  type PluginFlag struct {
    17  	raws []string
    18  }
    19  
    20  // String implements flag.Value.
    21  func (f *PluginFlag) String() string {
    22  	return fmt.Sprint(strings.Join(f.raws, ","))
    23  }
    24  
    25  // Set implements flag.Value.
    26  func (f *PluginFlag) Set(value string) error {
    27  	f.raws = append(f.raws, value)
    28  	return nil
    29  }
    30  
    31  // BuildPlugins builds all plugins.
    32  func (f *PluginFlag) BuildPlugins(verbose bool) ([]shared.RuleSet, error) {
    33  	var plugins []shared.RuleSet
    34  
    35  	for _, value := range f.raws {
    36  		level := hclog.Warn
    37  		if verbose {
    38  			level = hclog.Trace
    39  		}
    40  		client := plugin.NewClient(&plugin.ClientConfig{
    41  			HandshakeConfig: shared.Handshake,
    42  			Plugins:         shared.PluginMap,
    43  			Cmd:             exec.Command("sh", "-c", value),
    44  			AllowedProtocols: []plugin.Protocol{
    45  				plugin.ProtocolGRPC,
    46  			},
    47  			Logger: hclog.New(&hclog.LoggerOptions{
    48  				Output: hclog.DefaultOutput,
    49  				Level:  level,
    50  				Name:   "plugin",
    51  			}),
    52  			// To cleanup. See. https://github.com/yoheimuta/protolint/issues/237
    53  			Managed: true,
    54  		})
    55  
    56  		rpcClient, err := client.Client()
    57  		if err != nil {
    58  			return nil, fmt.Errorf("failed client.Client(), err=%s", err)
    59  		}
    60  
    61  		ruleSet, err := rpcClient.Dispense("ruleSet")
    62  		if err != nil {
    63  			return nil, fmt.Errorf("failed Dispense, err=%s", err)
    64  		}
    65  		plugins = append(plugins, ruleSet.(shared.RuleSet))
    66  	}
    67  	return plugins, nil
    68  }