-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathapp.go
More file actions
290 lines (243 loc) · 8.78 KB
/
Copy pathapp.go
File metadata and controls
290 lines (243 loc) · 8.78 KB
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
package detect
import (
"context"
stderrors "errors"
"os"
"strings"
"github.com/urfave/cli/v3"
"github.com/Scalingo/cli/config"
"github.com/Scalingo/cli/io"
"github.com/Scalingo/cli/utils"
"github.com/Scalingo/go-scalingo/v11/debug"
"github.com/Scalingo/go-utils/errors/v3"
)
var errDatabaseNotFound = stderrors.New("database name not found")
// GetAddonIDFromDatabase resolves the addon ID from a database name by calling the API.
// This is useful when the database name is provided as a positional argument.
func GetAddonIDFromDatabase(ctx context.Context, databaseName string) (string, error) {
client, err := config.ScalingoClient(ctx)
if err != nil {
return "", errors.Wrap(ctx, err, "get Scalingo client")
}
// AddonsList works for both apps and DBNG databases (same API endpoint).
// A DBNG database is modeled as an app with a single addon (itself),
// whereas an application can have multiple addons (postgresql, redis, etc.).
// If multiple addons are returned, the ID is likely an application, not a database.
addons, err := client.AddonsList(ctx, databaseName)
if err != nil {
return "", errors.Wrap(ctx, err, "list addons")
}
if len(addons) == 0 {
return "", errors.Newf(ctx, "no addon found for database %s", databaseName)
}
if len(addons) > 1 {
return "", errors.Newf(ctx, "multiple addons found for %s, it may be an application", databaseName)
}
return addons[0].ID, nil
}
// ErrTooManyArguments is returned when too many arguments are provided
var ErrTooManyArguments = stderrors.New("too many arguments")
// GetDatabaseFromArgs resolves the database name and addon ID from command arguments.
// If no positional argument is provided, it uses the --database flag.
// If one positional argument is provided, it uses it as the database name.
// Returns ErrTooManyArguments if more than one argument is provided.
func GetDatabaseFromArgs(ctx context.Context, c *cli.Command) (string, string, error) {
switch c.Args().Len() {
case 0:
// No positional arg, database from --database flag
databaseName, addonID := GetCurrentDatabase(ctx, c)
return databaseName, addonID, nil
case 1:
// database-name provided as positional arg
databaseName := c.Args().First()
addonID, err := GetAddonIDFromDatabase(ctx, databaseName)
if err != nil {
return "", "", errors.Wrapf(ctx, err, "fail to resolve addon ID for database %s", databaseName)
}
return databaseName, addonID, nil
default:
return "", "", ErrTooManyArguments
}
}
// GetCurrentDatabase is a helper to get the current database name and UUID.
func GetCurrentDatabase(ctx context.Context, c *cli.Command) (string, string) {
currentDatabase, databaseUUID, err := currentDatabaseNameAndUUID(ctx, c)
if errors.Is(err, errDatabaseNotFound) {
io.Error("No database found. Please use --database flag.")
os.Exit(1)
}
if err != nil {
io.Error(err)
os.Exit(1)
}
return currentDatabase, databaseUUID
}
// GetCurrentResource is the new helper to get the current resource (app or database).
func GetCurrentResource(ctx context.Context, c *cli.Command) string {
resource, _ := GetCurrentResourceAndDatabase(ctx, c)
return resource
}
// GetCurrentResourceAndDatabase returns the current resource (app or database)
// and the current database UUID if any.
// It exits CLI in case of error.
func GetCurrentResourceAndDatabase(ctx context.Context, c *cli.Command) (string, string) {
if os.Getenv("SCALINGO_PREVIEW_FEATURES") != "true" {
return CurrentApp(ctx, c), ""
}
currentApp := extractAppName(ctx, c)
currentDatabase, databaseUUID, err := currentDatabaseNameAndUUID(ctx, c)
if err != nil && !errors.Is(err, errDatabaseNotFound) {
io.Error(err)
os.Exit(1)
}
// Check if --app flag is set explicitly
var appFlagSet bool
for _, cliContext := range c.Lineage() {
if cliContext.IsSet("app") {
appFlagSet = true
break
}
}
if appFlagSet && currentDatabase != "" && databaseUUID != "" {
io.Error("You can't use --app and --database flags together.")
os.Exit(1)
}
if currentApp == "" && currentDatabase == "" {
io.Error("No application or database found. Please use --app or --database flag.")
os.Exit(1)
}
currentResource := currentApp
if currentDatabase != "" {
currentResource = currentDatabase
}
debug.Println("[detect] Current resource is", currentResource)
if databaseUUID != "" {
debug.Println("[detect] Current database UUID is", databaseUUID)
}
return currentResource, databaseUUID
}
// CurrentApp returns the app name if it has been found in one of the following:
// app flag, environment variable "SCALINGO_APP", current Git remote.
// It returns an empty string if not found.
func CurrentApp(ctx context.Context, c *cli.Command) string {
appName := extractAppName(ctx, c)
if appName == "" {
io.Error("Unable to find the application name, please use --app flag.")
os.Exit(1)
}
debug.Println("[detect] App name is", appName)
return appName
}
// currentDatabaseNameAndUUID returns the database name and its UUID
// if database name has been found in one of the following:
// database flag, environment variable "SCALINGO_DATABASE".
// It returns an empty string and errDatabaseNotFound error if the database name
// is not provided or resource ID not found.
func currentDatabaseNameAndUUID(ctx context.Context, c *cli.Command) (string, string, error) {
dbName := ExtractDatabaseNameFromCommandLineOrEnv(c)
if dbName == "" {
return "", "", errDatabaseNotFound
}
debug.Println("[detect] Database name is", dbName)
client, err := config.ScalingoClient(ctx)
if err != nil {
return "", "", errors.Wrap(ctx, err, "get Scalingo client")
}
// In case of a database, addons list should return only one element.
addons, err := client.AddonsList(ctx, dbName)
if err != nil {
return "", "", errors.Wrap(ctx, err, "list addons")
}
if len(addons) == 0 {
io.Warning("No database found with the given name.")
return "", "", errDatabaseNotFound
}
if len(addons) > 1 {
io.Error("Multiple databases found with the given name, it may be an application. Please use the database name instead.")
return "", "", errDatabaseNotFound
}
databaseUUID := addons[0].ID
if databaseUUID == "" {
io.Error("Unable to find the database ID with the given name.")
return "", "", errDatabaseNotFound
}
debug.Println("[detect] Database UUID is", databaseUUID)
return dbName, databaseUUID, nil
}
// GetAppNameFromGitRemote searches into the current directory and its parent for a remote
// named remoteName or scalingo-<remoteName>.
//
// It returns the application name and an error.
func GetAppNameFromGitRemote(ctx context.Context, directory string, remoteName string) (string, error) {
remotes, err := utils.ScalingoGitRemotes(ctx, directory)
if err != nil {
return "", errors.Wrapf(ctx, err, "list git remotes from %s", directory)
}
altRemoteName := "scalingo-" + remoteName
for _, remote := range remotes {
if remote.Config().Name == remoteName ||
remote.Config().Name == altRemoteName {
return extractAppNameFromGitRemote(remote.Config().URLs[0]), nil
}
}
return "", errors.Newf(ctx, "[detect] Scalingo Git remote hasn't been found")
}
// RemoteNameFromFlags returns the remote name specified in command flags
func RemoteNameFromFlags(c *cli.Command) string {
for _, cliContext := range c.Lineage() {
if cliContext.String("remote") != "" {
return cliContext.String("remote")
}
}
return ""
}
func extractAppName(ctx context.Context, c *cli.Command) string {
for _, cliContext := range c.Lineage() {
appName := cliContext.String("app")
if appName != "" && appName != "<name>" {
return appName
}
}
var err error
var appName string
if os.Getenv("SCALINGO_APP") != "" {
appName = os.Getenv("SCALINGO_APP")
} else if dir, ok := utils.DetectGit(); ok {
appName, err = GetAppNameFromGitRemote(ctx, dir, RemoteNameFromFlags(c))
if err != nil {
debug.Println(err)
}
}
return appName
}
func ExtractDatabaseNameFromCommandLineOrEnv(c *cli.Command) string {
if os.Getenv("SCALINGO_PREVIEW_FEATURES") != "true" {
return ""
}
for _, cliContext := range c.Lineage() {
dbName := cliContext.String("database")
if dbName != "" && dbName != "<database_name>" {
return dbName
}
}
var dbName string
if os.Getenv("SCALINGO_DATABASE") != "" {
dbName = os.Getenv("SCALINGO_DATABASE")
}
return dbName
}
// extractAppNameFromGitRemote parses a Git remote and return the app name extracted
// out of it. The Git remote URL may look like:
// - SSH on a custom port: ssh://git@host:port/appName.git
// - GitHub: git@github.com:owner/appName.git
func extractAppNameFromGitRemote(url string) string {
splittedURL := strings.Split(strings.TrimSuffix(url, ".git"), ":")
appName := splittedURL[len(splittedURL)-1]
// appName may contain "port/appName" or "owner/appName". We keep the part
// after the slash.
i := strings.LastIndex(appName, "/")
if i != -1 {
appName = appName[i+1:]
}
return appName
}