Skip to content

Commit d1a41f8

Browse files
committed
refactor config validation to remove some code duplication
1 parent be5022e commit d1a41f8

File tree

4 files changed

+16
-15
lines changed

4 files changed

+16
-15
lines changed

cli/config/add.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,7 @@ func initAddCommand() *cobra.Command {
4444

4545
func runAddCommand(cmd *cobra.Command, args []string) {
4646
key := args[0]
47-
kind, err := typeOf(key)
48-
if err != nil {
49-
feedback.Error(err)
50-
os.Exit(errorcodes.ErrGeneric)
51-
}
47+
kind := validateKey(key)
5248

5349
if kind != reflect.Slice {
5450
feedback.Errorf(tr("The key '%[1]v' is not a list of items, can't add to it.\nMaybe use '%[2]s'?"), key, "config set")

cli/config/remove.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,7 @@ func initRemoveCommand() *cobra.Command {
4444

4545
func runRemoveCommand(cmd *cobra.Command, args []string) {
4646
key := args[0]
47-
kind, err := typeOf(key)
48-
if err != nil {
49-
feedback.Error(err)
50-
os.Exit(errorcodes.ErrGeneric)
51-
}
47+
kind := validateKey(key)
5248

5349
if kind != reflect.Slice {
5450
feedback.Errorf(tr("The key '%[1]v' is not a list of items, can't remove from it.\nMaybe use '%[2]s'?"), key, "config delete")

cli/config/set.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,7 @@ func initSetCommand() *cobra.Command {
4747

4848
func runSetCommand(cmd *cobra.Command, args []string) {
4949
key := args[0]
50-
kind, err := typeOf(key)
51-
if err != nil {
52-
feedback.Error(err)
53-
os.Exit(errorcodes.ErrGeneric)
54-
}
50+
kind := validateKey(key)
5551

5652
if kind != reflect.Slice && len(args) > 2 {
5753
feedback.Errorf(tr("Can't set multiple values in key %v"), key)

cli/config/validate.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@ package config
1717

1818
import (
1919
"fmt"
20+
"os"
2021
"reflect"
22+
23+
"github.com/arduino/arduino-cli/cli/errorcodes"
24+
"github.com/arduino/arduino-cli/cli/feedback"
2125
)
2226

2327
var validMap = map[string]reflect.Kind{
@@ -46,3 +50,12 @@ func typeOf(key string) (reflect.Kind, error) {
4650
}
4751
return t, nil
4852
}
53+
54+
func validateKey(key string) reflect.Kind {
55+
kind, err := typeOf(key)
56+
if err != nil {
57+
feedback.Error(err)
58+
os.Exit(errorcodes.ErrGeneric)
59+
}
60+
return kind
61+
}

0 commit comments

Comments
 (0)