Просмотр исходного кода

Nullable args (#292)

* feature: Argument values can be null be default. Use RejectNull to change.

* feature: Argument values can be null be default. Use RejectNull to change.
James Read 2 лет назад
Родитель
Сommit
500419307b
3 измененных файлов с 41 добавлено и 0 удалено
  1. 1 0
      internal/config/config.go
  2. 12 0
      internal/executor/arguments.go
  3. 28 0
      internal/executor/arguments_test.go

+ 1 - 0
internal/config/config.go

@@ -33,6 +33,7 @@ type ActionArgument struct {
 	Default     string
 	Choices     []ActionArgumentChoice
 	Entity      string
+	RejectNull  bool
 	Suggestions map[string]string
 }
 

+ 12 - 0
internal/executor/arguments.go

@@ -71,6 +71,10 @@ func typecheckActionArgument(name string, value string, action *config.Action) e
 		return errors.New("Action arg not defined: " + name)
 	}
 
+	if value == "" {
+		return typecheckNull(arg)
+	}
+
 	if len(arg.Choices) > 0 {
 		return typecheckChoice(value, arg)
 	}
@@ -78,6 +82,14 @@ func typecheckActionArgument(name string, value string, action *config.Action) e
 	return TypeSafetyCheck(name, value, arg.Type)
 }
 
+func typecheckNull(arg *config.ActionArgument) error {
+	if arg.RejectNull {
+		return errors.New("Null values are not allowed")
+	}
+
+	return nil
+}
+
 func typecheckChoice(value string, arg *config.ActionArgument) error {
 	if arg.Entity != "" {
 		return typecheckChoiceEntity(value, arg)

+ 28 - 0
internal/executor/arguments_test.go

@@ -17,6 +17,34 @@ func TestSanitizeUnimplemented(t *testing.T) {
 	assert.NotNil(t, err, "Test an argument type that does not exist")
 }
 
+func TestArgumentValueNullable(t *testing.T) {
+	a1 := config.Action{
+		Title: "Release the hounds",
+		Shell: "echo 'Releasing {{ count }} hounds'",
+		Arguments: []config.ActionArgument{
+			{
+				Name: "count",
+				Type: "int",
+			},
+		},
+	}
+
+	values := map[string]string{
+		"count": "",
+	}
+
+	out, err := parseActionArguments(a1.Shell, values, &a1, a1.Title, "")
+
+	assert.Equal(t, "echo 'Releasing  hounds'", out)
+	assert.Nil(t, err)
+
+	a1.Arguments[0].RejectNull = true
+
+	_, err = parseActionArguments(a1.Shell, values, &a1, a1.Title, "")
+
+	assert.NotNil(t, err)
+}
+
 func TestArgumentNameNumbers(t *testing.T) {
 	a1 := config.Action{
 		Title: "Do some tickles",