Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove unsupported code "discovery_source.go" and increase test coverage #478

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
235 changes: 44 additions & 191 deletions pkg/command/discovery_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,25 @@ package command

import (
"fmt"
"strings"

"github.com/pkg/errors"

"github.com/vmware-tanzu/tanzu-cli/pkg/cli"
"github.com/vmware-tanzu/tanzu-cli/pkg/config"
"github.com/vmware-tanzu/tanzu-cli/pkg/constants"
"github.com/vmware-tanzu/tanzu-cli/pkg/discovery"
"github.com/vmware-tanzu/tanzu-cli/pkg/pluginmanager"

"github.com/pkg/errors"
"github.com/spf13/cobra"

"github.com/vmware-tanzu/tanzu-plugin-runtime/component"
configlib "github.com/vmware-tanzu/tanzu-plugin-runtime/config"
configtypes "github.com/vmware-tanzu/tanzu-plugin-runtime/config/types"

"github.com/vmware-tanzu/tanzu-cli/pkg/common"
"github.com/vmware-tanzu/tanzu-plugin-runtime/log"
)

var (
discoverySourceType, discoverySourceName, uri string
uri string
)

func newDiscoverySourceCmd() *cobra.Command {
Expand All @@ -36,43 +34,13 @@ func newDiscoverySourceCmd() *cobra.Command {
}
discoverySourceCmd.SetUsageFunc(cli.SubCmdUsageFunc)

listDiscoverySourceCmd := newListDiscoverySourceCmd()
updateDiscoverySourceCmd := newUpdateDiscoverySourceCmd()
deleteDiscoverySourceCmd := newDeleteDiscoverySourceCmd()

listDiscoverySourceCmd.Flags().StringVarP(&outputFormat, "output", "o", "", "Output format (yaml|json|table)")

discoverySourceCmd.AddCommand(
listDiscoverySourceCmd,
updateDiscoverySourceCmd,
deleteDiscoverySourceCmd,
newListDiscoverySourceCmd(),
newUpdateDiscoverySourceCmd(),
newDeleteDiscoverySourceCmd(),
newInitDiscoverySourceCmd(),
)

if !configlib.IsFeatureActivated(constants.FeatureDisableCentralRepositoryForTesting) {
discoverySourceCmd.AddCommand(newInitDiscoverySourceCmd())
updateDiscoverySourceCmd.Flags().StringVarP(&uri, "uri", "u", "", "URI for discovery source. The URI must be of an OCI image")
} else {
updateDiscoverySourceCmd.Flags().StringVarP(&discoverySourceType, "type", "t", "", "type of discovery source")
updateDiscoverySourceCmd.Flags().StringVarP(&uri, "uri", "u", "", "URI for discovery source. The URI format might be different based on the type of discovery source")

// The "add" and "delete" plugin source commands are not needed for the central repo
addDiscoverySourceCmd := newAddDiscoverySourceCmd()

// TODO: when reactivating the "plugin source add" command, we need to replace the --name flag
// with a argument for consistency with other commands
addDiscoverySourceCmd.Flags().StringVarP(&discoverySourceName, "name", "n", "", "name of discovery source")
addDiscoverySourceCmd.Flags().StringVarP(&discoverySourceType, "type", "t", "", "type of discovery source")
addDiscoverySourceCmd.Flags().StringVarP(&uri, "uri", "u", "", "URI for discovery source. The URI format might be different based on the type of discovery source")

// Not handling errors below because cobra handles the error when flag user doesn't provide these required flags
_ = cobra.MarkFlagRequired(addDiscoverySourceCmd.Flags(), "name")
_ = cobra.MarkFlagRequired(addDiscoverySourceCmd.Flags(), "type")
_ = cobra.MarkFlagRequired(addDiscoverySourceCmd.Flags(), "uri")

discoverySourceCmd.AddCommand(
addDiscoverySourceCmd,
)
}
return discoverySourceCmd
}

Expand All @@ -81,96 +49,40 @@ func newListDiscoverySourceCmd() *cobra.Command {
Use: "list",
Short: "List available discovery sources",
RunE: func(cmd *cobra.Command, args []string) error {
var err error
if !configlib.IsFeatureActivated(constants.FeatureDisableCentralRepositoryForTesting) {
output := component.NewOutputWriter(cmd.OutOrStdout(), outputFormat, "name", "image")
discoverySources, err := configlib.GetCLIDiscoverySources()
for _, ds := range discoverySources {
if ds.OCI != nil {
output.AddRow(ds.OCI.Name, ds.OCI.Image)
}
}
testPluginSources := pluginmanager.GetAdditionalTestPluginDiscoveries()
for _, ds := range testPluginSources {
if ds.OCI != nil {
output.AddRow(ds.OCI.Name+" (test only)", ds.OCI.Image)
}
output := component.NewOutputWriter(cmd.OutOrStdout(), outputFormat, "name", "image")
discoverySources, err := configlib.GetCLIDiscoverySources()
for _, ds := range discoverySources {
if ds.OCI != nil {
output.AddRow(ds.OCI.Name, ds.OCI.Image)
}
output.Render()
return err
}

output := component.NewOutputWriter(cmd.OutOrStdout(), outputFormat, "name", "type", "scope")

// List standalone scoped discoveries
discoverySources, _ := configlib.GetCLIDiscoverySources()
if discoverySources != nil {
outputFromDiscoverySources(discoverySources, common.PluginScopeStandalone, output)
}

// If context-target feature is activated, get discovery sources from all active context
// else get discovery sources from current server
if configlib.IsFeatureActivated(constants.FeatureContextCommand) {
mapContexts, err := configlib.GetAllCurrentContextsMap()
if err == nil {
for _, context := range mapContexts {
outputFromDiscoverySources(context.DiscoverySources, common.PluginScopeContext, output)
}
}
} else {
server, err := configlib.GetCurrentServer() // nolint:staticcheck // Deprecated
if err == nil && server != nil {
outputFromDiscoverySources(server.DiscoverySources, common.PluginScopeContext, output)
testPluginSources := pluginmanager.GetAdditionalTestPluginDiscoveries()
for _, ds := range testPluginSources {
if ds.OCI != nil {
output.AddRow(ds.OCI.Name+" (test only)", ds.OCI.Image)
}
}
output.Render()
return err
},
}
return listDiscoverySourceCmd
}

func outputFromDiscoverySources(discoverySources []configtypes.PluginDiscovery, scope string, output component.OutputWriter) {
for _, ds := range discoverySources {
dsName, dsType := discoverySourceNameAndType(ds)
output.AddRow(dsName, dsType, scope)
}
}
func newAddDiscoverySourceCmd() *cobra.Command {
var addDiscoverySourceCmd = &cobra.Command{
Use: "add",
Short: "Add a discovery source",
Long: "Add a discovery source. Supported discovery types are: oci, local",
Example: `
# Add a local discovery source. If URI is relative path,
# $HOME/.config/tanzu-plugins will be considered based path
tanzu plugin source add --name standalone-local --type local --uri path/to/local/discovery

# Add an OCI discovery source. URI should be an OCI image.
tanzu plugin source add --name standalone-oci --type oci --uri projects.registry.vmware.com/tkg/tanzu-plugins/standalone:latest`,
RunE: func(cmd *cobra.Command, args []string) error {
newDiscoverySource, err := createDiscoverySource(discoverySourceType, discoverySourceName, uri)
if err != nil {
return err
}

err = configlib.SetCLIDiscoverySource(newDiscoverySource)
if err != nil {
return err
}
listDiscoverySourceCmd.Flags().StringVarP(&outputFormat, "output", "o", "", "Output format (yaml|json|table)")

log.Successf("successfully added discovery source %s", discoverySourceName)
return nil
},
}
return addDiscoverySourceCmd
return listDiscoverySourceCmd
}

func newUpdateDiscoverySourceCmd() *cobra.Command {
var updateDiscoverySourceCmd = &cobra.Command{
Use: "update SOURCE_NAME",
Use: "update SOURCE_NAME --uri <URI>",
Short: "Update a discovery source configuration",
Args: cobra.ExactArgs(1),
// We already include the only flag in the use text,
// we therefore don't show '[flags]' in the usage text.
DisableFlagsInUseLine: true,
Example: `
# Update the discovery source for an air-gapped scenario. The URI must be an OCI image.
tanzu plugin source update default --uri registry.example.com/tanzu/plugin-inventory:latest`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
discoveryName := args[0]

Expand All @@ -179,11 +91,7 @@ func newUpdateDiscoverySourceCmd() *cobra.Command {
return fmt.Errorf("discovery %q does not exist", discoveryName)
}

if !configlib.IsFeatureActivated(constants.FeatureDisableCentralRepositoryForTesting) {
// With the central discovery, there is no more --type flag
discoverySourceType = common.DiscoveryTypeOCI
}
newDiscoverySource, err := createDiscoverySource(discoverySourceType, discoveryName, uri)
newDiscoverySource, err := createDiscoverySource(discoveryName, uri)
if err != nil {
return err
}
Expand All @@ -198,29 +106,20 @@ func newUpdateDiscoverySourceCmd() *cobra.Command {
},
}

if !configlib.IsFeatureActivated(constants.FeatureDisableCentralRepositoryForTesting) {
updateDiscoverySourceCmd.Example = `
# Update the discovery source for an air-gapped scenario. The URI must be an OCI image.
tanzu plugin source update default --uri registry.example.com/tanzu/plugin-inventory:latest`
} else {
updateDiscoverySourceCmd.Example = `
# Update a local discovery source. If URI is relative path,
# $HOME/.config/tanzu-plugins will be considered base path
tanzu plugin source update standalone-local --type local --uri new/path/to/local/discovery

# Update an OCI discovery source. URI should be an OCI image.
tanzu plugin source update standalone-oci --type oci --uri projects.registry.vmware.com/tkg/tanzu-plugins/standalone:v1.0`
}
updateDiscoverySourceCmd.Flags().StringVarP(&uri, "uri", "u", "", "URI for discovery source. The URI must be of an OCI image")
_ = updateDiscoverySourceCmd.MarkFlagRequired("uri")

return updateDiscoverySourceCmd
}

func newDeleteDiscoverySourceCmd() *cobra.Command {
var deleteDiscoverySourceCmd = &cobra.Command{
Use: "delete SOURCE_NAME",
Short: "Delete a discovery source",
Args: cobra.ExactArgs(1),
Hidden: true,
Use: "delete SOURCE_NAME",
Short: "Delete a discovery source",
// There are no flags
DisableFlagsInUseLine: true,
Args: cobra.ExactArgs(1),
Hidden: true,
Example: `
# Delete a discovery source
tanzu plugin discovery delete default`,
Expand Down Expand Up @@ -248,6 +147,8 @@ func newInitDiscoverySourceCmd() *cobra.Command {
Use: "init",
Short: "Initialize the discovery source to its default value",
Args: cobra.MaximumNArgs(0),
// There are no flags
DisableFlagsInUseLine: true,
RunE: func(cmd *cobra.Command, args []string) error {
err := config.PopulateDefaultCentralDiscovery(true)
if err != nil {
Expand All @@ -261,28 +162,18 @@ func newInitDiscoverySourceCmd() *cobra.Command {
return initDiscoverySourceCmd
}

func createDiscoverySource(dsType, dsName, uri string) (configtypes.PluginDiscovery, error) {
func createDiscoverySource(dsName, uri string) (configtypes.PluginDiscovery, error) {
pluginDiscoverySource := configtypes.PluginDiscovery{}
if dsType == "" {
return pluginDiscoverySource, errors.New("discovery source type cannot be empty")
}

if dsName == "" {
return pluginDiscoverySource, errors.New("discovery source name cannot be empty")
}

switch strings.ToLower(dsType) {
case common.DiscoveryTypeLocal:
pluginDiscoverySource.Local = createLocalDiscoverySource(dsName, uri)
case common.DiscoveryTypeOCI:
pluginDiscoverySource.OCI = createOCIDiscoverySource(dsName, uri)
case common.DiscoveryTypeREST:
pluginDiscoverySource.REST = createRESTDiscoverySource(dsName, uri)
case common.DiscoveryTypeGCP, common.DiscoveryTypeKubernetes:
return pluginDiscoverySource, errors.Errorf("discovery source type '%s' is not yet supported", dsType)
default:
return pluginDiscoverySource, errors.Errorf("unknown discovery source type '%s'", dsType)
}

pluginDiscoverySource = configtypes.PluginDiscovery{
OCI: &configtypes.OCIDiscovery{
Name: dsName,
Image: uri,
}}
err := checkDiscoverySource(pluginDiscoverySource)
return pluginDiscoverySource, err
}
Expand All @@ -297,41 +188,3 @@ func checkDiscoverySource(source configtypes.PluginDiscovery) error {
_, err = discObject.List()
return err
}

func createLocalDiscoverySource(discoveryName, uri string) *configtypes.LocalDiscovery {
return &configtypes.LocalDiscovery{
Name: discoveryName,
Path: uri,
}
}

func createOCIDiscoverySource(discoveryName, uri string) *configtypes.OCIDiscovery {
return &configtypes.OCIDiscovery{
Name: discoveryName,
Image: uri,
}
}

func createRESTDiscoverySource(discoveryName, uri string) *configtypes.GenericRESTDiscovery {
return &configtypes.GenericRESTDiscovery{
Name: discoveryName,
Endpoint: uri,
}
}

func discoverySourceNameAndType(ds configtypes.PluginDiscovery) (string, string) {
switch {
case ds.GCP != nil: // nolint:staticcheck // Deprecated
return ds.GCP.Name, common.DiscoveryTypeGCP // nolint:staticcheck // Deprecated
case ds.Kubernetes != nil:
return ds.Kubernetes.Name, common.DiscoveryTypeKubernetes
case ds.Local != nil:
return ds.Local.Name, common.DiscoveryTypeLocal
case ds.OCI != nil:
return ds.OCI.Name, common.DiscoveryTypeOCI
case ds.REST != nil:
return ds.REST.Name, common.DiscoveryTypeREST
default:
return "-", "Unknown" // Unknown discovery source found
}
}
Loading
Loading