MCPcopy Create free account
hub / github.com/cogentcore/core / cmdFromFunc

Function cmdFromFunc

cli/cmd.go:50–80  ·  view source on GitHub ↗

cmdFromFunc returns a new [Cmd] object from the given function and any information specified on it using comment directives, which requires the use of [types].

(fun func(T) error)

Source from the content-addressed store, hash-verified

48// and any information specified on it using comment directives,
49// which requires the use of [types].
50func cmdFromFunc[T any](fun func(T) error) (*Cmd[T], error) {
51 cmd := &Cmd[T]{
52 Func: fun,
53 }
54
55 fn := types.FuncName(fun)
56
57 // we need to get rid of package name and then convert to kebab
58 strs := strings.Split(fn, ".")
59 cfn := strs[len(strs)-1] // camel function name
60 cmd.Name = strcase.ToKebab(cfn)
61
62 if f := types.FuncByName(fn); f != nil {
63 cmd.Doc = f.Doc
64 for _, dir := range f.Directives {
65 if dir.Tool != "cli" {
66 continue
67 }
68 if dir.Directive != "cmd" {
69 return cmd, fmt.Errorf("unrecognized comment directive %q (from comment %q)", dir.Directive, dir.String())
70 }
71 _, err := SetFromArgs(cmd, dir.Args, ErrNotFound)
72 if err != nil {
73 return cmd, fmt.Errorf("error setting command from directive arguments (from comment %q): %w", dir.String(), err)
74 }
75 }
76 // we format the doc after the directives so that we have the up-to-date documentation and name
77 cmd.Doc = types.FormatDoc(cmd.Doc, cfn, strcase.ToSentence(cmd.Name))
78 }
79 return cmd, nil
80}
81
82// cmdFromCmdOrFunc returns a new [Cmd] object from the given
83// [CmdOrFunc] object, using [cmdFromFunc] if it is a function.

Callers 1

cmdFromCmdOrFuncFunction · 0.85

Calls 9

FuncNameFunction · 0.92
ToKebabFunction · 0.92
FuncByNameFunction · 0.92
FormatDocFunction · 0.92
ToSentenceFunction · 0.92
SetFromArgsFunction · 0.85
SplitMethod · 0.80
ErrorfMethod · 0.65
StringMethod · 0.65

Tested by

no test coverage detected