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)
| 48 | // and any information specified on it using comment directives, |
| 49 | // which requires the use of [types]. |
| 50 | func 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. |
no test coverage detected