From da2a040581395536231ba8a80bf1e1e1ba409431 Mon Sep 17 00:00:00 2001 From: Suraj B M Date: Thu, 25 Sep 2025 22:38:14 +0530 Subject: [PATCH] feat: implement switch command --- cmd/switch.go | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 cmd/switch.go diff --git a/cmd/switch.go b/cmd/switch.go new file mode 100644 index 0000000..00c656b --- /dev/null +++ b/cmd/switch.go @@ -0,0 +1,91 @@ +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 := envy.Get("envy.project").(string) + + 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) + + 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) + + 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") +}