Files
envy/cmd/switch.go

111 lines
2.5 KiB
Go

package cmd
import (
"envy/cmd/utils"
"fmt"
"os"
"path"
"github.com/charmbracelet/huh"
"github.com/spf13/cobra"
)
// switchCmd represents the switch command
var switchCmd = &cobra.Command{
Use: "switch",
Short: "Replace the current environment with another one",
Run: func(cmd *cobra.Command, args []string) {
var env = ""
if len(args) > 0 {
env = args[0]
}
envy, err := utils.GetEnvy()
utils.StopIfErr(err)
project, err := utils.GetKey(envy, "envy.project")
utils.StopIfErr(err)
current, err := utils.GetKey(envy, "envy.current")
utils.StopIfErr(err)
dbProject, err := utils.GetProject(project)
utils.StopIfErr(err)
if env != "" {
_, err := utils.GetEnvironment(dbProject.ID, env)
utils.StopIfErr(err)
} else {
envs, err := utils.GetEnvironments(dbProject.ID)
utils.StopIfErr(err)
if len(envs) == 1 {
utils.ErrPrint("Cannot switch when there is only one environment.")
os.Exit(1)
} else if len(envs) == 2 {
for _, en := range envs {
if en.Name != current {
env = en.Name
}
}
} else {
form := huh.NewForm(
huh.NewGroup(
huh.NewSelect[string]().
Title("Select environment").
Description("Select an environment to switch to").
OptionsFunc(func() []huh.Option[string] {
var options []huh.Option[string]
for _, en := range envs {
options = append(options, huh.NewOption(en.Name, en.Name))
}
return options
}, &env).
Value(&env),
),
)
err = form.Run()
utils.StopIfErr(err)
if env == "" {
return
}
}
}
envs, err := utils.GetEnvironments(dbProject.ID)
utils.StopIfErr(err)
var selectedEnv utils.Environment
for _, en := range envs {
if en.Name == env {
selectedEnv = en
}
}
cwd, err := os.Getwd()
utils.StopIfErr(err)
os.WriteFile(path.Join(cwd, ".env"), []byte(selectedEnv.Data), 0744)
envy.Set("envy.current", env)
err = utils.WriteEnvy(envy)
utils.StopIfErr(err)
fmt.Printf("Switched to environment %v.\n", env)
},
}
func init() {
rootCmd.AddCommand(switchCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// switchCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// switchCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}