forked from jfrog/jfrog-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
372 lines (350 loc) · 12.1 KB
/
main.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package main
import (
"fmt"
"os"
"runtime"
"sort"
"strings"
"github.com/agnivade/levenshtein"
corecommon "github.com/jfrog/jfrog-cli-core/v2/docs/common"
setupcore "github.com/jfrog/jfrog-cli-core/v2/general/envsetup"
"github.com/jfrog/jfrog-cli-core/v2/plugins/components"
coreconfig "github.com/jfrog/jfrog-cli-core/v2/utils/config"
"github.com/jfrog/jfrog-cli-core/v2/utils/coreutils"
"github.com/jfrog/jfrog-cli-core/v2/utils/log"
securityCLI "github.com/jfrog/jfrog-cli-security/cli"
"github.com/jfrog/jfrog-cli/artifactory"
"github.com/jfrog/jfrog-cli/buildtools"
"github.com/jfrog/jfrog-cli/completion"
"github.com/jfrog/jfrog-cli/config"
"github.com/jfrog/jfrog-cli/distribution"
"github.com/jfrog/jfrog-cli/docs/common"
"github.com/jfrog/jfrog-cli/docs/general/cisetup"
loginDocs "github.com/jfrog/jfrog-cli/docs/general/login"
tokenDocs "github.com/jfrog/jfrog-cli/docs/general/token"
cisetupcommand "github.com/jfrog/jfrog-cli/general/cisetup"
"github.com/jfrog/jfrog-cli/general/envsetup"
"github.com/jfrog/jfrog-cli/general/login"
"github.com/jfrog/jfrog-cli/general/project"
"github.com/jfrog/jfrog-cli/general/token"
"github.com/jfrog/jfrog-cli/lifecycle"
"github.com/jfrog/jfrog-cli/missioncontrol"
"github.com/jfrog/jfrog-cli/pipelines"
"github.com/jfrog/jfrog-cli/plugins"
"github.com/jfrog/jfrog-cli/plugins/utils"
"github.com/jfrog/jfrog-cli/utils/cliutils"
clientutils "github.com/jfrog/jfrog-client-go/utils"
"github.com/jfrog/jfrog-client-go/utils/io/fileutils"
clientlog "github.com/jfrog/jfrog-client-go/utils/log"
"github.com/urfave/cli"
"golang.org/x/exp/slices"
)
const commandHelpTemplate string = `{{.HelpName}}{{if .UsageText}}
Arguments:
{{.UsageText}}
{{end}}{{if .VisibleFlags}}
Options:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}{{if .ArgsUsage}}
Environment Variables:
{{.ArgsUsage}}{{end}}
`
const subcommandHelpTemplate = `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{if .Usage}}{{.Usage}}{{ "\n\t" }}{{end}}{{.HelpName}} command{{if .VisibleFlags}} [command options]{{end}} [arguments...]
COMMANDS:
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
{{end}}{{if .VisibleFlags}}{{if .ArgsUsage}}
Arguments:
{{.ArgsUsage}}{{ "\n" }}{{end}}
OPTIONS:
{{range .VisibleFlags}}{{.}}
{{end}}
{{end}}
`
const jfrogAppName = "jf"
func main() {
log.SetDefaultLogger()
err := execMain()
if cleanupErr := fileutils.CleanOldDirs(); cleanupErr != nil {
clientlog.Warn(cleanupErr)
}
coreutils.ExitOnErr(err)
}
func execMain() error {
// Set JFrog CLI's user-agent on the jfrog-client-go.
clientutils.SetUserAgent(coreutils.GetCliUserAgent())
app := cli.NewApp()
app.Name = jfrogAppName
app.Usage = "See https://github.com/jfrog/jfrog-cli for usage instructions."
app.Version = cliutils.GetVersion()
args := os.Args
cliutils.SetCliExecutableName(args[0])
app.EnableBashCompletion = true
commands, err := getCommands()
if err != nil {
clientlog.Error(err)
os.Exit(1)
}
sort.Slice(commands, func(i, j int) bool { return commands[i].Name < commands[j].Name })
app.Commands = commands
cli.CommandHelpTemplate = commandHelpTemplate
cli.AppHelpTemplate = getAppHelpTemplate()
cli.SubcommandHelpTemplate = subcommandHelpTemplate
app.CommandNotFound = func(c *cli.Context, command string) {
_, err := fmt.Fprintf(c.App.Writer, "'"+c.App.Name+" "+command+"' is not a jf command. See --help\n")
if err != nil {
clientlog.Debug(err)
os.Exit(1)
}
if bestSimilarity := searchSimilarCmds(c.App.Commands, command); len(bestSimilarity) > 0 {
text := "The most similar "
if len(bestSimilarity) == 1 {
text += "command is:\n\tjf " + bestSimilarity[0]
} else {
sort.Strings(bestSimilarity)
text += "commands are:\n\tjf " + strings.Join(bestSimilarity, "\n\tjf ")
}
_, err = fmt.Fprintln(c.App.Writer, text)
if err != nil {
clientlog.Debug(err)
}
}
os.Exit(1)
}
app.Before = func(ctx *cli.Context) error {
clientlog.Debug("JFrog CLI version:", app.Version)
clientlog.Debug("OS/Arch:", runtime.GOOS+"/"+runtime.GOARCH)
warningMessage, err := cliutils.CheckNewCliVersionAvailable(app.Version)
if err != nil {
clientlog.Debug("failed while trying to check latest JFrog CLI version:", err.Error())
}
if warningMessage != "" {
clientlog.Warn(warningMessage)
}
return nil
}
err = app.Run(args)
return err
}
// Detects typos and can identify one or more valid commands similar to the error command.
// In Addition, if a subcommand is found with exact match, preferred it over similar commands, for example:
// "jf bp" -> return "jf rt bp"
func searchSimilarCmds(cmds []cli.Command, toCompare string) (bestSimilarity []string) {
// Set min diff between two commands.
minDistance := 2
for _, cmd := range cmds {
// Check if we have an exact match with the next level.
for _, subCmd := range cmd.Subcommands {
for _, subCmdName := range subCmd.Names() {
// Found exact match, return it.
distance := levenshtein.ComputeDistance(subCmdName, toCompare)
if distance == 0 {
return []string{cmd.Name + " " + subCmdName}
}
}
}
// Search similar commands with max diff of 'minDistance'.
for _, cmdName := range cmd.Names() {
distance := levenshtein.ComputeDistance(cmdName, toCompare)
if distance == minDistance {
// In the case of an alias, we don't want to show the full command name, but the alias.
// Therefore, we trim the end of the full name and concat the actual matched (alias/full command name)
bestSimilarity = append(bestSimilarity, strings.Replace(cmd.FullName(), cmd.Name, cmdName, 1))
}
if distance < minDistance {
// Found a cmd with a smaller distance.
minDistance = distance
bestSimilarity = []string{strings.Replace(cmd.FullName(), cmd.Name, cmdName, 1)}
}
}
}
return
}
const otherCategory = "Other"
func getCommands() ([]cli.Command, error) {
cliNameSpaces := []cli.Command{
{
Name: cliutils.CmdArtifactory,
Usage: "Artifactory commands.",
Subcommands: artifactory.GetCommands(),
Category: otherCategory,
},
{
Name: cliutils.CmdMissionControl,
Usage: "Mission Control commands.",
Subcommands: missioncontrol.GetCommands(),
Category: otherCategory,
},
{
Name: cliutils.CmdDistribution,
Usage: "Distribution commands.",
Subcommands: distribution.GetCommands(),
Category: otherCategory,
},
{
Name: cliutils.CmdPipelines,
Usage: "JFrog Pipelines commands.",
Subcommands: pipelines.GetCommands(),
Category: otherCategory,
},
{
Name: cliutils.CmdCompletion,
Usage: "Generate autocomplete scripts.",
Subcommands: completion.GetCommands(),
Category: otherCategory,
},
{
Name: cliutils.CmdPlugin,
Usage: "Plugins handling commands.",
Subcommands: plugins.GetCommands(),
Category: otherCategory,
},
{
Name: cliutils.CmdConfig,
Aliases: []string{"c"},
Usage: "Config commands.",
Subcommands: config.GetCommands(),
Category: otherCategory,
},
{
Name: cliutils.CmdProject,
Usage: "Project commands.",
Subcommands: project.GetCommands(),
Category: otherCategory,
},
{
Name: "ci-setup",
Usage: cisetup.GetDescription(),
HelpName: corecommon.CreateUsage("ci-setup", cisetup.GetDescription(), cisetup.Usage),
ArgsUsage: common.CreateEnvVars(),
BashComplete: corecommon.CreateBashCompletionFunc(),
Category: otherCategory,
Action: func(c *cli.Context) error {
return cisetupcommand.RunCiSetupCmd()
},
},
// {
// Name: "invite",
// Usage: invite.GetDescription(),
// HelpName: corecommon.CreateUsage("invite", invite.GetDescription(), invite.Usage),
// ArgsUsage: common.CreateEnvVars(),
// BashComplete: corecommon.CreateBashCompletionFunc(),
// Category: otherCategory,
// Action: func(c *cli.Context) error {
// return invitecommand.RunInviteCmd(c)
// },
// },
{
Name: "setup",
HideHelp: true,
Hidden: true,
Flags: cliutils.GetCommandFlags(cliutils.Setup),
Action: SetupCmd,
},
{
Name: "intro",
HideHelp: true,
Hidden: true,
Flags: cliutils.GetCommandFlags(cliutils.Intro),
Action: IntroCmd,
},
{
Name: cliutils.CmdOptions,
Usage: "Show all supported environment variables.",
Category: otherCategory,
Action: func(*cli.Context) {
fmt.Println(common.GetGlobalEnvVars())
},
},
{
Name: "login",
Usage: loginDocs.GetDescription(),
HelpName: corecommon.CreateUsage("login", loginDocs.GetDescription(), loginDocs.Usage),
BashComplete: corecommon.CreateBashCompletionFunc(),
Category: otherCategory,
Action: login.LoginCmd,
},
{
Name: "access-token-create",
Aliases: []string{"atc"},
Flags: cliutils.GetCommandFlags(cliutils.AccessTokenCreate),
Usage: tokenDocs.GetDescription(),
HelpName: corecommon.CreateUsage("atc", tokenDocs.GetDescription(), tokenDocs.Usage),
UsageText: tokenDocs.GetArguments(),
ArgsUsage: common.CreateEnvVars(),
BashComplete: corecommon.CreateBashCompletionFunc(),
Action: token.AccessTokenCreateCmd,
},
}
securityCmds, err := ConvertEmbeddedPlugin(securityCLI.GetJfrogCliSecurityApp())
if err != nil {
return nil, err
}
allCommands := append(slices.Clone(cliNameSpaces), securityCmds...)
allCommands = append(allCommands, utils.GetPlugins()...)
allCommands = append(allCommands, buildtools.GetCommands()...)
allCommands = append(allCommands, lifecycle.GetCommands()...)
return append(allCommands, buildtools.GetBuildToolsHelpCommands()...), nil
}
// Embedded plugins are CLI plugins that are embedded in the JFrog CLI and not require any installation.
// This function converts an embedded plugin to a cli.Command slice to be registered as commands of the cli.
func ConvertEmbeddedPlugin(jfrogPlugin components.App) (converted []cli.Command, err error) {
for i := range jfrogPlugin.Subcommands {
// commands name-space without category are considered as 'other' category
if jfrogPlugin.Subcommands[i].Category == "" {
jfrogPlugin.Subcommands[i].Category = otherCategory
}
}
if converted, err = components.ConvertAppCommands(jfrogPlugin); err != nil {
err = fmt.Errorf("failed adding '%s' embedded plugin commands. Last error: %s", jfrogPlugin.Name, err.Error())
}
return
}
func getAppHelpTemplate() string {
return `NAME:
` + coreutils.GetCliExecutableName() + ` - {{.Usage}}
USAGE:
{{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} [arguments...]{{end}}
{{if .Version}}
VERSION:
{{.Version}}
{{end}}{{if len .Authors}}
AUTHOR(S):
{{range .Authors}}{{ . }}{{end}}
{{end}}{{if .VisibleCommands}}
COMMANDS:{{range .VisibleCategories}}{{if .Name}}
{{.Name}}:{{end}}{{range .VisibleCommands}}
{{join .Names ", "}}{{ "\t" }}{{if .Description}}{{.Description}}{{else}}{{.Usage}}{{end}}{{end}}{{end}}{{end}}{{if .VisibleFlags}}
GLOBAL OPTIONS:
{{range .VisibleFlags}}{{.}}
{{end}}
{{end}}
`
}
func SetupCmd(c *cli.Context) error {
format := setupcore.Human
formatFlag := c.String("format")
if formatFlag == string(setupcore.Machine) {
format = setupcore.Machine
}
return envsetup.RunEnvSetupCmd(c, format)
}
func IntroCmd(_ *cli.Context) error {
ci, err := clientutils.GetBoolEnvValue(coreutils.CI, false)
if ci || err != nil {
return err
}
clientlog.Output()
clientlog.Output(coreutils.PrintTitle(fmt.Sprintf("Thank you for installing version %s of JFrog CLI! 🐸", cliutils.CliVersion)))
var serverExists bool
serverExists, err = coreconfig.IsServerConfExists()
if serverExists || err != nil {
return err
}
clientlog.Output(coreutils.PrintTitle("Here's how you get started."))
clientlog.Output("🐸 If you already have a JFrog environment, run the 'jf c add' command to set its connection details.")
clientlog.Output("🐸 Don't have a JFrog environment? No problem!\n Simply run the 'jf setup' command.\n This command will set you up with a free JFrog environment in the cloud, and also configure JFrog CLI to use it, all in less then two minutes.\n")
return nil
}