fix: allow subcommands with TRIVY_RUN_AS_PLUGIN (#2577)

This commit is contained in:
Teppei Fukuda
2022-07-25 11:27:47 +03:00
committed by GitHub
parent c2f3731873
commit c7f0bc92ae
3 changed files with 31 additions and 11 deletions

View File

@@ -1,8 +1,14 @@
package main
import (
"context"
"os"
"golang.org/x/xerrors"
"github.com/aquasecurity/trivy/pkg/commands"
"github.com/aquasecurity/trivy/pkg/log"
"github.com/aquasecurity/trivy/pkg/plugin"
)
var (
@@ -10,8 +16,26 @@ var (
)
func main() {
app := commands.NewApp(version)
if err := app.Execute(); err != nil {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
// Trivy behaves as the specified plugin.
if runAsPlugin := os.Getenv("TRIVY_RUN_AS_PLUGIN"); runAsPlugin != "" {
if !plugin.IsPredefined(runAsPlugin) {
return xerrors.Errorf("unknown plugin: %s", runAsPlugin)
}
if err := plugin.RunWithArgs(context.Background(), runAsPlugin, os.Args); err != nil {
return xerrors.Errorf("plugin error: %w", err)
}
return nil
}
app := commands.NewApp(version)
if err := app.Execute(); err != nil {
return err
}
return nil
}

View File

@@ -68,15 +68,6 @@ func SetOut(out io.Writer) {
func NewApp(version string) *cobra.Command {
globalFlags := flag.NewGlobalFlagGroup()
rootCmd := NewRootCommand(version, globalFlags)
if runAsPlugin := os.Getenv("TRIVY_RUN_AS_PLUGIN"); runAsPlugin != "" {
rootCmd.RunE = func(cmd *cobra.Command, args []string) error {
return plugin.RunWithArgs(cmd.Context(), runAsPlugin, args)
}
rootCmd.DisableFlagParsing = true
return rootCmd
}
rootCmd.AddCommand(
NewImageCommand(globalFlags),
NewFilesystemCommand(globalFlags),

View File

@@ -293,6 +293,11 @@ func RunWithArgs(ctx context.Context, url string, args []string) error {
return nil
}
func IsPredefined(name string) bool {
_, ok := officialPlugins[name]
return ok
}
func loadMetadata(dir string) (Plugin, error) {
filePath := filepath.Join(dir, configFile)
f, err := os.Open(filePath)