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 dev, stg prefixes #86

Merged
merged 14 commits into from
Dec 16, 2024
33 changes: 24 additions & 9 deletions cmd/common/apiResources.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,29 @@ func ListAPIResources(serviceName string) error {
}

func getServiceEndpoint(config *Config, serviceName string) (string, error) {
envConfig := config.Environments[config.Environment]
if envConfig.URL == "" {
return "", fmt.Errorf("URL not found in environment config")
}

// Parse URL to get environment
urlParts := strings.Split(envConfig.URL, ".")
if len(urlParts) < 4 {
return "", fmt.Errorf("invalid URL format: %s", envConfig.URL)
}

var envPrefix string
if strings.HasPrefix(config.Environment, "dev-") {
envPrefix = "dev"
} else if strings.HasPrefix(config.Environment, "stg-") {
envPrefix = "stg"
} else {
return "", fmt.Errorf("unsupported environment prefix")
for i, part := range urlParts {
if part == "console" && i+1 < len(urlParts) {
envPrefix = urlParts[i+1] // Get the part after "console" (dev or stg)
break
}
}

if envPrefix == "" {
return "", fmt.Errorf("environment prefix not found in URL: %s", envConfig.URL)
}

endpoint := fmt.Sprintf("grpc+ssl://%s.api.%s.spaceone.dev:443", serviceName, envPrefix)
return endpoint, nil
}
Expand Down Expand Up @@ -122,16 +137,16 @@ func fetchServiceResources(serviceName, endpoint string, shortNamesMap map[strin
return nil, fmt.Errorf("failed to list services: %v", err)
}

// Load short names from setting.toml
// Load short names from setting.yaml
home, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get home directory: %v", err)
}

settingPath := filepath.Join(home, ".cfctl", "setting.toml")
settingPath := filepath.Join(home, ".cfctl", "setting.yaml")
v := viper.New()
v.SetConfigFile(settingPath)
v.SetConfigType("toml")
v.SetConfigType("yaml")

serviceShortNames := make(map[string]string)
if err := v.ReadInConfig(); err == nil {
Expand Down
58 changes: 37 additions & 21 deletions cmd/common/fetchService.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,16 @@ import (
"gopkg.in/yaml.v3"
)

// Config structure to parse environment files
type Config struct {
Environment string `yaml:"environment"`
Environments map[string]Environment `yaml:"environments"`
}

type Environment struct {
Endpoint string `yaml:"endpoint"`
Proxy string `yaml:"proxy"`
Proxy string `yaml:"proxy"`
Token string `yaml:"token"`
URL string `yaml:"url"`
}

type Config struct {
Environment string `yaml:"environment"`
Environments map[string]Environment `yaml:"environments"`
}

// FetchService handles the execution of gRPC commands for all services
Expand All @@ -54,8 +54,8 @@ func FetchService(serviceName string, verb string, resourceName string, options

// Read configuration file
mainViper := viper.New()
mainViper.SetConfigFile(filepath.Join(homeDir, ".cfctl", "setting.toml"))
mainViper.SetConfigType("toml")
mainViper.SetConfigFile(filepath.Join(homeDir, ".cfctl", "setting.yaml"))
mainViper.SetConfigType("yaml")
if err := mainViper.ReadInConfig(); err != nil {
return nil, fmt.Errorf("failed to read configuration file. Please run 'cfctl login' first")
}
Expand Down Expand Up @@ -158,12 +158,19 @@ func FetchService(serviceName string, verb string, resourceName string, options

// Get hostPort based on environment prefix
var envPrefix string
if strings.HasPrefix(config.Environment, "dev-") {
envPrefix = "dev"
} else if strings.HasPrefix(config.Environment, "stg-") {
envPrefix = "stg"
urlParts := strings.Split(config.Environments[config.Environment].URL, ".")
for i, part := range urlParts {
if part == "console" && i+1 < len(urlParts) {
envPrefix = urlParts[i+1] // Get the part after "console" (dev or stg)
break
}
}

if envPrefix == "" {
return nil, fmt.Errorf("environment prefix not found in URL: %s", config.Environments[config.Environment].URL)
}
hostPort := fmt.Sprintf("%s.api.%s.spaceone.dev:443", serviceName, envPrefix)

hostPort := fmt.Sprintf("%s.api.%s.spaceone.dev:443", convertServiceNameToEndpoint(serviceName), envPrefix)

// Configure gRPC connection
var conn *grpc.ClientConn
Expand Down Expand Up @@ -316,9 +323,9 @@ func loadConfig() (*Config, error) {

// Load main configuration file
mainV := viper.New()
mainConfigPath := filepath.Join(home, ".cfctl", "setting.toml")
mainConfigPath := filepath.Join(home, ".cfctl", "setting.yaml")
mainV.SetConfigFile(mainConfigPath)
mainV.SetConfigType("toml")
mainV.SetConfigType("yaml")
if err := mainV.ReadInConfig(); err != nil {
return nil, fmt.Errorf("failed to read config file: %v", err)
}
Expand All @@ -332,6 +339,7 @@ func loadConfig() (*Config, error) {
envConfig := &Environment{
Endpoint: mainV.GetString(fmt.Sprintf("environments.%s.endpoint", currentEnv)),
Proxy: mainV.GetString(fmt.Sprintf("environments.%s.proxy", currentEnv)),
URL: mainV.GetString(fmt.Sprintf("environments.%s.url", currentEnv)),
}

// Handle token based on environment type
Expand Down Expand Up @@ -374,12 +382,20 @@ func fetchJSONResponse(config *Config, serviceName string, verb string, resource
}
} else {
var envPrefix string
if strings.HasPrefix(config.Environment, "dev-") {
envPrefix = "dev"
} else if strings.HasPrefix(config.Environment, "stg-") {
envPrefix = "stg"
urlParts := strings.Split(config.Environments[config.Environment].URL, ".")
for i, part := range urlParts {
if part == "console" && i+1 < len(urlParts) {
envPrefix = urlParts[i+1]
break
}
}

if envPrefix == "" {
return nil, fmt.Errorf("environment prefix not found in URL: %s", config.Environments[config.Environment].URL)
}
hostPort := fmt.Sprintf("%s.api.%s.spaceone.dev:443", serviceName, envPrefix)

hostPort := fmt.Sprintf("%s.api.%s.spaceone.dev:443", convertServiceNameToEndpoint(serviceName), envPrefix)

tlsConfig := &tls.Config{
InsecureSkipVerify: false,
}
Expand Down
58 changes: 2 additions & 56 deletions cmd/common/fetchVerb.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,31 +54,7 @@ func AddVerbCommands(parentCmd *cobra.Command, serviceName string, groupID strin
verbCmd := &cobra.Command{
Use: currentVerb + " <resource>",
Short: shortDesc,
Long: fmt.Sprintf(`Supported %d resources for %s command.

%s

%s`,
len(resources),
currentVerb,
pterm.DefaultBox.WithTitle("Interactive Mode").WithTitleTopCenter().Sprint(
func() string {
str, _ := pterm.DefaultBulletList.WithItems([]pterm.BulletListItem{
{Level: 0, Text: "Required parameters will be prompted if not provided"},
{Level: 0, Text: "Missing parameters will be requested interactively"},
{Level: 0, Text: "Just follow the prompts to fill in the required fields"},
}).Srender()
return str
}()),
pterm.DefaultBox.WithTitle("Example").WithTitleTopCenter().Sprint(
fmt.Sprintf("List resources:\n"+
" $ cfctl %s list <Resource>\n\n"+
"List and sort by field:\n"+
" $ cfctl %s list <Resource> -s name\n"+
" $ cfctl %s list <Resource> -s created_at\n\n"+
"Watch for changes:\n"+
" $ cfctl %s list <Resource> -w",
serviceName, serviceName, serviceName, serviceName))),
Long: fmt.Sprintf("Supported %d resources for %s command.", len(resources), currentVerb),
Args: cobra.ArbitraryArgs, // Allow any number of arguments
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
Expand All @@ -101,10 +77,6 @@ func AddVerbCommands(parentCmd *cobra.Command, serviceName string, groupID strin
if err != nil {
return err
}
apiVersion, err := cmd.Flags().GetString("api-version")
if err != nil {
return err
}
outputFormat, err := cmd.Flags().GetString("output")
if err != nil {
return err
Expand All @@ -127,7 +99,6 @@ func AddVerbCommands(parentCmd *cobra.Command, serviceName string, groupID strin
Parameters: parameters,
JSONParameter: jsonParameter,
FileParameter: fileParameter,
APIVersion: apiVersion,
OutputFormat: outputFormat,
CopyToClipboard: copyToClipboard,
SortBy: sortBy,
Expand Down Expand Up @@ -171,7 +142,6 @@ func AddVerbCommands(parentCmd *cobra.Command, serviceName string, groupID strin
verbCmd.Flags().StringArrayP("parameter", "p", []string{}, "Input Parameter (-p <key>=<value> -p ...)")
verbCmd.Flags().StringP("json-parameter", "j", "", "JSON type parameter")
verbCmd.Flags().StringP("file-parameter", "f", "", "YAML file parameter")
verbCmd.Flags().StringP("api-version", "v", "v1", "API Version")
verbCmd.Flags().StringP("output", "o", "yaml", "Output format (yaml, json, table, csv)")
verbCmd.Flags().BoolP("copy", "y", false, "Copy the output to the clipboard (copies any output format)")

Expand All @@ -180,31 +150,7 @@ func AddVerbCommands(parentCmd *cobra.Command, serviceName string, groupID strin

// Update example for list command
if currentVerb == "list" {
verbCmd.Long = fmt.Sprintf(`Supported %d resources for %s command.

%s

%s`,
len(resources),
currentVerb,
pterm.DefaultBox.WithTitle("Interactive Mode").WithTitleTopCenter().Sprint(
func() string {
str, _ := pterm.DefaultBulletList.WithItems([]pterm.BulletListItem{
{Level: 0, Text: "Required parameters will be prompted if not provided"},
{Level: 0, Text: "Missing parameters will be requested interactively"},
{Level: 0, Text: "Just follow the prompts to fill in the required fields"},
}).Srender()
return str
}()),
pterm.DefaultBox.WithTitle("Example").WithTitleTopCenter().Sprint(
fmt.Sprintf("List resources:\n"+
" $ cfctl %s list <Resource>\n\n"+
"List and sort by field:\n"+
" $ cfctl %s list <Resource> -s name\n"+
" $ cfctl %s list <Resource> -s created_at\n\n"+
"Watch for changes:\n"+
" $ cfctl %s list <Resource> -w",
serviceName, serviceName, serviceName, serviceName)))
verbCmd.Long = fmt.Sprintf("Supported %d resources for %s command.", len(resources), currentVerb)
}

parentCmd.AddCommand(verbCmd)
Expand Down
Loading
Loading