BackGo/cmd/configcli.go

77 lines
2.0 KiB
Go
Raw Normal View History

2024-03-27 02:11:46 -06:00
package cmd
import (
"fmt"
"os"
"os/exec"
"pixelridgesoftworks.com/BackGo/config"
"reflect"
"strconv"
"strings"
2024-03-27 02:11:46 -06:00
)
const configFilePath = "/etc/PixelRidge/BackGo/config.json"
2024-03-27 02:11:46 -06:00
// OpenConfigInNano opens the configuration file in the nano editor.
func OpenConfigInNano() error {
cmd := exec.Command("nano", configFilePath)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
err := cmd.Run()
2024-03-27 02:11:46 -06:00
if err != nil {
return fmt.Errorf("error opening config in nano: %v", err)
2024-03-27 02:11:46 -06:00
}
return nil
}
// EditConfigOption allows editing a specific configuration option from the CLI
func EditConfigOption(optionName, newValue string) error {
// Load the current configuration from file
cfg, err := config.LoadConfigFromFile()
if err != nil {
return fmt.Errorf("loading config: %v", err)
}
2024-03-27 02:11:46 -06:00
// Use reflection to find and set the field in the Config struct
rConfig := reflect.ValueOf(cfg).Elem()
field := rConfig.FieldByNameFunc(func(s string) bool {
return strings.EqualFold(s, optionName)
})
2024-03-27 02:11:46 -06:00
if !field.IsValid() {
return fmt.Errorf("unknown configuration option: %s", optionName)
}
2024-03-27 02:11:46 -06:00
// Ensure the field can be set
if !field.CanSet() {
return fmt.Errorf("cannot set configuration option: %s", optionName)
}
// Convert and set the field value based on its kind
switch field.Kind() {
case reflect.String:
field.SetString(newValue)
case reflect.Bool:
boolVal, err := strconv.ParseBool(newValue)
if err != nil {
return fmt.Errorf("invalid value for %s: %v", optionName, err)
}
field.SetBool(boolVal)
case reflect.Int:
intVal, err := strconv.Atoi(newValue)
if err != nil {
return fmt.Errorf("invalid value for %s: %v", optionName, err)
}
// Additional checks can be implemented here for specific int fields like LogLevel
field.SetInt(int64(intVal))
default:
return fmt.Errorf("unsupported configuration type for: %s", optionName)
}
// Save the updated configuration back to the file
if err := config.SaveConfigToFile(cfg); err != nil {
return fmt.Errorf("saving config: %v", err)
}
return nil
2024-03-27 02:11:46 -06:00
}