envoid/cmd/set.go
Sagi Dayan 33f99dd65b
All checks were successful
build bin / Make sure build does not fail (push) Successful in 2m51s
Codespell / Check for spelling errors (push) Successful in 22s
Initial commit
Signed-off-by: Sagi Dayan <sagidayan@gmail.com>
2024-12-15 17:41:31 +02:00

125 lines
2.7 KiB
Go

package cmd
import (
"fmt"
"git.dayanhub.com/sagi/envoid/internal/common"
"git.dayanhub.com/sagi/envoid/internal/datastore"
"git.dayanhub.com/sagi/envoid/internal/errors"
"git.dayanhub.com/sagi/envoid/internal/types"
"github.com/spf13/cobra"
)
type setCmdFlags struct {
envName *string
encrypt *bool
}
var setFlags = setCmdFlags{}
var setCmd = &cobra.Command{
Use: "set [flags] <key> <value>",
Short: "sets a variable in environment(s)",
Long: "",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return errors.NewInvalidCommandError("expected 2 args. <key> <value>")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
err := initProject()
if err != nil {
return err
}
if project.IsEmpty() {
return errors.NewProjectEmptyError(project.Name)
}
key := args[0]
val := args[1]
ds, err := datastore.NewDataStore()
if err != nil {
fmt.Printf("Error: %e", err)
}
defer ds.Close()
envs := project.Environments
if len(*setFlags.envName) != 0 {
e, err := project.GetEnv(*setFlags.envName)
if err != nil {
return err
}
envs = []*types.Environment{e}
}
err = ds.SetValue(key, val, setFlags.encrypt, envs)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
}
return nil
},
}
var setEncryptCmd = &cobra.Command{
Use: "encrypt <key>",
Short: "encrypts an existing variable in environment(s)",
Long: "",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.NewInvalidCommandError("expected 1 args. <key>")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
err := initProject()
if err != nil {
return err
}
if project.IsEmpty() {
return errors.NewProjectEmptyError(project.Name)
}
key := args[0]
ds, err := datastore.NewDataStore()
if err != nil {
fmt.Printf("Error: %e", err)
}
defer ds.Close()
envs := project.Environments
if len(*setFlags.envName) != 0 {
e, err := project.GetEnv(*setFlags.envName)
if err != nil {
return err
}
envs = []*types.Environment{e}
}
for _, env := range envs {
// Get value
v, err := ds.GetVar(env.Name, key)
if err != nil {
return err
}
if !v.Encrypted {
err := ds.SetValue(v.Key, v.Value, common.BoolP(true), []*types.Environment{env})
if err != nil {
return err
}
}
}
return nil
},
}
func init() {
setFlags.envName = setCmd.PersistentFlags().StringP("environment", "e", "", "environments name")
setFlags.encrypt = setCmd.Flags().BoolP("secret", "s", false, "value is a secret. encrypt this value")
err := setCmd.RegisterFlagCompletionFunc("environment", validEnvironmentNamesComplete)
if err != nil {
panic(err)
}
setCmd.AddCommand(setEncryptCmd)
}