Skip to content

Commit

Permalink
Merge pull request #28 from yjinjo/v0
Browse files Browse the repository at this point in the history
Allow only yaml and add proxy, static, and dynamic mode
  • Loading branch information
yjinjo authored Nov 18, 2024
2 parents bed4542 + 57d9cba commit 831d5d9
Showing 1 changed file with 106 additions and 11 deletions.
117 changes: 106 additions & 11 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ import (

var envFile string

var availableServices = []string{
"identity", "inventory", "plugin", "repository", "secret",
"monitoring", "config", "statistics", "notification",
"cost_analysis", "board", "file_manager", "dashboard",
}

// configCmd represents the config command
var configCmd = &cobra.Command{
Use: "config",
Expand Down Expand Up @@ -91,9 +97,12 @@ var configInitCmd = &cobra.Command{
baseURL = "grpc+ssl://identity.api.stg.spaceone.dev:443"
}

// Set endpoint, token, and proxy fields for the environment
if baseURL != "" {
viper.Set(fmt.Sprintf("environments.%s.endpoint", envName), baseURL)
}
viper.Set(fmt.Sprintf("environments.%s.token", envName), "") // Add token as an empty value
viper.Set(fmt.Sprintf("environments.%s.proxy", envName), true) // Set proxy to true

// Set the current environment
viper.Set("environment", envName)
Expand Down Expand Up @@ -121,11 +130,9 @@ var envCmd = &cobra.Command{

// Handle environment switching
if switchEnv != "" {
// Check for both .yaml and .yml extensions
// Check only for .yaml extensions
if _, err := os.Stat(filepath.Join(getConfigDir(), "environments", switchEnv+".yaml")); os.IsNotExist(err) {
if _, err := os.Stat(filepath.Join(getConfigDir(), "environments", switchEnv+".yml")); os.IsNotExist(err) {
log.Fatalf("Environment '%s' not found.", switchEnv)
}
log.Fatalf("Environment '%s' not found.", switchEnv)
}

// Update the environment in ~/.spaceone/config.yaml
Expand Down Expand Up @@ -155,11 +162,9 @@ var envCmd = &cobra.Command{

// Handle environment removal with confirmation
if removeEnv != "" {
// Check for both .yaml and .yml extensions
// Check only for .yaml extensions
if _, err := os.Stat(filepath.Join(getConfigDir(), "environments", removeEnv+".yaml")); os.IsNotExist(err) {
if _, err := os.Stat(filepath.Join(getConfigDir(), "environments", removeEnv+".yml")); os.IsNotExist(err) {
log.Fatalf("Environment '%s' not found.", removeEnv)
}
log.Fatalf("Environment '%s' not found.", removeEnv)
}

// Ask for confirmation before deletion
Expand All @@ -171,7 +176,6 @@ var envCmd = &cobra.Command{
if response == "y" {
// Remove the environment file
os.Remove(filepath.Join(getConfigDir(), "environments", removeEnv+".yaml"))
os.Remove(filepath.Join(getConfigDir(), "environments", removeEnv+".yml"))

// Check if this environment is set in config.yaml and clear it if so
configFilePath := filepath.Join(getConfigDir(), "config.yaml")
Expand Down Expand Up @@ -222,7 +226,7 @@ var envCmd = &cobra.Command{
pterm.Println("Available Environments:")
for _, entry := range entries {
name := entry.Name()
name = strings.TrimSuffix(name, filepath.Ext(name)) // Remove ".yaml" or ".yml" extension
name = strings.TrimSuffix(name, ".yaml") // Remove ".yaml" extension
if name == currentEnv {
pterm.FgGreen.Printf(" > %s (current)\n", name)
} else {
Expand Down Expand Up @@ -288,6 +292,93 @@ var showCmd = &cobra.Command{
},
}

// configEndpointCmd updates the endpoint for the current environment
var configEndpointCmd = &cobra.Command{
Use: "endpoint",
Short: "Set the endpoint for the current environment",
Long: `Update the endpoint for the current environment based on the specified service.
If the service is not 'identity', the proxy setting will be updated to false.
Available Services:
identity, inventory, plugin, repository, secret, monitoring, config, statistics,
notification, cost_analysis, board, file_manager, dashboard`,
Run: func(cmd *cobra.Command, args []string) {
service, _ := cmd.Flags().GetString("service")
if service == "" {
pterm.Error.Println("Please specify a service using -s or --service.")
pterm.Println()
pterm.DefaultBox.WithTitle("Available Services").
WithRightPadding(1).WithLeftPadding(1).WithTopPadding(0).WithBottomPadding(0).
Println(strings.Join(availableServices, "\n"))
return
}

// Validate the service name
isValidService := false
for _, validService := range availableServices {
if service == validService {
isValidService = true
break
}
}

if !isValidService {
pterm.Error.Printf("Invalid service '%s'.\n", service)
pterm.Println()
pterm.DefaultBox.WithTitle("Available Services").
WithRightPadding(1).WithLeftPadding(1).WithTopPadding(0).WithBottomPadding(0).
Println(strings.Join(availableServices, "\n"))
return
}

currentEnv := getCurrentEnvironment()
if currentEnv == "" {
pterm.Error.Println("No environment is set. Please initialize or switch to an environment.")
return
}

// Determine prefix from the current environment
var prefix string
if strings.HasPrefix(currentEnv, "dev-") {
prefix = "dev"
} else if strings.HasPrefix(currentEnv, "stg-") {
prefix = "stg"
} else {
pterm.Error.Printf("Unsupported environment prefix for '%s'.\n", currentEnv)
return
}

// Construct new endpoint
newEndpoint := fmt.Sprintf("grpc+ssl://%s.api.%s.spaceone.dev:443", service, prefix)

// Load config
configPath := filepath.Join(getConfigDir(), "config.yaml")
viper.SetConfigFile(configPath)
if err := viper.ReadInConfig(); err != nil {
pterm.Error.Printf("Failed to read config.yaml: %v\n", err)
return
}

// Update endpoint
viper.Set(fmt.Sprintf("environments.%s.endpoint", currentEnv), newEndpoint)

// Update proxy based on service
if service != "identity" {
viper.Set(fmt.Sprintf("environments.%s.proxy", currentEnv), false)
} else {
viper.Set(fmt.Sprintf("environments.%s.proxy", currentEnv), true)
}

// Save updated config
if err := viper.WriteConfig(); err != nil {
pterm.Error.Printf("Failed to update config.yaml: %v\n", err)
return
}

pterm.Success.Printf("Updated endpoint for '%s' to '%s'.\n", currentEnv, newEndpoint)
},
}

// syncCmd syncs the environments in ~/.spaceone/environments with ~/.spaceone/config.yaml
var syncCmd = &cobra.Command{
Use: "sync",
Expand All @@ -309,7 +400,7 @@ var syncCmd = &cobra.Command{
}

for _, entry := range entries {
if !entry.IsDir() && (filepath.Ext(entry.Name()) == ".yaml" || filepath.Ext(entry.Name()) == ".yml") {
if !entry.IsDir() && (filepath.Ext(entry.Name()) == ".yaml") {
envName := strings.TrimSuffix(entry.Name(), filepath.Ext(entry.Name()))

// Check if the environment already has a URL; if not, set it to an empty string
Expand Down Expand Up @@ -403,6 +494,7 @@ func init() {
configCmd.AddCommand(configInitCmd)
configCmd.AddCommand(envCmd)
configCmd.AddCommand(showCmd)
configCmd.AddCommand(configEndpointCmd)
configCmd.AddCommand(syncCmd)

// Defining flags for configInitCmd
Expand All @@ -418,5 +510,8 @@ func init() {
// Defining flags for showCmd
showCmd.Flags().StringP("output", "o", "yaml", "Output format (yaml/json)")

// Add flags for configEndpointCmd
configEndpointCmd.Flags().StringP("service", "s", "", "Service to set the endpoint for")

viper.SetConfigType("yaml")
}

0 comments on commit 831d5d9

Please sign in to comment.