forked from norman-abramovitz/cf-targets-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcf_targets.go
339 lines (305 loc) · 9.04 KB
/
cf_targets.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package main
import (
"bytes"
"flag"
"fmt"
"path/filepath"
"strings"
realio "io/ioutil"
realos "os"
"code.cloudfoundry.org/cli/cf/configuration"
"code.cloudfoundry.org/cli/cf/configuration/confighelpers"
"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
"code.cloudfoundry.org/cli/plugin"
)
type TargetsPlugin struct {
configPath string
targetsPath string
currentPath string
suffix string
status TargetStatus
}
type TargetStatus struct {
currentHasName bool
currentName string
currentNeedsSaving bool
currentNeedsUpdate bool
}
type RealOS struct{}
type OS interface {
Exit(int)
Mkdir(string, realos.FileMode)
Remove(string)
Symlink(string, string) error
ReadDir(string) ([]realos.FileInfo, error)
ReadFile(string) ([]byte, error)
WriteFile(string, []byte, realos.FileMode) error
}
func (*RealOS) Exit(code int) { realos.Exit(code) }
func (*RealOS) Mkdir(path string, mode realos.FileMode) { realos.Mkdir(path, mode) }
func (*RealOS) Remove(path string) { realos.Remove(path) }
func (*RealOS) Symlink(target string, source string) error { return realos.Symlink(target, source) }
func (*RealOS) ReadDir(path string) ([]realos.FileInfo, error) { return realio.ReadDir(path) }
func (*RealOS) ReadFile(path string) ([]byte, error) { return realio.ReadFile(path) }
func (*RealOS) WriteFile(path string, content []byte, mode realos.FileMode) error {
return realio.WriteFile(path, content, mode)
}
var os OS
func newTargetsPlugin() *TargetsPlugin {
configPath, _ := confighelpers.DefaultFilePath()
targetsPath := filepath.Join(filepath.Dir(configPath), "targets")
os.Mkdir(targetsPath, 0700)
return &TargetsPlugin{
configPath: configPath,
targetsPath: targetsPath,
currentPath: filepath.Join(targetsPath, "current"),
suffix: "." + filepath.Base(configPath),
}
}
func (c *TargetsPlugin) GetMetadata() plugin.PluginMetadata {
return plugin.PluginMetadata{
Name: "cf-targets",
Version: plugin.VersionType{
Major: 1,
Minor: 2,
Build: 0,
},
Commands: []plugin.Command{
{
Name: "targets",
HelpText: "List available targets",
UsageDetails: plugin.Usage{
Usage: "cf targets",
},
},
{
Name: "set-target",
HelpText: "Set current target",
UsageDetails: plugin.Usage{
Usage: "cf set-target [-f] NAME",
Options: map[string]string{
"f": "replace the current target even if it has not been saved",
},
},
},
{
Name: "save-target",
HelpText: "Save current target",
UsageDetails: plugin.Usage{
Usage: "cf save-target [-f] [NAME]",
Options: map[string]string{
"f": "save the target even if the specified name already exists",
},
},
},
{
Name: "delete-target",
HelpText: "Delete a saved target",
UsageDetails: plugin.Usage{
Usage: "cf delete-target NAME",
},
},
},
}
}
func main() {
os = &RealOS{}
plugin.Start(newTargetsPlugin())
}
func (c *TargetsPlugin) Run(cliConnection plugin.CliConnection, args []string) {
defer func() {
reason := recover()
if code, ok := reason.(int); ok {
os.Exit(code)
} else if reason != nil {
panic(reason)
}
}()
c.checkStatus()
if args[0] == "targets" {
c.TargetsCommand(args)
} else if args[0] == "set-target" {
c.SetTargetCommand(args)
} else if args[0] == "save-target" {
c.SaveTargetCommand(args)
} else if args[0] == "delete-target" {
c.DeleteTargetCommand(args)
}
}
func (c *TargetsPlugin) TargetsCommand(args []string) {
if len(args) != 1 {
c.exitWithUsage("targets")
}
targets := c.getTargets()
if len(targets) < 1 {
fmt.Println("No targets have been saved yet. To save the current target, use:")
fmt.Println(" cf save-target NAME")
} else {
for _, target := range targets {
var qualifier string
if c.isCurrent(target) {
qualifier = "(current"
if c.status.currentNeedsSaving {
qualifier += ", modified"
} else if c.status.currentNeedsUpdate {
qualifier += "*"
}
qualifier += ")"
}
fmt.Println(target, qualifier)
}
}
}
func (c *TargetsPlugin) SetTargetCommand(args []string) {
flagSet := flag.NewFlagSet("set-target", flag.ContinueOnError)
force := flagSet.Bool("f", false, "force")
err := flagSet.Parse(args[1:])
if err != nil || len(flagSet.Args()) != 1 {
c.exitWithUsage("set-target")
}
targetName := flagSet.Arg(0)
targetPath := c.targetPath(targetName)
if !c.targetExists(targetPath) {
fmt.Println("Target", targetName, "does not exist.")
panic(1)
}
if *force || !c.status.currentNeedsSaving {
c.copyContents(targetPath, c.configPath)
c.linkCurrent(targetPath)
} else {
fmt.Println("Your current target has not been saved. Use save-target first, or use -f to discard your changes.")
panic(1)
}
fmt.Println("Set target to", targetName)
}
func (c *TargetsPlugin) SaveTargetCommand(args []string) {
flagSet := flag.NewFlagSet("save-target", flag.ContinueOnError)
force := flagSet.Bool("f", false, "force")
err := flagSet.Parse(args[1:])
if err != nil || len(flagSet.Args()) > 1 {
c.exitWithUsage("save-target")
}
if len(flagSet.Args()) < 1 {
c.SaveCurrentTargetCommand(*force)
} else {
c.SaveNamedTargetCommand(flagSet.Arg(0), *force)
}
}
func (c *TargetsPlugin) SaveNamedTargetCommand(targetName string, force bool) {
targetPath := c.targetPath(targetName)
if force || !c.targetExists(targetPath) {
c.copyContents(c.configPath, targetPath)
c.linkCurrent(targetPath)
} else {
fmt.Println("Target", targetName, "already exists. Use -f to overwrite it.")
panic(1)
}
fmt.Println("Saved current target as", targetName)
}
func (c *TargetsPlugin) SaveCurrentTargetCommand(force bool) {
if !c.status.currentHasName {
fmt.Println("Current target has not been previously saved. Please provide a name.")
panic(1)
}
targetName := c.status.currentName
targetPath := c.targetPath(targetName)
if c.status.currentNeedsSaving && !force {
fmt.Println("You've made substantial changes to the current target.")
fmt.Println("Use -f if you intend to overwrite the target named", targetName, "or provide an alternate name")
panic(1)
}
c.copyContents(c.configPath, targetPath)
fmt.Println("Saved current target as", targetName)
}
func (c *TargetsPlugin) DeleteTargetCommand(args []string) {
if len(args) != 2 {
c.exitWithUsage("delete-target")
}
targetName := args[1]
targetPath := c.targetPath(targetName)
if !c.targetExists(targetPath) {
fmt.Println("Target", targetName, "does not exist")
panic(1)
}
os.Remove(targetPath)
if c.isCurrent(targetName) {
os.Remove(c.currentPath)
}
fmt.Println("Deleted target", targetName)
}
func (c *TargetsPlugin) getTargets() []string {
var targets []string
files, _ := os.ReadDir(c.targetsPath)
for _, file := range files {
filename := file.Name()
if strings.HasSuffix(filename, c.suffix) {
targets = append(targets, strings.TrimSuffix(filename, c.suffix))
}
}
return targets
}
func (c *TargetsPlugin) targetExists(targetPath string) bool {
target := configuration.NewDiskPersistor(targetPath)
return target.Exists()
}
func (c *TargetsPlugin) checkStatus() {
currentConfig := configuration.NewDiskPersistor(c.configPath)
currentTarget := configuration.NewDiskPersistor(c.currentPath)
if !currentTarget.Exists() {
os.Remove(c.currentPath)
c.status = TargetStatus{false, "", true, false}
return
}
name := c.getCurrent()
configData := coreconfig.NewData()
targetData := coreconfig.NewData()
err := currentConfig.Load(configData)
c.checkError(err)
err = currentTarget.Load(targetData)
c.checkError(err)
// Ignore the access-token field, as it changes frequently
needsUpdate := targetData.AccessToken != configData.AccessToken
targetData.AccessToken = configData.AccessToken
currentContent, err := configData.JSONMarshalV3()
c.checkError(err)
savedContent, err := targetData.JSONMarshalV3()
c.checkError(err)
c.status = TargetStatus{true, name, !bytes.Equal(currentContent, savedContent), needsUpdate}
}
func (c *TargetsPlugin) copyContents(sourcePath, targetPath string) {
content, err := os.ReadFile(sourcePath)
c.checkError(err)
err = os.WriteFile(targetPath, content, 0600)
c.checkError(err)
}
func (c *TargetsPlugin) linkCurrent(targetPath string) {
os.Remove(c.currentPath)
err := os.Symlink(targetPath, c.currentPath)
c.checkError(err)
}
func (c *TargetsPlugin) targetPath(targetName string) string {
return filepath.Join(c.targetsPath, targetName+c.suffix)
}
func (c *TargetsPlugin) checkError(err error) {
if err != nil {
fmt.Println("Error:", err)
panic(1)
}
}
func (c *TargetsPlugin) exitWithUsage(command string) {
metadata := c.GetMetadata()
for _, candidate := range metadata.Commands {
if candidate.Name == command {
fmt.Println("Usage: " + candidate.UsageDetails.Usage)
panic(1)
}
}
}
func (c *TargetsPlugin) getCurrent() string {
targetPath, err := filepath.EvalSymlinks(c.currentPath)
c.checkError(err)
return strings.TrimSuffix(filepath.Base(targetPath), c.suffix)
}
func (c *TargetsPlugin) isCurrent(target string) bool {
return c.status.currentHasName && c.status.currentName == target
}