From e71f4f4e265df75bdead0a03c3dc6f2f667178c1 Mon Sep 17 00:00:00 2001 From: Suraj B M Date: Wed, 24 Sep 2025 12:24:01 +0530 Subject: [PATCH] feat: implement pin command --- cmd/pin.go | 89 ++++++++++++++++++++++++++++++++++++++++++++++ cmd/utils/other.go | 7 ++++ 2 files changed, 96 insertions(+) create mode 100644 cmd/pin.go diff --git a/cmd/pin.go b/cmd/pin.go new file mode 100644 index 0000000..691accc --- /dev/null +++ b/cmd/pin.go @@ -0,0 +1,89 @@ +/* +Copyright © 2025 NAME HERE +*/ +package cmd + +import ( + "envy/cmd/utils" + "fmt" + "os" + "path" + + "github.com/charmbracelet/huh" + "github.com/pelletier/go-toml" + "github.com/spf13/cobra" +) + +// pinCmd represents the pin command +var pinCmd = &cobra.Command{ + Use: "pin", + Short: "Pin an environment to the .envy file", + 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 pin"). + 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 + } + } + + envy.Set("envy.env", env) + data, err := toml.Marshal(envy) + utils.StopIfErr(err) + + cwd, err := os.Getwd() + utils.StopIfErr(err) + os.WriteFile(path.Join(cwd, ".envy"), data, 0744) + + fmt.Println("Pinned", env, "to the project.") + }, +} + +func init() { + rootCmd.AddCommand(pinCmd) + + // Here you will define your flags and configuration settings. + + // Cobra supports Persistent Flags which will work for this command + // and all subcommands, e.g.: + // pinCmd.PersistentFlags().String("foo", "", "A help for foo") + + // Cobra supports local flags which will only run when this command + // is called directly, e.g.: + // pinCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") +} diff --git a/cmd/utils/other.go b/cmd/utils/other.go index b1db369..d2c4f90 100644 --- a/cmd/utils/other.go +++ b/cmd/utils/other.go @@ -9,6 +9,13 @@ import ( "gorm.io/gorm" ) +func StopIfErr(err error) { + if err != nil { + ErrPrint(err.Error()) + os.Exit(1) + } +} + func GetEnvy() (*toml.Tree, error) { cwd, err := os.Getwd() if err != nil {