Added custom printers

This commit is contained in:
Leon Mika 2024-12-11 22:30:14 +11:00
parent 62724e3f37
commit 7a92eeddac
7 changed files with 287 additions and 63 deletions

57
cmd/cmsh/fancy.go Normal file
View file

@ -0,0 +1,57 @@
package main
import (
"context"
"fmt"
"io"
"ucl.lmika.dev/repl"
"ucl.lmika.dev/ucl"
)
type FancyType struct {
Foo string
Bar string
}
var newFancyDoc = repl.Doc{
Brief: "returns something fancy",
Detailed: `
This will create and return something fancy.
`,
}
func newFancy(ctx context.Context, args ucl.CallArgs) (any, error) {
return FancyType{Foo: "is foo", Bar: "is bar"}, nil
}
func manyFancies(ctx context.Context, args ucl.CallArgs) (any, error) {
return []FancyType{
{Foo: "foo 1", Bar: "bar 1"},
{Foo: "foo 2", Bar: "bar 2"},
{Foo: "foo 3", Bar: "bar 3"},
}, nil
}
func displayFancy(w io.Writer, f FancyType, concise bool) error {
if concise {
_, err := fmt.Fprintf(w, "%s:%s", f.Foo, f.Bar)
return err
}
fmt.Fprintf(w, "Foo.. %s\n", f.Foo)
fmt.Fprintf(w, "Bar.. %s\n", f.Bar)
return nil
}
func displayFancies(w io.Writer, fs []FancyType, concise bool) error {
if concise {
_, err := fmt.Fprintf(w, "%d fancies", len(fs))
return err
}
fmt.Fprintln(w, "FOO\tBAR")
for _, f := range fs {
fmt.Fprintf(w, "%v\t%v\n", f.Foo, f.Bar)
}
return nil
}

View file

@ -33,6 +33,11 @@ func main() {
It then terminates.
`,
})
instRepl.SetCommand("new-fancy", newFancy, newFancyDoc)
instRepl.SetCommand("many-fancies", manyFancies)
repl.AddTypePrinter(instRepl, displayFancy)
repl.AddTypePrinter(instRepl, displayFancies)
for {
line, err := rl.Readline()