ucl/repl/repl.go

65 lines
1.1 KiB
Go

package repl
import (
"context"
"fmt"
"github.com/lmika/gopkgs/fp/maps"
"sort"
"ucl.lmika.dev/ucl"
)
type CommandOpt interface {
config(cmdName string, r *REPL)
}
type REPL struct {
inst *ucl.Inst
commandDocs map[string]Doc
}
func New(opts ...ucl.InstOption) *REPL {
inst := ucl.New(opts...)
r := &REPL{
inst: inst,
commandDocs: make(map[string]Doc),
}
inst.SetBuiltin("help", r.helpBuiltin)
return r
}
func (r *REPL) Inst() *ucl.Inst {
return r.inst
}
func (r *REPL) SetCommand(name string, fn ucl.BuiltinHandler, opts ...CommandOpt) {
r.commandDocs[name] = Doc{}
for _, opt := range opts {
opt.config(name, r)
}
r.inst.SetBuiltin(name, fn)
}
func (r *REPL) helpBuiltin(ctx context.Context, args ucl.CallArgs) (any, error) {
switch {
case args.NArgs() == 0:
// TEMP
names := maps.Keys(r.commandDocs)
sort.Strings(names)
for _, name := range names {
cdoc := r.commandDocs[name]
if cdoc.Brief != "" {
fmt.Println("%v\t%v", name, r.commandDocs[name])
} else {
fmt.Println("%v", name)
}
}
// END TEMP
}
return nil, nil
}