/
appenv.go
129 lines (99 loc) · 2.5 KB
/
appenv.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
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"github.com/cloudfoundry/cli/plugin"
)
type AppEnv struct{}
func main() {
plugin.Start(new(AppEnv))
}
func (a *AppEnv) GetAppEnvFromCli(cli plugin.CliConnection, appName string) ([]string, error) {
return cli.CliCommandWithoutTerminalOutput("env", appName)
}
func panicOnError(err error) {
if err != nil {
fmt.Println("error: ", err)
os.Exit(1)
}
}
func (a *AppEnv) GetJson(key string, out []string) (string, error) {
for _, line := range out {
if strings.Contains(line, key) {
bytes := []byte(line)
var j interface{}
err := json.Unmarshal(bytes, &j)
if err != nil {
return "", err
}
m := j.(map[string]interface{})
marshalledBytes, err := json.Marshal(m[key])
if err != nil {
return "", err
}
return string(marshalledBytes[:]), nil
}
}
return "", errors.New(fmt.Sprintf("%s not found", key))
}
func formatExportEnvvar(key string, value string) string {
return fmt.Sprintf("export %s='%s'", key, value)
}
func (a *AppEnv) GetJsonAndFormat(key string, cliOut []string) string {
json, err := a.GetJson(key, cliOut)
if err == nil {
return formatExportEnvvar(key, json)
}
return ""
}
func (a *AppEnv) GetEnvs(cli plugin.CliConnection, args []string) ([]string, error) {
if loggedIn, _ := cli.IsLoggedIn(); loggedIn == false {
return nil, errors.New("You must login first!")
}
if len(args) <= 1 {
return nil, errors.New("You must specify an app name")
}
cliOut, err := a.GetAppEnvFromCli(cli, args[1])
vcapServicesExport := a.GetJsonAndFormat("VCAP_SERVICES", cliOut)
vcapAppExport := a.GetJsonAndFormat("VCAP_APPLICATION", cliOut)
envvars := []string{}
if vcapServicesExport != "" {
envvars = append(envvars, vcapServicesExport)
}
if vcapAppExport != "" {
envvars = append(envvars, vcapAppExport)
}
return envvars, err
}
func (a *AppEnv) Run(cli plugin.CliConnection, args []string) {
if len(args) > 0 && args[0] == "CLI-MESSAGE-UNINSTALL" {
return
}
envVars, err := a.GetEnvs(cli, args)
panicOnError(err)
for _, env := range envVars {
fmt.Println(env)
}
}
func (a *AppEnv) GetMetadata() plugin.PluginMetadata {
return plugin.PluginMetadata{
Name: "appenvs",
Version: plugin.VersionType{
Major: 0,
Minor: 1,
Build: 0,
},
Commands: []plugin.Command{
plugin.Command{
Name: "appenvs",
HelpText: "Export application environment variables locally.",
UsageDetails: plugin.Usage{
Usage: "appenvs APP_NAME",
},
},
},
}
}