From d3b77fda1a72c76726186299c2c6a9bfbd9403da Mon Sep 17 00:00:00 2001 From: Youngjin Jo Date: Tue, 17 Dec 2024 01:05:00 +0900 Subject: [PATCH 1/4] refactor: remove http protocol Signed-off-by: Youngjin Jo --- cmd/other/setting.go | 52 ++++---------------------------------------- cmd/root.go | 9 ++++---- 2 files changed, 8 insertions(+), 53 deletions(-) diff --git a/cmd/other/setting.go b/cmd/other/setting.go index ca1f6f5..52e2079 100644 --- a/cmd/other/setting.go +++ b/cmd/other/setting.go @@ -139,12 +139,6 @@ var settingInitLocalCmd = &cobra.Command{ return fmt.Errorf("conflicting flags") } - // Plugin flag takes precedence - if pluginFlag { - initializePluginSetting(localEnv) - return - } - // Rest of the existing implementation... settingDir := GetSettingDir() if err := os.MkdirAll(settingDir, 0755); err != nil { @@ -171,7 +165,7 @@ var settingInitLocalCmd = &cobra.Command{ // Create initial configuration envConfig := map[string]interface{}{ "endpoint": "grpc://localhost:50051", - "url": "http://localhost:8080", + "url": "http://localhost:8080", } // Add specific fields based on configuration type @@ -252,47 +246,6 @@ func initializePluginSetting(pluginName string) { pterm.Success.Printf("Plugin environment '%s' successfully initialized.\n", envName) } -func initializePluginSetting(pluginName string) { - // Add 'local-' prefix to plugin name - envName := fmt.Sprintf("local-%s", pluginName) - - settingDir := GetSettingDir() - if err := os.MkdirAll(settingDir, 0755); err != nil { - pterm.Error.Printf("Failed to create setting directory: %v\n", err) - return - } - - mainSettingPath := filepath.Join(settingDir, "setting.toml") - if _, err := os.Stat(mainSettingPath); os.IsNotExist(err) { - initialSetting := []byte("environments = {}\n") - if err := os.WriteFile(mainSettingPath, initialSetting, 0644); err != nil { - pterm.Error.Printf("Failed to create setting file: %v\n", err) - return - } - } - - v := viper.New() - v.SetConfigFile(mainSettingPath) - v.SetConfigType("toml") - - if err := v.ReadInConfig(); err != nil && !os.IsNotExist(err) { - pterm.Error.Printf("Error reading setting: %v\n", err) - return - } - - // Set environment configuration using the prefixed name - v.Set(fmt.Sprintf("environments.%s.endpoint", envName), "grpc://localhost:50051") - v.Set(fmt.Sprintf("environments.%s.token", envName), "NO TOKEN") - v.Set("environment", envName) - - if err := v.WriteConfig(); err != nil { - pterm.Error.Printf("Failed to write setting: %v\n", err) - return - } - - pterm.Success.Printf("Plugin environment '%s' successfully initialized.\n", envName) -} - func updateLocalSetting(envName, settingType, settingPath string) { v := viper.New() v.SetConfigFile(settingPath) @@ -1092,6 +1045,9 @@ func parseEnvNameFromURL(urlStr string) (string, error) { // updateSetting updates the configuration files func updateSetting(envName, urlStr, settingType string) { + urlStr = strings.TrimPrefix(urlStr, "https://") + urlStr = strings.TrimPrefix(urlStr, "http://") + settingDir := GetSettingDir() mainSettingPath := filepath.Join(settingDir, "setting.yaml") diff --git a/cmd/root.go b/cmd/root.go index c802550..4036a5c 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -191,7 +191,7 @@ func showInitializationGuide(originalErr error) { // Fallback URL if not specified in config parts := strings.Split(currentEnv, "-") if len(parts) >= 2 { - serviceName := parts[0] // cloudone, spaceone, etc. + serviceName := parts[0] // cloudone, spaceone, etc. url = fmt.Sprintf("https://%s.console.dev.spaceone.dev", serviceName) } else { url = "https://console.spaceone.dev" @@ -336,7 +336,6 @@ func addDynamicServiceCommands() error { return nil } - func loadCachedEndpoints() (map[string]string, error) { home, err := os.UserHomeDir() if err != nil { @@ -479,9 +478,9 @@ func loadConfig() (*Config, error) { func createServiceCommand(serviceName string) *cobra.Command { cmd := &cobra.Command{ - Use: serviceName, - Short: fmt.Sprintf("Interact with the %s service", serviceName), - Long: fmt.Sprintf("Use this command to interact with the %s service.", serviceName), + Use: serviceName, + Short: fmt.Sprintf("Interact with the %s service", serviceName), + Long: fmt.Sprintf("Use this command to interact with the %s service.", serviceName), GroupID: "available", } From 2cea9f45bd2fe6cf37a4746971b690ba449e5507 Mon Sep 17 00:00:00 2001 From: Youngjin Jo Date: Tue, 17 Dec 2024 02:03:47 +0900 Subject: [PATCH 2/4] refactor: show current configuration Signed-off-by: Youngjin Jo --- cmd/other/setting.go | 70 ++++++++++++++++++++++++++++---------------- 1 file changed, 45 insertions(+), 25 deletions(-) diff --git a/cmd/other/setting.go b/cmd/other/setting.go index 52e2079..efbb846 100644 --- a/cmd/other/setting.go +++ b/cmd/other/setting.go @@ -71,7 +71,6 @@ var settingInitURLCmd = &cobra.Command{ return } - // Create setting directory if it doesn't exist settingDir := GetSettingDir() if err := os.MkdirAll(settingDir, 0755); err != nil { pterm.Error.Printf("Failed to create setting directory: %v\n", err) @@ -79,8 +78,6 @@ var settingInitURLCmd = &cobra.Command{ } mainSettingPath := filepath.Join(settingDir, "setting.yaml") - - // Check if environment already exists v := viper.New() v.SetConfigFile(mainSettingPath) v.SetConfigType("yaml") @@ -89,10 +86,15 @@ var settingInitURLCmd = &cobra.Command{ fullEnvName := fmt.Sprintf("%s-%s", envName, envSuffix) if err := v.ReadInConfig(); err == nil { - // File exists and can be read environments := v.GetStringMap("environments") - if _, exists := environments[fullEnvName]; exists { - // Environment exists, ask for confirmation + if existingEnv, exists := environments[fullEnvName]; exists { + currentConfig, _ := yaml.Marshal(map[string]interface{}{ + "environment": fullEnvName, + "environments": map[string]interface{}{ + fullEnvName: existingEnv, + }, + }) + confirmBox := pterm.DefaultBox.WithTitle("Environment Already Exists"). WithTitleTopCenter(). WithRightPadding(4). @@ -101,6 +103,9 @@ var settingInitURLCmd = &cobra.Command{ confirmBox.Println(fmt.Sprintf("Environment '%s' already exists.\nDo you want to overwrite it?", fullEnvName)) + pterm.Info.Println("Current configuration:") + fmt.Println(string(currentConfig)) + fmt.Print("\nEnter (y/N): ") var response string fmt.Scanln(&response) @@ -127,57 +132,72 @@ var settingInitLocalCmd = &cobra.Command{ appFlag, _ := cmd.Flags().GetBool("app") userFlag, _ := cmd.Flags().GetBool("user") - // Validate that either app or user flag is provided if !appFlag && !userFlag { pterm.Error.Println("You must specify either --app or --user flag.") return fmt.Errorf("missing required flag") } - // Validate that not both flags are provided if appFlag && userFlag { pterm.Error.Println("Cannot use both --app and --user flags together.") return fmt.Errorf("conflicting flags") } - // Rest of the existing implementation... settingDir := GetSettingDir() - if err := os.MkdirAll(settingDir, 0755); err != nil { - return fmt.Errorf("failed to create setting directory: %v", err) - } - mainSettingPath := filepath.Join(settingDir, "setting.yaml") - // Basic local environment envName := "local" - - // Add app/user suffix based on flag if appFlag { envName = fmt.Sprintf("%s-app", envName) } else { envName = fmt.Sprintf("%s-user", envName) } - // Initialize or update the settings v := viper.New() v.SetConfigFile(mainSettingPath) v.SetConfigType("yaml") - // Create initial configuration + if err := v.ReadInConfig(); err == nil { + environments := v.GetStringMap("environments") + if existingEnv, exists := environments[envName]; exists { + currentConfig, _ := yaml.Marshal(map[string]interface{}{ + "environment": envName, + "environments": map[string]interface{}{ + envName: existingEnv, + }, + }) + + confirmBox := pterm.DefaultBox.WithTitle("Environment Already Exists"). + WithTitleTopCenter(). + WithRightPadding(4). + WithLeftPadding(4). + WithBoxStyle(pterm.NewStyle(pterm.FgYellow)) + + confirmBox.Println(fmt.Sprintf("Environment '%s' already exists.\nDo you want to overwrite it?", envName)) + + pterm.Info.Println("Current configuration:") + fmt.Println(string(currentConfig)) + + fmt.Print("\nEnter (y/N): ") + var response string + fmt.Scanln(&response) + response = strings.ToLower(strings.TrimSpace(response)) + + if response != "y" { + pterm.Info.Printf("Operation cancelled. Environment '%s' remains unchanged.\n", envName) + return nil + } + } + } + envConfig := map[string]interface{}{ "endpoint": "grpc://localhost:50051", "url": "http://localhost:8080", } - // Add specific fields based on configuration type if appFlag { - envConfig["token"] = "" - } - - if err := v.ReadInConfig(); err != nil && !os.IsNotExist(err) { - return fmt.Errorf("error reading setting: %v", err) + envConfig["token"] = "no_token" } - // Set environment configuration v.Set(fmt.Sprintf("environments.%s", envName), envConfig) v.Set("environment", envName) From 1552c85ad3d50c3ebc502d0a60d8c5889c8a05d9 Mon Sep 17 00:00:00 2001 From: Youngjin Jo Date: Tue, 17 Dec 2024 02:14:50 +0900 Subject: [PATCH 3/4] refactor: add command for local env Signed-off-by: Youngjin Jo --- cmd/common/fetchService.go | 5 ++--- cmd/common/helpers.go | 42 +++++++++++++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/cmd/common/fetchService.go b/cmd/common/fetchService.go index c0be6fb..8089cf3 100644 --- a/cmd/common/fetchService.go +++ b/cmd/common/fetchService.go @@ -35,7 +35,7 @@ import ( type Environment struct { Endpoint string `yaml:"endpoint"` - Proxy string `yaml:"proxy"` + Proxy string `yaml:"proxy"` Token string `yaml:"token"` URL string `yaml:"url"` } @@ -339,7 +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)), + URL: mainV.GetString(fmt.Sprintf("environments.%s.url", currentEnv)), } // Handle token based on environment type @@ -925,7 +925,6 @@ func formatTableValue(val interface{}) string { } func printCSV(data map[string]interface{}) string { - // CSV writer 생성 writer := csv.NewWriter(os.Stdout) defer writer.Flush() diff --git a/cmd/common/helpers.go b/cmd/common/helpers.go index 5c0cbf0..20ec66c 100644 --- a/cmd/common/helpers.go +++ b/cmd/common/helpers.go @@ -31,7 +31,6 @@ func convertServiceNameToEndpoint(serviceName string) string { return strings.ReplaceAll(serviceName, "_", "-") } - func BuildVerbResourceMap(serviceName string) (map[string][]string, error) { // Try to load from cache first home, err := os.UserHomeDir() @@ -44,6 +43,47 @@ func BuildVerbResourceMap(serviceName string) (map[string][]string, error) { return nil, fmt.Errorf("failed to load config: %v", err) } + if strings.HasPrefix(config.Environment, "local-") { + conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure()) + if err != nil { + return nil, fmt.Errorf("failed to connect to local server: %v", err) + } + defer conn.Close() + + ctx := context.Background() + refClient := grpcreflect.NewClient(ctx, grpc_reflection_v1alpha.NewServerReflectionClient(conn)) + defer refClient.Reset() + + verbResourceMap := make(map[string][]string) + services, err := refClient.ListServices() + if err != nil { + return nil, fmt.Errorf("failed to list services: %v", err) + } + + for _, s := range services { + if !strings.Contains(s, fmt.Sprintf(".%s.", serviceName)) { + continue + } + + serviceDesc, err := refClient.ResolveService(s) + if err != nil { + continue + } + + resourceName := s[strings.LastIndex(s, ".")+1:] + for _, method := range serviceDesc.GetMethods() { + verb := method.GetName() + if resources, ok := verbResourceMap[verb]; ok { + verbResourceMap[verb] = append(resources, resourceName) + } else { + verbResourceMap[verb] = []string{resourceName} + } + } + } + + return verbResourceMap, nil + } + cacheDir := filepath.Join(home, ".cfctl", "cache", config.Environment) cacheFile := filepath.Join(cacheDir, fmt.Sprintf("%s_verbs.yaml", serviceName)) From 7ad310a0739d09375ad74051e9c4b6fd5b2b459f Mon Sep 17 00:00:00 2001 From: Youngjin Jo Date: Tue, 17 Dec 2024 02:29:09 +0900 Subject: [PATCH 4/4] refactor: add verb, resource for local env Signed-off-by: Youngjin Jo --- cmd/common/helpers.go | 41 ----------------------------------------- 1 file changed, 41 deletions(-) diff --git a/cmd/common/helpers.go b/cmd/common/helpers.go index 20ec66c..1969427 100644 --- a/cmd/common/helpers.go +++ b/cmd/common/helpers.go @@ -43,47 +43,6 @@ func BuildVerbResourceMap(serviceName string) (map[string][]string, error) { return nil, fmt.Errorf("failed to load config: %v", err) } - if strings.HasPrefix(config.Environment, "local-") { - conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure()) - if err != nil { - return nil, fmt.Errorf("failed to connect to local server: %v", err) - } - defer conn.Close() - - ctx := context.Background() - refClient := grpcreflect.NewClient(ctx, grpc_reflection_v1alpha.NewServerReflectionClient(conn)) - defer refClient.Reset() - - verbResourceMap := make(map[string][]string) - services, err := refClient.ListServices() - if err != nil { - return nil, fmt.Errorf("failed to list services: %v", err) - } - - for _, s := range services { - if !strings.Contains(s, fmt.Sprintf(".%s.", serviceName)) { - continue - } - - serviceDesc, err := refClient.ResolveService(s) - if err != nil { - continue - } - - resourceName := s[strings.LastIndex(s, ".")+1:] - for _, method := range serviceDesc.GetMethods() { - verb := method.GetName() - if resources, ok := verbResourceMap[verb]; ok { - verbResourceMap[verb] = append(resources, resourceName) - } else { - verbResourceMap[verb] = []string{resourceName} - } - } - } - - return verbResourceMap, nil - } - cacheDir := filepath.Join(home, ".cfctl", "cache", config.Environment) cacheFile := filepath.Join(cacheDir, fmt.Sprintf("%s_verbs.yaml", serviceName))