Files
envy/cmd/root.go

78 lines
1.6 KiB
Go

package cmd
import (
"envy/cmd/utils"
"fmt"
"os"
"path"
"github.com/charmbracelet/huh"
"github.com/spf13/cobra"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "envy",
Short: "A CLI tool to manage .env files for your projects",
Run: func(cmd *cobra.Command, args []string) {
cwd, err := os.Getwd()
utils.StopIfErr(err)
if _, err := os.Stat(path.Join(cwd, ".env")); os.IsNotExist(err) {
cmd.Help()
return
}
env, err := os.ReadFile(path.Join(cwd, ".env"))
utils.StopIfErr(err)
envs := utils.ParseEnvToStruct(string(env))
var lines []int
form := huh.NewForm(
huh.NewGroup(
huh.NewMultiSelect[int]().
Title("Enable or disable environment variables").
OptionsFunc(func() []huh.Option[int] {
var opts []huh.Option[int]
for i, en := range envs {
opts = append(opts,
huh.NewOption(fmt.Sprintf("%s = %s", en.Key, en.Value), i).
Selected(en.Enabled))
}
return opts
}, &envs).
Value(&lines),
),
)
err = form.Run()
utils.StopIfErr(err)
for i := range envs {
envs[i].Enabled = false
}
for _, v := range lines {
envs[v].Enabled = true
}
envStr := utils.ParseEnvStruct(envs)
os.WriteFile(path.Join(cwd, ".env"), []byte(envStr), 0755)
},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func init() {
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}