Files
envy/cmd/pin.go

96 lines
2.1 KiB
Go

/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
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.toml 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, err := utils.GetKey(envy, "envy.project")
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("The current environment is already pinned.")
os.Exit(1)
}
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.toml"), 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")
}