From 1c313ef77353792a54556fdca65e9eafe0e45f86 Mon Sep 17 00:00:00 2001 From: "Anand Babu (AB) Periasamy" Date: Sat, 22 Aug 2015 22:31:15 -0700 Subject: [PATCH] final update and tiny fixes --- config-main.go | 6 +++--- cp-main.go | 6 +++--- mirror-main.go | 30 ++++++++++++++---------------- notifier.go | 5 +++-- session-main.go | 38 +++++++++++++++++--------------------- session-v2.go | 21 +++++++++------------ share-main.go | 20 ++++++++++---------- update-main.go | 26 +++++++++++++------------- url.go | 6 +++--- verify-runtime.go | 17 +++++++++-------- version-main.go | 4 +--- 11 files changed, 85 insertions(+), 94 deletions(-) diff --git a/config-main.go b/config-main.go index f8776e5a..40f5ef3d 100644 --- a/config-main.go +++ b/config-main.go @@ -70,13 +70,13 @@ func (a AliasMessage) String() string { if !globalJSONFlag { message := console.Colorize("Alias", fmt.Sprintf("[%s] <-", a.Alias)) message += console.Colorize("URL", fmt.Sprintf("%s", a.URL)) - return message + "\n" + return message } jsonMessageBytes, err := json.Marshal(a) if err != nil { panic(err) } - return string(jsonMessageBytes) + "\n" + return string(jsonMessageBytes) } // mainConfig is the handle for "mc config" sub-command. writes configuration data in json format to config file. @@ -112,7 +112,7 @@ func mainConfig(ctx *cli.Context) { "URL": color.New(color.FgWhite), }) for k, v := range newConf.Aliases { - console.Print(AliasMessage{k, v}) + console.Println(AliasMessage{k, v}) } return } diff --git a/cp-main.go b/cp-main.go index da381209..51ca993f 100644 --- a/cp-main.go +++ b/cp-main.go @@ -78,12 +78,12 @@ type CopyMessage struct { // String string printer for copy message func (c CopyMessage) String() string { if !globalJSONFlag { - return fmt.Sprintf("‘%s’ -> ‘%s’\n", c.Source, c.Target) + return fmt.Sprintf("‘%s’ -> ‘%s’", c.Source, c.Target) } copyMessageBytes, err := json.Marshal(c) fatalIf(probe.NewError(err), "Failed to marshal copy message.") - return string(copyMessageBytes) + "\n" + return string(copyMessageBytes) } // doCopy - Copy a singe file from source to destination @@ -119,7 +119,7 @@ func doCopy(cpURLs copyURLs, bar *barSend, cpQueue <-chan bool, wg *sync.WaitGro Source: cpURLs.SourceContent.Name, Target: cpURLs.TargetContent.Name, Length: cpURLs.SourceContent.Size, - }) + }.String() + "\n") newReader = reader } else { // set up progress diff --git a/mirror-main.go b/mirror-main.go index 5031a6d1..7952b62d 100644 --- a/mirror-main.go +++ b/mirror-main.go @@ -87,7 +87,7 @@ func doMirror(sURLs mirrorURLs, bar *barSend, mirrorQueueCh <-chan bool, wg *syn if !globalQuietFlag && !globalJSONFlag { bar.ErrorGet(int64(length)) } - sURLs.Error = err.Trace() + sURLs.Error = err.Trace(sURLs.SourceContent.Name) statusCh <- sURLs return } @@ -102,7 +102,7 @@ func doMirror(sURLs mirrorURLs, bar *barSend, mirrorQueueCh <-chan bool, wg *syn console.PrintC(MirrorMessage{ Source: sURLs.SourceContent.Name, Targets: targetURLs, - }) + }.String() + "\n") newReader = reader } else { // set up progress @@ -115,7 +115,7 @@ func doMirror(sURLs mirrorURLs, bar *barSend, mirrorQueueCh <-chan bool, wg *syn if !globalQuietFlag && !globalJSONFlag { bar.ErrorPut(int64(length)) } - sURLs.Error = err.Trace() + sURLs.Error = err.Trace(targetURLs...) statusCh <- sURLs return } @@ -156,7 +156,7 @@ func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) { break } if sURLs.Error != nil { - errorIf(sURLs.Error, "Unable to prepare mirror URLs.") + errorIf(sURLs.Error, "Unable to prepare mirror arguments.") break } if sURLs.isEmpty() { @@ -165,7 +165,7 @@ func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) { jsonData, err := json.Marshal(sURLs) if err != nil { session.Close() - console.Fatalf("Unable to marshal URLs to JSON. %s\n", probe.NewError(err)) + fatalIf(probe.NewError(err), "Unable to marshal URLs into JSON.") } fmt.Fprintln(dataFP, string(jsonData)) if !globalQuietFlag && !globalJSONFlag { @@ -228,8 +228,7 @@ func doMirrorCmdSession(session *sessionV2) { if sURLs.Error == nil { session.Header.LastCopied = sURLs.SourceContent.Name } else { - console.Println() - errorIf(sURLs.Error, fmt.Sprintf("Failed to mirror ‘%s’.", sURLs.SourceContent.Name)) + errorIf(sURLs.Error.Trace(), "Failed to mirror.") } case <-trapCh: // Receive interrupt notification. session.Close() @@ -271,24 +270,23 @@ func doMirrorCmdSession(session *sessionV2) { func mainMirror(ctx *cli.Context) { checkMirrorSyntax(ctx) + var e error session := newSessionV2() - - var err error session.Header.CommandType = "mirror" - session.Header.RootPath, err = os.Getwd() - if err != nil { + session.Header.RootPath, e = os.Getwd() + if e != nil { session.Close() session.Delete() - console.Fatalf("Unable to get current working folder. %s\n", err) + fatalIf(probe.NewError(e), "Unable to get current working folder.") } // extract URLs. - var perr *probe.Error - session.Header.CommandArgs, perr = args2URLs(ctx.Args()) - if perr != nil { + var err *probe.Error + session.Header.CommandArgs, err = args2URLs(ctx.Args()) + if err != nil { session.Close() session.Delete() - console.Fatalf("One or more unknown URL types found in %s. %s\n", ctx.Args(), perr) + fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("One or more unknown argument types found in ‘%s’.", ctx.Args())) } doMirrorCmdSession(session) diff --git a/notifier.go b/notifier.go index bfcd2896..550bf672 100644 --- a/notifier.go +++ b/notifier.go @@ -23,11 +23,12 @@ import ( "strings" "github.com/fatih/color" + "github.com/minio/minio/pkg/probe" "github.com/olekukonko/ts" ) // printUpdateNotify - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier -func printUpdateNotify(updateString, latestVersion, currentVersion string) (string, error) { +func printUpdateNotify(updateString, latestVersion, currentVersion string) (string, *probe.Error) { // TODO - make this configurable // // initialize coloring @@ -52,7 +53,7 @@ func printUpdateNotify(updateString, latestVersion, currentVersion string) (stri terminal, err := ts.GetSize() if err != nil { - return "", err + return "", probe.NewError(err) } var message string switch { diff --git a/session-main.go b/session-main.go index 9ea386c4..1358f8fb 100644 --- a/session-main.go +++ b/session-main.go @@ -17,6 +17,7 @@ package main import ( + "errors" "os" "sort" "strings" @@ -76,7 +77,7 @@ func listSessions() *probe.Error { // sort sessions based on time sort.Sort(bySessionWhen(bySessions)) for _, session := range bySessions { - console.Print(session) + console.Println(session) } return nil } @@ -85,22 +86,21 @@ func clearSession(sid string) { if sid == "all" { for _, sid := range getSessionIDs() { session, err := loadSessionV2(sid) - fatalIf(err.Trace(), "Unable to load session ‘"+sid+"’") - - fatalIf(session.Delete().Trace(), "Unable to load session ‘"+sid+"’") + fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’") + fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’") } return } if !isSession(sid) { - console.Fatalf("Session ‘%s’ not found.\n", sid) + fatalIf(probe.NewError(errors.New("")), "Session ‘"+sid+"’ not found.") } session, err := loadSessionV2(sid) - fatalIf(err.Trace(), "Unable to load session ‘"+sid+"’") + fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.") if session != nil { - fatalIf(session.Delete().Trace(), "Unable to load session ‘"+sid+"’") + fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.") } } @@ -121,12 +121,12 @@ func mainSession(ctx *cli.Context) { cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code } if !isSessionDirExists() { - fatalIf(createSessionDir(), "Unable to create session directory") + fatalIf(createSessionDir().Trace(), "Unable to create session directory.") } switch strings.TrimSpace(ctx.Args().First()) { // list resumable sessions case "list": - fatalIf(listSessions(), "Unable to list sessions") + fatalIf(listSessions().Trace(), "Unable to list sessions.") case "resume": if len(ctx.Args().Tail()) != 1 { cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code @@ -138,11 +138,11 @@ func mainSession(ctx *cli.Context) { sid := strings.TrimSpace(ctx.Args().Tail().First()) if !isSession(sid) { - console.Fatalf("Session ‘%s’ not found.\n", sid) + fatalIf(probe.NewError(errors.New("")), "Session ‘"+sid+"’ not found.") } s, err := loadSessionV2(sid) - fatalIf(err.Trace(sid), "Unable to load session") + fatalIf(err.Trace(sid), "Unable to load session.") // extra check for testing purposes if s == nil { @@ -150,16 +150,13 @@ func mainSession(ctx *cli.Context) { } savedCwd, e := os.Getwd() - if err != nil { - console.Fatalf("Unable to verify your current working folder. %s\n", e) - } + fatalIf(probe.NewError(e), "Unable to verify your current working folder.") + if s.Header.RootPath != "" { // chdir to RootPath - if e := os.Chdir(s.Header.RootPath); e != nil { - console.Fatalf("Unable to change directory to root path while resuming session. %s\n", e) - } + e = os.Chdir(s.Header.RootPath) + fatalIf(probe.NewError(e), "Unable to change directory to root path while resuming session.") } - sessionExecute(s) err = s.Close() fatalIf(err.Trace(), "Unable to close session file properly.") @@ -169,9 +166,8 @@ func mainSession(ctx *cli.Context) { // change dir back e = os.Chdir(savedCwd) - if e != nil { - console.Fatalf("Unable to change directory to saved path. %s\n", e) - } + fatalIf(probe.NewError(e), "Unable to change directory to saved path ‘"+savedCwd+"’.") + // purge a requested pending session, if "*" purge everything case "clear": if len(ctx.Args().Tail()) != 1 { diff --git a/session-v2.go b/session-v2.go index 23c7ba60..a578fb62 100644 --- a/session-v2.go +++ b/session-v2.go @@ -20,7 +20,6 @@ package main import ( "encoding/json" - "errors" "fmt" "io" "os" @@ -79,7 +78,7 @@ func (s sessionV2) String() string { message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID)) message = message + console.Colorize("Time", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate))) message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " "))) - return message + "\n" + return message } sessionMesage := SessionJSONMessage{ SessionID: s.SessionID, @@ -87,11 +86,10 @@ func (s sessionV2) String() string { CommandType: s.Header.CommandType, CommandArgs: s.Header.CommandArgs, } - sessionJSONBytes, err := json.Marshal(sessionMesage) - if err != nil { - panic(err) - } - return string(sessionJSONBytes) + "\n" + sessionJSONBytes, e := json.Marshal(sessionMesage) + fatalIf(probe.NewError(e), "Unable to marshall into JSON.") + + return string(sessionJSONBytes) } // newSessionV2 provides a new session @@ -228,11 +226,11 @@ func loadSessionV2(sid string) (*sessionV2, *probe.Error) { s.Header.Version = "1.1.0" qs, err := quick.New(s.Header) if err != nil { - return nil, err.Trace() + return nil, err.Trace(sid, s.Header.Version) } err = qs.Load(sessionFile) if err != nil { - return nil, err.Trace() + return nil, err.Trace(sid, s.Header.Version) } s.mutex = new(sync.Mutex) @@ -240,7 +238,7 @@ func loadSessionV2(sid string) (*sessionV2, *probe.Error) { sessionDataFile, err := getSessionDataFile(s.SessionID) if err != nil { - return nil, err.Trace() + return nil, err.Trace(sid, s.Header.Version) } var e error @@ -257,8 +255,7 @@ func isCopiedFactory(lastCopied string) func(string) bool { copied := true // closure return func(sourceURL string) bool { if sourceURL == "" { - fatalIf(probe.NewError(errors.New("")), - "Empty source URL passed to isCopied() function. please report this bug at https://github.com/minio/mc/issues.") + fatalIf(probe.NewError(errInvalidArgument), "Empty source argument passed.") } if lastCopied == "" { return false diff --git a/share-main.go b/share-main.go index c6777c51..b2b3cd04 100644 --- a/share-main.go +++ b/share-main.go @@ -76,13 +76,14 @@ func mainShare(ctx *cli.Context) { if len(args) == 2 { var err error expires, err = time.ParseDuration(args.Last()) - fatalIf(probe.NewError(err), "Unable to parse time argument") + fatalIf(probe.NewError(err), "Unable to parse time argument.") } targetURL, err := getCanonicalizedURL(url, config.Aliases) fatalIf(err.Trace(url), "Unable to parse argument ‘"+url+"’.") // if recursive strip off the "..." - fatalIf(doShareCmd(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires).Trace(), "Unable generate URL for sharing") + err = doShareCmd(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires) + fatalIf(err.Trace(targetURL), "Unable generate URL for sharing.") } // ShareMessage container for share messages @@ -94,16 +95,15 @@ type ShareMessage struct { // String string printer for share message func (s ShareMessage) String() string { if !globalJSONFlag { - return fmt.Sprintf("Succesfully generated shared URL with expiry %s, please share: %s\n", s.Expires, s.PresignedURL) + return fmt.Sprintf("Succesfully generated shared URL with expiry %s, please share: %s", s.Expires, s.PresignedURL) } shareMessageBytes, err := json.Marshal(s) - if err != nil { - panic(err) - } + fatalIf(probe.NewError(err), "Failed to marshal into JSON.") + // json encoding escapes ampersand into its unicode character which is not usable directly for share // and fails with cloud storage. convert them back so that they are usable shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u0026"), []byte("&"), -1) - return fmt.Sprintf("%s\n", string(shareMessageBytes)) + return string(shareMessageBytes) } func getNewTargetURL(targetParser *client.URL, name string) string { @@ -123,10 +123,10 @@ func doShareCmd(targetURL string, recursive bool, expires time.Duration) *probe. return err.Trace() } if expires.Seconds() < 1 { - return probe.NewError(errors.New("Too low expires, expiration cannot be less than 1 second")) + return probe.NewError(errors.New("Too low expires, expiration cannot be less than 1 second.")) } if expires.Seconds() > 604800 { - return probe.NewError(errors.New("Too high expires, expiration cannot be larger than 7 days")) + return probe.NewError(errors.New("Too high expires, expiration cannot be larger than 7 days.")) } for contentCh := range clnt.List(recursive) { if contentCh.Err != nil { @@ -140,7 +140,7 @@ func doShareCmd(targetURL string, recursive bool, expires time.Duration) *probe. if err != nil { return err.Trace() } - console.PrintC(ShareMessage{Expires: expires, PresignedURL: presignedURL}) + console.PrintC(ShareMessage{Expires: expires, PresignedURL: presignedURL}.String() + "\n") } return nil } diff --git a/update-main.go b/update-main.go index 0ce0233b..c3ef31e5 100644 --- a/update-main.go +++ b/update-main.go @@ -61,29 +61,29 @@ func mainUpdate(ctx *cli.Context) { cli.ShowCommandHelpAndExit(ctx, "update", 1) // last argument is exit code } clnt, err := url2Client(mcUpdateURL) - fatalIf(err.Trace(), "Unable to initalize update URL") + fatalIf(err.Trace(mcUpdateURL), "Unable to initalize update URL.") data, _, err := clnt.GetObject(0, 0) - fatalIf(err.Trace(), "Unable to read update URL") + fatalIf(err.Trace(mcUpdateURL), "Unable to read from update URL ‘"+mcUpdateURL+"’.") - current, goerr := time.Parse(time.RFC3339Nano, Version) - fatalIf(probe.NewError(goerr), "Unable to parse Version as time") + current, e := time.Parse(time.RFC3339Nano, Version) + fatalIf(probe.NewError(e), "Unable to parse Version string as time.") if current.IsZero() { - console.Infoln(`Version is empty, must be a custom build cannot update. Please download releases from -https://dl.minio.io:9000 for continuous updates`) + console.Infoln("Updates not supported for custom build. Version field is empty. Please download official releases from https://dl.minio.io:9000") return } + var updates Updates decoder := json.NewDecoder(data) - goerr = decoder.Decode(&updates) - fatalIf(probe.NewError(goerr), "Unable to decode update URL data") + e = decoder.Decode(&updates) + fatalIf(probe.NewError(e), "Unable to decode update notification.") - latest, goerr := time.Parse(http.TimeFormat, updates.BuildDate) - fatalIf(probe.NewError(goerr), "Unable to parse BuildDate") + latest, e := time.Parse(http.TimeFormat, updates.BuildDate) + fatalIf(probe.NewError(e), "Unable to parse BuildDate.") if latest.IsZero() { - console.Infoln("No update available at this time") + console.Infoln("No update available at this time.") return } @@ -96,11 +96,11 @@ https://dl.minio.io:9000 for continuous updates`) updateString = "mc cp " + mcUpdateURLParse.Scheme + "://" + mcUpdateURLParse.Host + string(mcUpdateURLParse.Separator) + updates.Platforms[runtime.GOOS] + " ./mc" } msg, err := printUpdateNotify(updateString, "new", "old") - fatalIf(probe.NewError(err), "Unable to print update notification") + fatalIf(err.Trace(updateString), "Unable to print update notification string ‘"+updateString+"’.") console.Println(msg) return } - console.Infoln("You are already running the most recent version of ‘mc’") + console.Infoln("You are already running the most recent version of ‘mc’.") return } diff --git a/url.go b/url.go index aeaaf00a..29cfa2a4 100644 --- a/url.go +++ b/url.go @@ -50,7 +50,7 @@ func getCanonicalizedURL(arg string, aliases map[string]string) (urlStr string, // Check and expand Alias urlStr, err = aliasExpand(arg, aliases) if err != nil { - return "", err.Trace() + return "", err.Trace(arg) } if _, err := client.Parse(urlStr); err != nil { // Not a valid URL. Return error @@ -64,7 +64,7 @@ func getCanonicalizedURLs(args []string, aliases map[string]string) (urls []stri for _, arg := range args { u, err := getCanonicalizedURL(arg, aliases) if err != nil { - return nil, err.Trace() + return nil, err.Trace(arg) } urls = append(urls, u) } @@ -81,7 +81,7 @@ func args2URLs(args []string) ([]string, *probe.Error) { // Convert arguments to URLs: expand alias, fix format... URLs, err := getCanonicalizedURLs(args, config.Aliases) if err != nil { - return nil, err.Trace() + return nil, err.Trace(args...) } return URLs, nil } diff --git a/verify-runtime.go b/verify-runtime.go index ea67643a..74fd52d5 100644 --- a/verify-runtime.go +++ b/verify-runtime.go @@ -17,6 +17,7 @@ package main import ( + "errors" "fmt" "regexp" "runtime" @@ -24,6 +25,7 @@ import ( "strings" "github.com/minio/mc/pkg/console" + "github.com/minio/minio/pkg/probe" ) var minGolangVersion = "1.5" @@ -74,10 +76,8 @@ func (v1 version) String() string { } func (v1 version) Version() int { - ver, err := strconv.Atoi(v1.String()) - if err != nil { - console.Fatalf("Unable to parse version string. %s\n", err) - } + ver, e := strconv.Atoi(v1.String()) + fatalIf(probe.NewError(e), "Unable to parse version string.") return ver } @@ -92,7 +92,8 @@ func checkGolangRuntimeVersion() { v1 := newVersion(getNormalizedGolangVersion()) v2 := newVersion(minGolangVersion) if v1.LessThan(v2) { - console.Errorf("Found Golang runtime: ‘%s’, minimum Golang runtime expected for ‘%s’ is go1.5, please compile ‘mc’ with atleast go1.5\n", v1, runtime.GOOS) + errorIf(probe.NewError(errors.New("")), + "Old Golang runtime version ‘"+v1.String()+"’ detected., ‘mc’ requires minimum go1.5 or later.") } } @@ -102,15 +103,15 @@ func verifyMCRuntime() { fatalIf(err.Trace(), "Unable to create ‘mc’ config folder.") config, err := newConfig() - fatalIf(err.Trace(), "Unable to initialize newConfig") + fatalIf(err.Trace(), "Unable to initialize newConfig.") err = writeConfig(config) - fatalIf(err.Trace(), "Unable to write newConfig") + fatalIf(err.Trace(), "Unable to write newConfig.") console.Infoln("Configuration written to [" + mustGetMcConfigPath() + "]. Please update your access credentials.") } if !isSessionDirExists() { - fatalIf(createSessionDir(), "Unable to create session dir") + fatalIf(createSessionDir(), "Unable to create session dir.") } checkGolangRuntimeVersion() } diff --git a/version-main.go b/version-main.go index 851b7c9d..6e755974 100644 --- a/version-main.go +++ b/version-main.go @@ -63,9 +63,7 @@ func mainVersion(ctxx *cli.Context) { Version Version `json:"version"` }{Version: Version{t, "RFC3339Nano"}}, ) - if err != nil { - console.Fatalln(probe.NewError(err)) - } + fatalIf(probe.NewError(err), "Unable to construct version string.") console.Println(string(tB)) return }