-
Notifications
You must be signed in to change notification settings - Fork 0
/
environment_create.go
108 lines (90 loc) · 2.53 KB
/
environment_create.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package cmd
import (
"github.com/davidalpert/go-contentstack/internal/cfg"
"github.com/davidalpert/go-contentstack/v1/management"
"github.com/davidalpert/go-contentstack/v1/schema"
"github.com/davidalpert/go-printers/v1"
"github.com/spf13/cobra"
"strings"
)
type EnvironmentCreateOptions struct {
*printers.PrinterOptions
Config cfg.Config
Client *management.Client
Name string
RawURLParams []string
URLsByLocale map[string]string
}
func NewEnvironmentCreateOptions(s printers.IOStreams) *EnvironmentCreateOptions {
return &EnvironmentCreateOptions{
PrinterOptions: printers.NewPrinterOptions().WithStreams(s).WithDefaultOutput("yaml"),
URLsByLocale: map[string]string{},
}
}
func NewCmdEnvironmentCreate(s printers.IOStreams) *cobra.Command {
o := NewEnvironmentCreateOptions(s)
var cmd = &cobra.Command{
Use: "create <name>",
Short: "create a new publishing environment with the given name",
Aliases: []string{"c", "cr"},
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if err := o.Complete(cmd, args); err != nil {
return err
}
if err := o.Validate(); err != nil {
return err
}
return o.Run()
},
}
o.AddPrinterFlags(cmd.Flags())
cmd.Flags().StringSliceVarP(&o.RawURLParams, "url", "u", []string{}, "locale;url pairs describing render url by locale")
return cmd
}
// Complete the options
func (o *EnvironmentCreateOptions) Complete(cmd *cobra.Command, args []string) error {
o.Name = args[0]
for _, s := range o.RawURLParams {
parts := strings.Split(s, ";")
if len(parts) > 1 {
o.URLsByLocale[parts[0]] = parts[1]
}
}
if err := cfg.ReadMergedInto(&o.Config); err != nil {
return err
}
c, err := management.NewClient(&o.Config.ContentStack.ManagementApi)
if err != nil {
return err
}
o.Client = c
return nil
}
// Validate the options
func (o *EnvironmentCreateOptions) Validate() error {
if err := o.Config.Validate(); err != nil {
return err
}
return o.PrinterOptions.Validate()
}
// Run the command
func (o *EnvironmentCreateOptions) Run() error {
if o.FormatCategory() == "table" || o.FormatCategory() == "csv" {
o.WithDefaultOutput("json")
}
w := schema.SingleEnvironmentWrapper{
Environment: schema.Environment{
Name: o.Name,
Urls: []schema.LocaleURLPair{},
},
}
for l, u := range o.URLsByLocale {
w.Environment.Urls = append(w.Environment.Urls, schema.LocaleURLPair{Locale: l, Url: u})
}
r, err := o.Client.CreatePublishingEnvironment(&w)
if err != nil {
return err
}
return o.WriteOutput(r)
}