diff --git a/cmd/trivy/main.go b/cmd/trivy/main.go index 4e45b40ad5..54ef107122 100644 --- a/cmd/trivy/main.go +++ b/cmd/trivy/main.go @@ -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 +} diff --git a/pkg/commands/app.go b/pkg/commands/app.go index 33a251eee0..b93e26284f 100644 --- a/pkg/commands/app.go +++ b/pkg/commands/app.go @@ -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), diff --git a/pkg/plugin/plugin.go b/pkg/plugin/plugin.go index 015d7926d6..db3ef2b83c 100644 --- a/pkg/plugin/plugin.go +++ b/pkg/plugin/plugin.go @@ -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)