Skip to content

Commit

Permalink
Merge pull request #87 from yjinjo/master
Browse files Browse the repository at this point in the history
Add verbs and resources for local env
  • Loading branch information
yjinjo authored Dec 16, 2024
2 parents 643f547 + 7ad310a commit 25134b4
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 82 deletions.
5 changes: 2 additions & 3 deletions cmd/common/fetchService.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()

Expand Down
1 change: 0 additions & 1 deletion cmd/common/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
122 changes: 49 additions & 73 deletions cmd/other/setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,16 +71,13 @@ 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)
return
}

mainSettingPath := filepath.Join(settingDir, "setting.yaml")

// Check if environment already exists
v := viper.New()
v.SetConfigFile(mainSettingPath)
v.SetConfigType("yaml")
Expand All @@ -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).
Expand All @@ -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)
Expand All @@ -127,63 +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")
}

// Plugin flag takes precedence
if pluginFlag {
initializePluginSetting(localEnv)
return
}

// 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",
"url": "http://localhost:8080",
}

// Add specific fields based on configuration type
if appFlag {
envConfig["token"] = ""
envConfig["token"] = "no_token"
}

if err := v.ReadInConfig(); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("error reading setting: %v", err)
}

// Set environment configuration
v.Set(fmt.Sprintf("environments.%s", envName), envConfig)
v.Set("environment", envName)

Expand Down Expand Up @@ -252,47 +266,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)
Expand Down Expand Up @@ -1092,6 +1065,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")

Expand Down
9 changes: 4 additions & 5 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -336,7 +336,6 @@ func addDynamicServiceCommands() error {
return nil
}


func loadCachedEndpoints() (map[string]string, error) {
home, err := os.UserHomeDir()
if err != nil {
Expand Down Expand Up @@ -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",
}

Expand Down

0 comments on commit 25134b4

Please sign in to comment.