-
Notifications
You must be signed in to change notification settings - Fork 223
/
utils.go
315 lines (282 loc) · 10.4 KB
/
utils.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
package cliutils
import (
"fmt"
"os"
"strings"
"github.com/codegangsta/cli"
"github.com/jfrog/jfrog-cli-core/utils/config"
"github.com/jfrog/jfrog-cli-core/utils/coreutils"
"github.com/jfrog/jfrog-cli/utils/summary"
"github.com/jfrog/jfrog-client-go/utils"
clientutils "github.com/jfrog/jfrog-client-go/utils"
"github.com/jfrog/jfrog-client-go/utils/errorutils"
"github.com/jfrog/jfrog-client-go/utils/io/content"
"github.com/jfrog/jfrog-client-go/utils/log"
"github.com/pkg/errors"
)
// Error modes (how should the application behave when the CheckError function is invoked):
type OnError string
func init() {
// Initialize cli-core values.
cliUserAgent := os.Getenv(UserAgent)
if cliUserAgent != "" {
cliUserAgentName, cliUserAgentVersion := splitAgentNameAndVersion(cliUserAgent)
coreutils.SetCliUserAgentName(cliUserAgentName)
coreutils.SetCliUserAgentVersion(cliUserAgentVersion)
} else {
coreutils.SetCliUserAgentName(ClientAgent)
coreutils.SetCliUserAgentVersion(CliVersion)
}
coreutils.SetClientAgentName(ClientAgent)
coreutils.SetClientAgentVersion(CliVersion)
}
// Splits the full agent name to its name and version.
// The full agent name needs to be the agent name and version separated by a slash ('/').
// If the full agent name doesn't include a version, then it's returned as the agent name and an empty string is returned as the agent version.
func splitAgentNameAndVersion(fullAgentName string) (string, string) {
var agentName, agentVersion string
lastSlashIndex := strings.LastIndex(fullAgentName, "/")
if lastSlashIndex == -1 {
agentName = fullAgentName
} else {
agentName = fullAgentName[:lastSlashIndex]
agentVersion = fullAgentName[lastSlashIndex+1:]
}
return agentName, agentVersion
}
func GetCliError(err error, success, failed int, failNoOp bool) error {
switch coreutils.GetExitCode(err, success, failed, failNoOp) {
case coreutils.ExitCodeError:
{
var errorMessage string
if err != nil {
errorMessage = err.Error()
}
return coreutils.CliError{ExitCode: coreutils.ExitCodeError, ErrorMsg: errorMessage}
}
case coreutils.ExitCodeFailNoOp:
return coreutils.CliError{ExitCode: coreutils.ExitCodeFailNoOp, ErrorMsg: "No errors, but also no files affected (fail-no-op flag)."}
default:
return nil
}
}
type DetailedSummaryRecord struct {
Source string `json:"source,omitempty"`
Target string `json:"target"`
}
type ExtendedDetailedSummaryRecord struct {
DetailedSummaryRecord
Sha256 string `json:"sha256"`
}
// Print summary report.
// a given non-nil error will pass through and be returned as is if no other errors are raised.
// In case of a nil error, the current function error will be returned.
func summaryPrintError(summaryError, originalError error) error {
if originalError != nil {
if summaryError != nil {
log.Error(summaryError)
}
return originalError
}
return summaryError
}
func PrintSummaryReport(success, failed int, originalErr error) error {
basicSummary, mErr := CreateSummaryReportString(success, failed, originalErr)
if mErr != nil {
return summaryPrintError(mErr, originalErr)
}
log.Output(basicSummary)
return summaryPrintError(mErr, originalErr)
}
// Prints a summary report.
// If a resultReader is provided, we will iterate over the result and print a detailed summary including the affected files.
func PrintDetailedSummaryReport(success, failed int, reader *content.ContentReader, printExtendedDetails bool, originalErr error) error {
basicSummary, mErr := CreateSummaryReportString(success, failed, originalErr)
if mErr != nil {
return summaryPrintError(mErr, originalErr)
}
// A reader wasn't provided, prints the basic summary json and return.
if reader == nil {
log.Output(basicSummary)
return summaryPrintError(mErr, originalErr)
}
reader.Reset()
defer reader.Close()
writer, mErr := content.NewContentWriter("files", false, true)
if mErr != nil {
log.Output(basicSummary)
return summaryPrintError(mErr, originalErr)
}
// We remove the closing curly bracket in order to append the affected files array using a responseWriter to write directly to stdout.
basicSummary = strings.TrimSuffix(basicSummary, "\n}") + ","
log.Output(basicSummary)
defer log.Output("}")
readerLength, _ := reader.Length()
// If the reader is empty we will print an empty array.
if readerLength == 0 {
log.Output(" \"files\": []")
} else {
for transferDetails := new(clientutils.FileTransferDetails); reader.NextRecord(transferDetails) == nil; transferDetails = new(clientutils.FileTransferDetails) {
writer.Write(getDetailedSummaryRecord(transferDetails, printExtendedDetails))
}
}
mErr = writer.Close()
return summaryPrintError(mErr, originalErr)
}
// Get the detailed summary record.
// In case of an upload/publish commands we want to print sha256 of the uploaded file in addition to the source and the target.
func getDetailedSummaryRecord(transferDetails *clientutils.FileTransferDetails, extendDetailedSummary bool) interface{} {
record := DetailedSummaryRecord{
Source: transferDetails.SourcePath,
Target: transferDetails.TargetPath,
}
if extendDetailedSummary {
extendedRecord := ExtendedDetailedSummaryRecord{
DetailedSummaryRecord: record,
Sha256: transferDetails.Sha256,
}
return extendedRecord
}
return record
}
func PrintBuildInfoSummaryReport(succeeded bool, sha256 string, originalErr error) error {
success, failed := 1, 0
if !succeeded {
success, failed = 0, 1
}
summary, mErr := CreateBuildInfoSummaryReportString(success, failed, sha256, originalErr)
if mErr != nil {
return summaryPrintError(mErr, originalErr)
}
log.Output(summary)
return summaryPrintError(mErr, originalErr)
}
func CreateSummaryReportString(success, failed int, err error) (string, error) {
summaryReport := summary.GetSummaryReport(success, failed, err)
content, mErr := summaryReport.Marshal()
if errorutils.CheckError(mErr) != nil {
return "", mErr
}
return utils.IndentJson(content), mErr
}
func CreateBuildInfoSummaryReportString(success, failed int, sha256 string, err error) (string, error) {
buildInfoSummary := summary.NewBuildInfoSummary(success, failed, sha256, err)
content, mErr := buildInfoSummary.Marshal()
if errorutils.CheckError(mErr) != nil {
return "", mErr
}
return utils.IndentJson(content), mErr
}
func PrintHelpAndReturnError(msg string, context *cli.Context) error {
log.Error(msg + " " + GetDocumentationMessage())
cli.ShowCommandHelp(context, context.Command.Name)
return errors.New(msg)
}
// This function indicates whether the command should be executed without
// confirmation warning or not.
// If the --quiet option was sent, it is used to determine whether to prompt the confirmation or not.
// If not, the command will prompt the confirmation, unless the CI environment variable was set to true.
func GetQuietValue(c *cli.Context) bool {
if c.IsSet("quiet") {
return c.Bool("quiet")
}
return getCiValue()
}
// This function indicates whether the command should be executed in
// an interactive mode.
// If the --interactive option was sent, it is used to determine the mode.
// If not, the mode will be interactive, unless the CI environment variable was set to true.
func GetInteractiveValue(c *cli.Context) bool {
if c.IsSet("interactive") {
return c.BoolT("interactive")
}
return !getCiValue()
}
// Return true if the CI environment variable was set to true.
func getCiValue() bool {
var ci bool
var err error
if ci, err = clientutils.GetBoolEnvValue(coreutils.CI, false); err != nil {
return false
}
return ci
}
func GetVersion() string {
return CliVersion
}
func GetDocumentationMessage() string {
return "You can read the documentation at https://www.jfrog.com/confluence/display/CLI/JFrog+CLI"
}
func GetBuildName(buildName string) string {
return getOrDefaultEnv(buildName, coreutils.BuildName)
}
func GetBuildUrl(buildUrl string) string {
return getOrDefaultEnv(buildUrl, BuildUrl)
}
func GetEnvExclude(envExclude string) string {
return getOrDefaultEnv(envExclude, EnvExclude)
}
// Return argument if not empty or retrieve from environment variable
func getOrDefaultEnv(arg, envKey string) string {
if arg != "" {
return arg
}
return os.Getenv(envKey)
}
func ShouldOfferConfig() (bool, error) {
exists, err := config.IsServerConfExists()
if err != nil || exists {
return false, err
}
var ci bool
if ci, err = clientutils.GetBoolEnvValue(coreutils.CI, false); err != nil {
return false, err
}
var offerConfig bool
if offerConfig, err = clientutils.GetBoolEnvValue(OfferConfig, !ci); err != nil {
return false, err
}
if !offerConfig {
config.SaveServersConf(make([]*config.ServerDetails, 0))
return false, nil
}
msg := fmt.Sprintf("To avoid this message in the future, set the %s environment variable to false.\n"+
"The CLI commands require the URL and authentication details\n"+
"Configuring JFrog CLI with these parameters now will save you having to include them as command options.\n"+
"You can also configure these parameters later using the 'jfrog c' command.\n"+
"Configure now?", OfferConfig)
confirmed := coreutils.AskYesNo(msg, false)
if !confirmed {
config.SaveServersConf(make([]*config.ServerDetails, 0))
return false, nil
}
return true, nil
}
func CreateServerDetailsFromFlags(c *cli.Context) (details *config.ServerDetails) {
details = new(config.ServerDetails)
details.Url = clientutils.AddTrailingSlashIfNeeded(c.String(url))
details.ArtifactoryUrl = clientutils.AddTrailingSlashIfNeeded(c.String(configRtUrl))
details.DistributionUrl = clientutils.AddTrailingSlashIfNeeded(c.String(distUrl))
details.XrayUrl = clientutils.AddTrailingSlashIfNeeded(c.String(configXrUrl))
details.MissionControlUrl = clientutils.AddTrailingSlashIfNeeded(c.String(configMcUrl))
details.PipelinesUrl = clientutils.AddTrailingSlashIfNeeded(c.String(configPlUrl))
details.ApiKey = c.String(apikey)
details.User = c.String(user)
details.Password = c.String(password)
details.SshKeyPath = c.String(sshKeyPath)
details.SshPassphrase = c.String(sshPassphrase)
details.AccessToken = c.String(accessToken)
details.ClientCertPath = c.String(clientCertPath)
details.ClientCertKeyPath = c.String(clientCertKeyPath)
details.ServerId = c.String(serverId)
details.InsecureTls = c.Bool(insecureTls)
if details.ApiKey != "" && details.User != "" && details.Password == "" {
// The API Key is deprecated, use password option instead.
details.Password = details.ApiKey
details.ApiKey = ""
}
return
}
func IsLegacyGoPublish(c *cli.Context) bool {
return c.Command.Name == "go-publish" && c.NArg() > 1
}