-
Notifications
You must be signed in to change notification settings - Fork 8
/
do.go
85 lines (67 loc) · 1.96 KB
/
do.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package fncobra
import (
"context"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"namespacelabs.dev/foundation/internal/compute"
)
type CmdHandler func(context.Context, []string) error
type ArgsParser interface {
AddFlags(*cobra.Command)
Parse(ctx context.Context, args []string) error
}
func RunE(f CmdHandler) func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, args []string) error {
ctx, cancel := WithSigIntCancel(cmd.Context())
defer cancel()
return compute.Do(ctx, func(ctx context.Context) error {
return f(ctx, args)
})
}
}
type CommandCtrl struct {
cmd *cobra.Command
argParsers []ArgsParser
}
func Cmd(cmd *cobra.Command) *CommandCtrl {
return &CommandCtrl{
cmd: cmd,
argParsers: []ArgsParser{},
}
}
func (c *CommandCtrl) With(argParser ...ArgsParser) *CommandCtrl {
c.argParsers = append(c.argParsers, argParser...)
return c
}
func (c *CommandCtrl) WithFlags(f func(flags *pflag.FlagSet)) *CommandCtrl {
return c.With(&simpleFlagParser{f})
}
func (c *CommandCtrl) Do(handler func(context.Context) error) *cobra.Command {
return c.DoWithArgs(func(ctx context.Context, args []string) error {
return handler(ctx)
})
}
func (c *CommandCtrl) DoWithArgs(handler CmdHandler) *cobra.Command {
for _, parser := range c.argParsers {
parser.AddFlags(c.cmd)
}
c.cmd.RunE = RunE(func(ctx context.Context, args []string) error {
for _, parser := range c.argParsers {
if err := parser.Parse(ctx, args); err != nil {
return err
}
}
return handler(ctx, args)
})
return c.cmd
}
type simpleFlagParser struct {
f func(flags *pflag.FlagSet)
}
func (p *simpleFlagParser) AddFlags(cmd *cobra.Command) {
p.f(cmd.Flags())
}
func (p *simpleFlagParser) Parse(ctx context.Context, args []string) error { return nil }