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

Modify the config and login function #26

Merged
merged 5 commits into from
Nov 14, 2024
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
162 changes: 94 additions & 68 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,26 +40,21 @@ var configInitCmd = &cobra.Command{
urlStr, _ := cmd.Flags().GetString("url")
localEnv, _ := cmd.Flags().GetString("local")

// If both url and local flags are empty, show help and return
if urlStr == "" && localEnv == "" {
cmd.Help()
return
}

// Determine environment name
var envName string
if localEnv != "" {
// Use local environment name directly
envName = localEnv
envName = fmt.Sprintf("%s-user", localEnv)
if urlStr == "" {
urlStr = "http://localhost:8080"
}
} else {
// Ensure URL has a scheme; default to "https" if missing
if !strings.HasPrefix(urlStr, "http://") && !strings.HasPrefix(urlStr, "https://") {
urlStr = "https://" + urlStr
}
// Parse environment name from URL
parsedEnvName, err := parseEnvNameFromURL(urlStr)
if err != nil {
pterm.Error.WithShowLineNumber(false).Println("Invalid URL format:", err)
Expand All @@ -69,73 +64,60 @@ var configInitCmd = &cobra.Command{
envName = parsedEnvName
}

// Override the parsed name if an explicit environment is provided
if environment != "" {
envName = environment
}

// Ensure environments directory exists
configPath := filepath.Join(getConfigDir(), "config.yaml")
configDir := filepath.Join(getConfigDir(), "environments")
if err := os.MkdirAll(configDir, 0755); err != nil {
pterm.Error.WithShowLineNumber(false).Println("Failed to create environments directory:", err)
return
}
envFilePath := filepath.Join(configDir, envName+".yaml")

// Load existing config if it exists
// Create an empty environment file if it doesn't already exist
if _, err := os.Stat(envFilePath); os.IsNotExist(err) {
file, err := os.Create(envFilePath)
if err != nil {
pterm.Error.WithShowLineNumber(false).Println("Failed to create environment file:", err)
return
}
file.Close()
}

// Set configuration in config.yaml
configPath := filepath.Join(getConfigDir(), "config.yaml")
viper.SetConfigFile(configPath)
_ = viper.ReadInConfig()

// Add or update the environment entry in viper
if urlStr != "" {
// Add or update the environment entry in config.yaml
if !viper.IsSet(fmt.Sprintf("environments.%s", envName)) {
viper.Set(fmt.Sprintf("environments.%s.url", envName), urlStr)
} else {
viper.Set(fmt.Sprintf("environments.%s", envName), "local")
}

// Set the default environment to the new envName
viper.Set("environment", envName)

// Serialize config data with 2-space indentation
configData := viper.AllSettings()
yamlData, err := yaml.Marshal(configData)
if err != nil {
pterm.Error.WithShowLineNumber(false).Println("Failed to encode YAML data:", err)
return
var baseURL string
if strings.HasPrefix(envName, "dev") {
baseURL = "grpc+ssl://identity.api.dev.spaceone.dev:443/v1"
} else if strings.HasPrefix(envName, "stg") {
baseURL = "grpc+ssl://identity.api.stg.spaceone.dev:443/v1"
}

// Write the serialized YAML to file with 2-space indentation
file, err := os.Create(configPath)
if err != nil {
pterm.Error.WithShowLineNumber(false).Println("Failed to write to config.yaml:", err)
return
if baseURL != "" {
viper.Set(fmt.Sprintf("environments.%s.endpoint", envName), baseURL)
}
defer file.Close()

if _, err := file.Write(yamlData); err != nil {
pterm.Error.WithShowLineNumber(false).Println("Failed to write YAML data to file:", err)
// Set the current environment
viper.Set("environment", envName)

// Write the updated configuration to config.yaml
if err := viper.WriteConfig(); err != nil {
pterm.Error.WithShowLineNumber(false).Println("Failed to write updated config.yaml:", err)
return
}

pterm.Success.WithShowLineNumber(false).
Printfln("Environment '%s' successfully initialized and set as the current environment in '%s/config.yaml'", envName, getConfigDir())

// After successfully writing to config.yaml, create the environment-specific YAML file
envFilePath := filepath.Join(getConfigDir(), "environments", fmt.Sprintf("%s.yaml", envName))

// Ensure the environments directory exists
environmentsDir := filepath.Dir(envFilePath)
if _, err := os.Stat(environmentsDir); os.IsNotExist(err) {
os.MkdirAll(environmentsDir, os.ModePerm)
}

// Create a blank environment-specific file if it doesn't exist
if _, err := os.Stat(envFilePath); os.IsNotExist(err) {
file, err := os.Create(envFilePath)
if err != nil {
pterm.Error.WithShowLineNumber(false).Println("Failed to create environment file:", err)
return
}
defer file.Close()
pterm.Success.WithShowLineNumber(false).Printfln("Created environment-specific file: %s", envFilePath)
} else {
pterm.Info.WithShowLineNumber(false).Printfln("Environment file already exists: %s", envFilePath)
}
Printfln("Environment '%s' successfully initialized with configuration in '%s/config.yaml'", envName, getConfigDir())
},
}

Expand All @@ -151,9 +133,11 @@ var envCmd = &cobra.Command{

// Handle environment switching
if switchEnv != "" {
configPath := filepath.Join(getConfigDir(), "environments", switchEnv+".yaml")
if _, err := os.Stat(configPath); os.IsNotExist(err) {
log.Fatalf("Environment '%s' not found.", switchEnv)
// Check for both .yaml and .yml 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)
}
}

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

// Handle environment removal with confirmation
if removeEnv != "" {
configPath := filepath.Join(getConfigDir(), "environments", removeEnv+".yaml")
if _, err := os.Stat(configPath); os.IsNotExist(err) {
log.Fatalf("Environment '%s' not found.", removeEnv)
// Check for both .yaml and .yml 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)
}
}

// Ask for confirmation before deletion
Expand All @@ -194,11 +180,10 @@ var envCmd = &cobra.Command{
fmt.Scanln(&response)
response = strings.ToLower(strings.TrimSpace(response))

if response == "Y" || response == "y" {
if response == "y" {
// Remove the environment file
if err := os.Remove(configPath); err != nil {
log.Fatalf("Failed to remove environment '%s': %v", removeEnv, err)
}
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 All @@ -208,7 +193,7 @@ var envCmd = &cobra.Command{
// Update environment to "no-env" if the deleted environment was the current one
if viper.GetString("environment") == removeEnv {
viper.Set("environment", "no-env")
pterm.Info.WithShowLineNumber(false).Printfln("Cleared current environment(default: %s/config.yaml)", getConfigDir())
pterm.Info.WithShowLineNumber(false).Printfln("Cleared current environment (default: %s/config.yaml)", getConfigDir())
}

// Remove the environment from the environments map if it exists
Expand Down Expand Up @@ -249,7 +234,7 @@ var envCmd = &cobra.Command{
pterm.Println("Available Environments:")
for _, entry := range entries {
name := entry.Name()
name = name[:len(name)-len(filepath.Ext(name))] // Remove ".yaml" extension
name = strings.TrimSuffix(name, filepath.Ext(name)) // Remove ".yaml" or ".yml" extension
if name == currentEnv {
pterm.FgGreen.Printf(" > %s (current)\n", name)
} else {
Expand Down Expand Up @@ -315,6 +300,46 @@ var showCmd = &cobra.Command{
},
}

// syncCmd syncs the environments in ~/.spaceone/environments with ~/.spaceone/config.yaml
var syncCmd = &cobra.Command{
Use: "sync",
Short: "Sync environments from the environments directory to config.yaml",
Long: "Sync all environment files from the ~/.spaceone/environments directory to ~/.spaceone/config.yaml",
Run: func(cmd *cobra.Command, args []string) {
// Define paths
envDir := filepath.Join(getConfigDir(), "environments")
configPath := filepath.Join(getConfigDir(), "config.yaml")

// Ensure the config file is loaded
viper.SetConfigFile(configPath)
_ = viper.ReadInConfig()

// Iterate over each .yaml file in the environments directory
entries, err := os.ReadDir(envDir)
if err != nil {
log.Fatalf("Unable to read environments directory: %v", err)
}

for _, entry := range entries {
if !entry.IsDir() && (filepath.Ext(entry.Name()) == ".yaml" || filepath.Ext(entry.Name()) == ".yml") {
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
if viper.GetString(fmt.Sprintf("environments.%s.url", envName)) == "" {
viper.Set(fmt.Sprintf("environments.%s.url", envName), "")
}
}
}

// Save updated config to config.yaml
if err := viper.WriteConfig(); err != nil {
log.Fatalf("Failed to write updated config.yaml: %v", err)
}

pterm.Success.Println("Successfully synced environments from environments directory to config.yaml.")
},
}

// getConfigDir returns the directory where config files are stored
func getConfigDir() string {
home, err := os.UserHomeDir()
Expand Down Expand Up @@ -395,7 +420,7 @@ func parseEnvNameFromURL(urlStr string) (string, error) {
re := regexp.MustCompile(`^(.*?)\.spaceone`)
matches := re.FindStringSubmatch(hostname)
if len(matches) == 2 {
return fmt.Sprintf("prd-%s", matches[1]), nil
return fmt.Sprintf("prd-%s-user", matches[1]), nil
}
}

Expand All @@ -404,7 +429,7 @@ func parseEnvNameFromURL(urlStr string) (string, error) {
re := regexp.MustCompile(`(.*)\.console\.dev\.spaceone\.dev`)
matches := re.FindStringSubmatch(hostname)
if len(matches) == 2 {
return fmt.Sprintf("dev-%s", matches[1]), nil
return fmt.Sprintf("dev-%s-user", matches[1]), nil
}
pterm.Error.WithShowLineNumber(false).Println("Invalid URL format for dev environment. Expected format: '<prefix>.console.dev.spaceone.dev'")
return "", fmt.Errorf("invalid dev URL format")
Expand All @@ -415,7 +440,7 @@ func parseEnvNameFromURL(urlStr string) (string, error) {
re := regexp.MustCompile(`(.*)\.console\.stg\.spaceone\.dev`)
matches := re.FindStringSubmatch(hostname)
if len(matches) == 2 {
return fmt.Sprintf("stg-%s", matches[1]), nil
return fmt.Sprintf("stg-%s-user", matches[1]), nil
}
pterm.Error.WithShowLineNumber(false).Println("Invalid URL format for stg environment. Expected format: '<prefix>.console.stg.spaceone.dev'")
return "", fmt.Errorf("invalid stg URL format")
Expand All @@ -431,6 +456,7 @@ func init() {
configCmd.AddCommand(configInitCmd)
configCmd.AddCommand(envCmd)
configCmd.AddCommand(showCmd)
configCmd.AddCommand(syncCmd)

// Defining flags for configInitCmd
configInitCmd.Flags().StringP("environment", "e", "", "Override environment name")
Expand Down
4 changes: 2 additions & 2 deletions cmd/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func init() {
}

func loadConfig(environment string) (*Config, error) {
configPath := fmt.Sprintf("%s/.spaceone/environments/%s.yml", os.Getenv("HOME"), environment)
configPath := fmt.Sprintf("%s/.spaceone/environments/%s.yaml", os.Getenv("HOME"), environment)
data, err := os.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("could not read config file: %w", err)
Expand All @@ -72,7 +72,7 @@ func loadConfig(environment string) (*Config, error) {
}

func fetchCurrentEnvironment() (string, error) {
envPath := fmt.Sprintf("%s/.spaceone/environment.yml", os.Getenv("HOME"))
envPath := fmt.Sprintf("%s/.spaceone/config.yaml", os.Getenv("HOME"))
data, err := os.ReadFile(envPath)
if err != nil {
return "", fmt.Errorf("could not read environment file: %w", err)
Expand Down
Loading
Loading