Skip to content

Commit

Permalink
macro: default arg
Browse files Browse the repository at this point in the history
  • Loading branch information
rsteube committed May 10, 2022
1 parent 8428009 commit 1c8aca6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions macro.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ func MacroI[T any](f func(t T) carapace.Action) Macro {
if err := yaml.Unmarshal([]byte(s), &t); err != nil {
return carapace.ActionMessage(err.Error())
}

if s == "" {
if m := reflect.ValueOf(&t).MethodByName("Default"); m.IsValid() && m.Type().NumIn() == 0 {
values := m.Call([]reflect.Value{}) // TODO check if needs args
if len(values) > 0 && values[0].Type().AssignableTo(reflect.TypeOf(t)) {
reflect.ValueOf(&t).Elem().Set(values[0])
}
}

}
}
return f(t)
},
Expand Down
18 changes: 18 additions & 0 deletions macro_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ type Arg struct {
Option bool
}

func (a Arg) Default() Arg {
a.Option = true
return a
}

func TestSignature(t *testing.T) {
signature := MacroI(func(a Arg) carapace.Action { return carapace.ActionValues() }).Signature()
if expected := `{name: "", option: false}`; signature != expected {
Expand Down Expand Up @@ -42,3 +47,16 @@ func TestSignature(t *testing.T) {
t.Errorf("should be: %v", expected)
}
}

func TestDefault(t *testing.T) {
var actual Arg
m := MacroI(func(a Arg) carapace.Action { actual = a; return carapace.ActionValues() })

if m.f(""); !actual.Option {
t.Error("should be true (default)")
}

if m.f("{option: false}"); actual.Option {
t.Error("should be false")
}
}

0 comments on commit 1c8aca6

Please sign in to comment.