Skip to content

Commit

Permalink
added the set command which lets users change config params on the fl…
Browse files Browse the repository at this point in the history
…y. probably a bad idea, might remove later on but for now its there.
  • Loading branch information
terminaldweller committed May 12, 2024
1 parent eabdc60 commit e7c76ab
Showing 1 changed file with 54 additions and 5 deletions.
59 changes: 54 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,12 @@ import (
)

var (
errNotEnoughArgs = errors.New("not enough arguments")
errUnknCmd = errors.New("unknown command")
errUnknConfig = errors.New("unknown config name")
errNotEnoughArgs = errors.New("not enough arguments")
errUnknCmd = errors.New("unknown command")
errUnknConfig = errors.New("unknown config name")
errCantSet = errors.New("can't set field")
errWrongDataForField = errors.New("wrong data type for field")
errUnsupportedType = errors.New("unsupported type")
)

type TomlConfig struct {
Expand Down Expand Up @@ -126,12 +129,12 @@ func extractLast256ColorEscapeCode(str string) (string, error) {

r, err := regexp.Compile(pattern)
if err != nil {
return "", fmt.Errorf("failed to compile regular expression: %v", err)
return "", fmt.Errorf("failed to compile regular expression: %w", err)
}

matches := r.FindAllStringSubmatch(str, -1)
if len(matches) == 0 {
return "", nil // No 256-color escape codes found
return "", nil
}

lastMatch := matches[len(matches)-1]
Expand Down Expand Up @@ -174,6 +177,47 @@ func getHelpString() string {
return helpString
}

func setFieldByName(v reflect.Value, field string, value string) error {
fieldValue := v.FieldByName(field)
if !fieldValue.IsValid() {
return errUnknConfig
}

if !fieldValue.CanSet() {
return errCantSet
}

switch fieldValue.Kind() {
case reflect.String:
fieldValue.SetString(value)
case reflect.Int:
intValue, err := strconv.Atoi(value)
if err != nil {
return errWrongDataForField
}

fieldValue.SetInt(int64(intValue))
case reflect.Float64:
floatValue, err := strconv.ParseFloat(value, 64)
if err != nil {
return errWrongDataForField
}

fieldValue.SetFloat(floatValue)
case reflect.Bool:
boolValue, err := strconv.ParseBool(value)
if err != nil {
return errWrongDataForField
}

fieldValue.SetBool(boolValue)
default:
return errUnsupportedType
}

return nil
}

func runCommand(
client *girc.Client,
event girc.Event,
Expand Down Expand Up @@ -207,6 +251,11 @@ func runCommand(

break
}

err := setFieldByName(reflect.ValueOf(appConfig).Elem(), args[1], args[2])
if err != nil {
client.Cmd.Reply(event, err.Error())
}
case "get":
if len(args) < 2 { //nolint:gomnd
client.Cmd.Reply(event, errNotEnoughArgs.Error())
Expand Down

0 comments on commit e7c76ab

Please sign in to comment.