diff --git a/macro.go b/macro.go index 706c0ab..01b80ee 100644 --- a/macro.go +++ b/macro.go @@ -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) }, diff --git a/macro_test.go b/macro_test.go index a395768..e77255b 100644 --- a/macro_test.go +++ b/macro_test.go @@ -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 { @@ -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") + } +}