-
Notifications
You must be signed in to change notification settings - Fork 5
/
get.go
80 lines (64 loc) · 2.33 KB
/
get.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
package manipcli
import (
"context"
"fmt"
"time"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.aporeto.io/elemental"
"go.aporeto.io/manipulate"
)
// generateGetCommandForIdentity generates the command to get an object based on its identity.
func generateGetCommandForIdentity(identity elemental.Identity, modelManager elemental.ModelManager, manipulatorMaker ManipulatorMaker) (*cobra.Command, error) {
cmd := &cobra.Command{
Use: fmt.Sprintf("%s <id-or-name>", identity.Name),
Aliases: []string{identity.Category},
Short: "Get an existing " + identity.Name,
Args: cobra.ExactArgs(1),
// Aliases: TODO: Missing alias from the spec file -> To be stored in the identity ?,
RunE: func(cmd *cobra.Command, args []string) error {
fParam := viper.GetStringSlice("param")
fTrackingID := viper.GetString(flagTrackingID)
fRecursive := viper.GetBool(flagRecursive)
fOutput := viper.GetString(flagOutput)
fFormatTypeColumn := viper.GetStringSlice(formatTypeColumn)
fOutputTemplate := viper.GetString(flagOutputTemplate)
manipulator, err := manipulatorMaker()
if err != nil {
return fmt.Errorf("unable to make manipulator: %w", err)
}
parameters, err := parametersToURLValues(fParam)
if err != nil {
return fmt.Errorf("unable to convert parameters to url values: %w", err)
}
options := []manipulate.ContextOption{
manipulate.ContextOptionTracking(fTrackingID, "cli"),
manipulate.ContextOptionParameters(parameters),
manipulate.ContextOptionFields(fFormatTypeColumn),
manipulate.ContextOptionRecursive(fRecursive),
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
mctx := manipulate.NewContext(ctx, options...)
identifiable, err := retrieveObjectByIDOrByName(mctx, manipulator, identity, args[0], modelManager)
if err != nil {
return fmt.Errorf("unable to retrieve %s: %w", identity.Name, err)
}
outputType := fOutput
if fOutput == flagOutputDefault {
outputType = flagOutputJSON
}
result, err := formatObjects(
prepareOutputFormat(outputType, formatTypeHash, fFormatTypeColumn, fOutputTemplate),
false,
identifiable,
)
if err != nil {
return fmt.Errorf("unable to format output: %w", err)
}
fmt.Fprint(cmd.OutOrStdout(), result)
return nil
},
}
return cmd, nil
}