github.com/anchore/syft@v1.38.2/cmd/syft/cli/cli.go (about)

     1  package cli
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  
     7  	cranecmd "github.com/google/go-containerregistry/cmd/crane/cmd"
     8  	"github.com/spf13/cobra"
     9  
    10  	"github.com/anchore/clio"
    11  	"github.com/anchore/syft/cmd/syft/internal"
    12  	"github.com/anchore/syft/cmd/syft/internal/commands"
    13  	constants "github.com/anchore/syft/internal"
    14  )
    15  
    16  // Application constructs the `syft packages` command and aliases the root command to `syft packages`.
    17  // It is also responsible for organizing flag usage and injecting the application config for each command.
    18  // It also constructs the syft attest command and the syft version command.
    19  // `RunE` is the earliest that the complete application configuration can be loaded.
    20  func Application(id clio.Identification) clio.Application {
    21  	app, _ := create(id, os.Stdout)
    22  	return app
    23  }
    24  
    25  // Command returns the root command for the syft CLI application. This is useful for embedding the entire syft CLI
    26  // into an existing application.
    27  func Command(id clio.Identification) *cobra.Command {
    28  	_, cmd := create(id, os.Stdout)
    29  	return cmd
    30  }
    31  
    32  func create(id clio.Identification, out io.Writer) (clio.Application, *cobra.Command) {
    33  	clioCfg := internal.AppClioSetupConfig(id, out)
    34  
    35  	app := clio.New(*clioCfg)
    36  
    37  	// since root is aliased as the packages cmd we need to construct this command first
    38  	// we also need the command to have information about the `root` options because of this alias
    39  	scanCmd := commands.Scan(app)
    40  
    41  	// root is currently an alias for the scan command
    42  	rootCmd := commands.Root(app, scanCmd)
    43  
    44  	// add sub-commands
    45  	rootCmd.AddCommand(
    46  		scanCmd,
    47  		commands.Packages(app, scanCmd), // this is currently an alias for the scan command
    48  		commands.Cataloger(app),
    49  		commands.Attest(app),
    50  		commands.Convert(app),
    51  		clio.VersionCommand(id, schemaVersion),
    52  		clio.ConfigCommand(app, nil),
    53  		cranecmd.NewCmdAuthLogin(id.Name), // syft login uses the same command as crane
    54  	)
    55  
    56  	// note: we would direct cobra to use our writer explicitly with rootCmd.SetOut(out) , however this causes
    57  	// deprecation warnings to be shown to stdout via the writer instead of stderr. This is unfortunate since this
    58  	// does not appear to be the correct behavior on cobra's part https://github.com/spf13/cobra/issues/1708 .
    59  	// In the future this functionality should be restored.
    60  
    61  	return app, rootCmd
    62  }
    63  
    64  func schemaVersion() (string, any) {
    65  	return "SchemaVersion", constants.JSONSchemaVersion
    66  }