diff --git a/access-main.go b/access-main.go index 0d5ed9d5..58f2ad6d 100644 --- a/access-main.go +++ b/access-main.go @@ -36,15 +36,15 @@ var ( // Set access permissions. var accessCmd = cli.Command{ Name: "access", - Usage: "Set or get access permissions.", + Usage: "Manage bucket access permissions.", Action: mainAccess, Flags: []cli.Flag{accessFlagHelp}, CustomHelpTemplate: `Name: mc {{.Name}} - {{.Usage}} USAGE: - mc {{.Name}} [FLAGS] set PERMISSION TARGET [TARGET ...] - mc {{.Name}} [FLAGS] get TARGET [TARGET ...] + mc {{.Name}} [FLAGS] set PERMISSION TARGET [TARGET...] + mc {{.Name}} [FLAGS] get TARGET [TARGET...] PERMISSION: Allowed permissions are: [private, readonly, public, authorized]. @@ -70,7 +70,7 @@ EXAMPLES: `, } -// accessMessage is container for access command on bucket success and failure messages +// accessMessage is container for access command on bucket success and failure messages. type accessMessage struct { Operation string `json:"operation"` Status string `json:"status"` @@ -78,19 +78,21 @@ type accessMessage struct { Perms accessPerms `json:"permission"` } -// String colorized access message +// String colorized access message. func (s accessMessage) String() string { if s.Operation == "set" { - return console.Colorize("Access", "Set access permission ‘"+string(s.Perms)+"’ updated successfully for ‘"+s.Bucket+"’") + return console.Colorize("Access", + "Set access permission ‘"+string(s.Perms)+"’ updated successfully for ‘"+s.Bucket+"’") } if s.Operation == "get" { - return console.Colorize("Access", "Access permission for ‘"+s.Bucket+"’"+" is ‘"+string(s.Perms)+"’") + return console.Colorize("Access", + "Access permission for ‘"+s.Bucket+"’"+" is ‘"+string(s.Perms)+"’") } // nothing to print return "" } -// JSON jsonified access message +// JSON jsonified access message. func (s accessMessage) JSON() string { accessJSONBytes, err := json.Marshal(s) fatalIf(probe.NewError(err), "Unable to marshal into JSON.") @@ -98,22 +100,23 @@ func (s accessMessage) JSON() string { return string(accessJSONBytes) } +// checkAccessSyntax check for incoming syntax. func checkAccessSyntax(ctx *cli.Context) { if !ctx.Args().Present() { - cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code + cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code. } if len(ctx.Args()) < 2 { - cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code + cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code. } switch ctx.Args().First() { case "set": if len(ctx.Args().Tail()) < 2 { - cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code + cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code. } perms := accessPerms(ctx.Args().Tail().Get(0)) if !perms.isValidAccessPERM() { fatalIf(errDummy().Trace(), - "Unrecognized permission ‘"+perms.String()+"’. Allowed values are [private, public, readonly].") + "Unrecognized permission ‘"+perms.String()+"’. Allowed values are [private, public, readonly, authorized].") } for _, arg := range ctx.Args().Tail().Tail() { if strings.TrimSpace(arg) == "" { @@ -122,11 +125,12 @@ func checkAccessSyntax(ctx *cli.Context) { } case "get": if len(ctx.Args().Tail()) < 1 { - cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code + cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code. } } } +// doSetAccess do set access. func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error { clnt, err := url2Client(targetURL) if err != nil { @@ -138,6 +142,7 @@ func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error { return nil } +// doGetAccess do get access. func doGetAccess(targetURL string) (perms accessPerms, err *probe.Error) { clnt, err := url2Client(targetURL) if err != nil { @@ -166,12 +171,13 @@ func mainAccess(ctx *cli.Context) { err := doSetAccess(targetURL, perms) // Upon error, print and continue. if err != nil { - errorIf(err.Trace(targetURL, string(perms)), "Unable to set access permission ‘"+string(perms)+"’ for ‘"+targetURL+"’.") + errorIf(err.Trace(targetURL, string(perms)), + "Unable to set access permission ‘"+string(perms)+"’ for ‘"+targetURL+"’.") continue } printMsg(accessMessage{ - Operation: "set", Status: "success", + Operation: "set", Bucket: targetURL, Perms: perms, }) @@ -185,8 +191,8 @@ func mainAccess(ctx *cli.Context) { continue } printMsg(accessMessage{ - Operation: "get", Status: "success", + Operation: "get", Bucket: targetURL, Perms: perms, }) diff --git a/accounting-reader.go b/accounting-reader.go index 01917372..560f996a 100644 --- a/accounting-reader.go +++ b/accounting-reader.go @@ -23,11 +23,13 @@ import ( "time" ) +// accountingReader - implements and inherits io.ReadCloser interface for accounter. type accountingReader struct { io.ReadCloser acct *accounter } +// accounter keeps tabs of ongoing data transfer information. type accounter struct { current int64 @@ -40,7 +42,7 @@ type accounter struct { isFinished chan struct{} } -// Instantiate a new accounter +// Instantiate a new accounter. func newAccounter(total int64) *accounter { acct := &accounter{ Total: total, @@ -54,6 +56,7 @@ func newAccounter(total int64) *accounter { return acct } +// write calculate the final speed. func (a *accounter) write(current int64) float64 { fromStart := time.Now().Sub(a.startTime) currentFromStart := current - a.startValue @@ -64,6 +67,7 @@ func (a *accounter) write(current int64) float64 { return 0.0 } +// writer update new accounting data for a specified refreshRate. func (a *accounter) writer() { a.Update() for { @@ -76,12 +80,14 @@ func (a *accounter) writer() { } } +// accountStat cantainer for current stats captured. type accountStat struct { Total int64 Transferred int64 Speed float64 } +// Stat provides current stats captured. func (a *accounter) Stat() accountStat { var acntStat accountStat a.finishOnce.Do(func() { @@ -93,6 +99,7 @@ func (a *accounter) Stat() accountStat { return acntStat } +// Update update with new values loaded atomically. func (a *accounter) Update() { c := atomic.LoadInt64(&a.current) if c != a.currentValue { @@ -101,14 +108,17 @@ func (a *accounter) Update() { } } +// Add add to current values atomically. func (a *accounter) Add(n int64) int64 { return atomic.AddInt64(&a.current, n) } +// Instantiate a new proxy reader for accounter. func (a *accounter) NewProxyReader(r io.ReadCloser) *accountingReader { return &accountingReader{r, a} } +// Read implement Reader which internally updates current value. func (a *accountingReader) Read(p []byte) (n int, err error) { n, err = a.ReadCloser.Read(p) if err != nil { diff --git a/aliasconfig.go b/aliasconfig.go index 869d7409..148e4d8b 100644 --- a/aliasconfig.go +++ b/aliasconfig.go @@ -28,7 +28,7 @@ func isValidAliasName(aliasName string) bool { return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(aliasName) } -// normalizeAliasedURL - remove any preceding separators +// normalizeAliasedURL - remove any preceding separators. func normalizeAliasedURL(aliasedURL string) string { aliasedURL = strings.TrimPrefix(aliasedURL, string(os.PathSeparator)) return aliasedURL diff --git a/cat-main.go b/cat-main.go index e31b33bf..1470985a 100644 --- a/cat-main.go +++ b/cat-main.go @@ -128,7 +128,7 @@ func mainCat(ctx *cli.Context) { stdinMode = true } - // handle std input data + // handle std input data. if stdinMode { fatalIf(catOut(os.Stdin).Trace(), "Unable to read from standard input.") return @@ -146,7 +146,7 @@ func mainCat(ctx *cli.Context) { } } - // Convert arguments to URLs: expand alias, fix format... + // Convert arguments to URLs: expand alias, fix format. URLs, err := args2URLs(args) fatalIf(err.Trace(args...), "Unable to parse arguments.") diff --git a/config-alias-main.go b/config-alias-main.go index 101771e8..98ed1bc5 100644 --- a/config-alias-main.go +++ b/config-alias-main.go @@ -56,18 +56,18 @@ FLAGS: {{end}} EXAMPLES: 1. Add aliases for Amazon S3. - $ mc config {{.Name}} add mcloud https://s3.amazonaws.com/miniocloud + $ mc config {{.Name}} add mcloud https://miniocloud.s3.amazonaws.com $ mc ls mcloud 2. Add aliases for Google Cloud Storage. - $ mc config {{.Name}} add gcscloud https://storage.googleapis.com/miniocloud + $ mc config {{.Name}} add gcscloud https://miniocloud.storage.googleapis.com $ mc ls gcscloud 3. List all aliased URLs. $ mc config {{.Name}} list 4. Remove an alias - $ mc config {{.Name}} remove zek + $ mc config {{.Name}} remove mcloud `, } diff --git a/config-host-main.go b/config-host-main.go index 7a857c85..40108a9d 100644 --- a/config-host-main.go +++ b/config-host-main.go @@ -45,7 +45,7 @@ EXAMPLES: $ mc config {{.Name}} add s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 $ set -o history - 2. Add host configuration for a URL, using s3 api v2. For security reasons turn off bash history + 2. Add host configuration for a URL, using signature V2. For security reasons turn off bash history $ set +o history $ mc config {{.Name}} add storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2 $ set -o history diff --git a/config.go b/config.go index 0dbba29b..9dc24bbe 100644 --- a/config.go +++ b/config.go @@ -240,6 +240,7 @@ func newConfig() (config quick.Config, err *probe.Error) { return config, nil } +// fixConfigV6 - fix all the unnecessary glob URLs present in existing config version 6. func fixConfigV6() { if !isMcConfigExists() { return @@ -267,6 +268,11 @@ func fixConfigV6() { newConfig.Hosts["s3.amazonaws.com"] = hostCfg continue } + if strings.Contains(host, "*amazonaws.com") || strings.Contains(host, "*.amazonaws.com") { + console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com") + newConfig.Hosts["s3.amazonaws.com"] = hostCfg + continue + } if strings.Contains(host, "*storage.googleapis.com") { console.Infoln("Found glob url, replacing " + host + " with storage.googleapis.com") newConfig.Hosts["storage.googleapis.com"] = hostCfg diff --git a/hostconfig.go b/hostconfig.go index d9ab90b2..f1a61699 100644 --- a/hostconfig.go +++ b/hostconfig.go @@ -23,20 +23,21 @@ import ( "github.com/minio/minio-xl/pkg/probe" ) +// hostConfig configuration of a host. type hostConfig struct { AccessKeyID string `json:"accessKeyId"` SecretAccessKey string `json:"secretAccessKey"` API string `json:"api"` } -// getHostConfig retrieves host specific configuration such as access keys, certs. +// getHostConfig retrieves host specific configuration such as access keys, signature type. func getHostConfig(URL string) (hostConfig, *probe.Error) { config, err := getMcConfig() if err != nil { return hostConfig{}, err.Trace() } url := client.NewURL(URL) - // No host matching or keys needed for filesystem requests + // No host matching or keys needed for filesystem requests. if url.Type == client.Filesystem { hostCfg := hostConfig{ AccessKeyID: "", @@ -45,13 +46,16 @@ func getHostConfig(URL string) (hostConfig, *probe.Error) { } return hostCfg, nil } + // if host is exact return quickly. if _, ok := config.Hosts[url.Host]; ok { return config.Hosts[url.Host], nil } + // if host matches a suffix return. for savedURL, hostCfg := range config.Hosts { if strings.HasSuffix(url.Host, savedURL) { return hostCfg, nil } } + // return error if cannot be matched. return hostConfig{}, errNoMatchingHost(URL).Trace() } diff --git a/main.go b/main.go index 8c9985bd..12bcfac8 100644 --- a/main.go +++ b/main.go @@ -49,7 +49,7 @@ VERSION: {{$value}} {{end}}` -// Default handler for missing commands. +// Function invoked when invalid command is passed. func commandNotFound(ctx *cli.Context, command string) { msg := fmt.Sprintf("‘%s’ is not a mc command. See ‘mc help’.", command) closestCommands := findClosestCommands(command) @@ -64,7 +64,7 @@ func commandNotFound(ctx *cli.Context, command string) { // Check for sane config environment early on and gracefully report. func checkConfig() { - // Ensures config file is sane + // Ensures config file is sane. _, err := getMcConfig() fatalIf(err.Trace(), "Unable to access configuration file.") } @@ -81,7 +81,7 @@ func migrate() { } // Get os/arch/platform specific information. -// Returns a map of current os/arch/platform/memstats +// Returns a map of current os/arch/platform/memstats. func getSystemData() map[string]string { host, e := os.Hostname() fatalIf(probe.NewError(e), "Unable to determine the hostname.") @@ -117,17 +117,19 @@ func registerBefore(ctx *cli.Context) error { console.SetColorOff() } - // Verify golang runtime + // Verify golang runtime. verifyMCRuntime() // Migrate any old version of config / state files to newer format. migrate() - // Checkconfig if it can be read + // Checkconfig if it can be read. checkConfig() + return nil } +// findClosestCommands to match a given string with commands trie tree. func findClosestCommands(command string) []string { var closestCommands []string for _, value := range commandsTree.PrefixMatch(command) { diff --git a/notifier.go b/notifier.go index b6eb9cd9..b9020629 100644 --- a/notifier.go +++ b/notifier.go @@ -27,28 +27,29 @@ import ( "github.com/olekukonko/ts" ) -// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier +// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier. func colorizeUpdateMessage(updateString string) (string, *probe.Error) { // initialize coloring cyan := color.New(color.FgCyan, color.Bold).SprintFunc() yellow := color.New(color.FgYellow, color.Bold).SprintfFunc() // calculate length without color coding, due to ANSI color characters padded to actual - // string the final length is wrong than the original string length + // string the final length is wrong than the original string length. line1Str := fmt.Sprintf(" Update available: ") line2Str := fmt.Sprintf(" Run \"%s\" to update. ", updateString) line1Length := len(line1Str) line2Length := len(line2Str) - // populate lines with color coding + // populate lines with color coding. line1InColor := line1Str line2InColor := fmt.Sprintf(" Run \"%s\" to update. ", cyan(updateString)) - // calculate the rectangular box size + // calculate the rectangular box size. maxContentWidth := int(math.Max(float64(line1Length), float64(line2Length))) line1Rest := maxContentWidth - line1Length line2Rest := maxContentWidth - line2Length + // Fetch terminal size to calculate optimal box size. terminal, err := ts.GetSize() if err != nil { return "", probe.NewError(err) @@ -59,28 +60,28 @@ func colorizeUpdateMessage(updateString string) (string, *probe.Error) { case len(line2Str) > terminal.Col(): message = "\n" + line1InColor + "\n" + line2InColor + "\n" default: - // on windows terminal turn off unicode characters + // on windows terminal turn off unicode characters. var top, bottom, sideBar string if runtime.GOOS == "windows" { top = yellow("*" + strings.Repeat("*", maxContentWidth) + "*") bottom = yellow("*" + strings.Repeat("*", maxContentWidth) + "*") sideBar = yellow("|") } else { - // color the rectangular box, use unicode characters here + // color the rectangular box, use unicode characters here. top = yellow("┏" + strings.Repeat("━", maxContentWidth) + "┓") bottom = yellow("┗" + strings.Repeat("━", maxContentWidth) + "┛") sideBar = yellow("┃") } - // fill spaces to the rest of the area + // fill spaces to the rest of the area. spacePaddingLine1 := strings.Repeat(" ", line1Rest) spacePaddingLine2 := strings.Repeat(" ", line2Rest) - // construct the final message + // construct the final message. message = "\n" + top + "\n" + sideBar + line1InColor + spacePaddingLine1 + sideBar + "\n" + sideBar + line2InColor + spacePaddingLine2 + sideBar + "\n" + bottom + "\n" } - // finally print the message + // return the final message return message, nil } diff --git a/progress-bar.go b/progress-bar.go index 7198b80f..d074eb21 100644 --- a/progress-bar.go +++ b/progress-bar.go @@ -17,23 +17,21 @@ package main import ( - "fmt" "io" "runtime" "strings" "time" - "github.com/dustin/go-humanize" "github.com/fatih/color" - "github.com/minio/minio-xl/pkg/probe" "github.com/minio/pb" - "github.com/olekukonko/ts" "github.com/minio/mc/pkg/console" ) +// pbBar type of operation. type pbBar int +// collection of different progress bar operations. const ( pbBarProgress pbBar = iota pbBarFinish @@ -42,57 +40,69 @@ const ( pbBarSetCaption ) +// proxyReader progress bar proxy reader for barSend inherits io.ReadCloser. type proxyReader struct { io.ReadCloser bar *barSend } +// Read proxy Read sends progress for each Read operation. func (r *proxyReader) Read(p []byte) (n int, err error) { n, err = r.ReadCloser.Read(p) r.bar.Progress(int64(n)) return } +// Close proxy Close closes the internal ReadCloser. func (r *proxyReader) Close() (err error) { return r.ReadCloser.Close() } +// barMsg progress bar message for a given operation. type barMsg struct { Op pbBar Arg interface{} } +// barSend implements various methods for progress bar operation. type barSend struct { opCh chan<- barMsg finishCh <-chan bool } +// Instantiate a new progress bar proxy reader. func (b *barSend) NewProxyReader(r io.ReadCloser) *proxyReader { return &proxyReader{r, b} } +// Progress send current progress message. func (b barSend) Progress(progress int64) { b.opCh <- barMsg{Op: pbBarProgress, Arg: progress} } +// ErrorPut send message for error in put operation. func (b barSend) ErrorPut(size int64) { b.opCh <- barMsg{Op: pbBarPutError, Arg: size} } +// ErrorGet send message for error in get operation. func (b barSend) ErrorGet(size int64) { b.opCh <- barMsg{Op: pbBarGetError, Arg: size} } +// SetCaption set an additional prefix/caption for an active progress bar. func (b *barSend) SetCaption(c string) { b.opCh <- barMsg{Op: pbBarSetCaption, Arg: c} } +// Finish finishes the progress bar and closes the message channel. func (b barSend) Finish() { defer close(b.opCh) b.opCh <- barMsg{Op: pbBarFinish} <-b.finishCh } +// cursorAnimate - returns a animated rune through read channel for every read. func cursorAnimate() <-chan rune { cursorCh := make(chan rune) var cursors string @@ -121,6 +131,7 @@ func cursorAnimate() <-chan rune { return cursorCh } +// fixateBarCaption - fancify bar caption based on the terminal width. func fixateBarCaption(caption string, width int) string { switch { case len(caption) > width: @@ -135,11 +146,12 @@ func fixateBarCaption(caption string, width int) string { return caption } +// getFixedWidth - get a fixed width based for a given percentage. func getFixedWidth(width, percent int) int { return width * percent / 100 } -// newProgressBar - instantiate a pbBar. +// newProgressBar - instantiate a progress bar. func newProgressBar(total int64) *barSend { // Progress bar speific theme customization. console.SetColor("Bar", color.New(color.FgGreen, color.Bold)) @@ -147,16 +159,28 @@ func newProgressBar(total int64) *barSend { cmdCh := make(chan barMsg) finishCh := make(chan bool) go func(total int64, cmdCh <-chan barMsg, finishCh chan<- bool) { - var started bool + var started bool // has the progress bar started? default is false. var totalBytesRead int64 // total amounts of bytes read + + // get the new original progress bar. bar := pb.New64(total) bar.SetUnits(pb.U_BYTES) + + // refresh rate for progress bar is set to 125 milliseconds. bar.SetRefreshRate(time.Millisecond * 125) + + // Do not print a newline by default handled, it is handled manually. bar.NotPrint = true + + // Show current speed is true. bar.ShowSpeed = true + + // Custom callback with colorized bar. bar.Callback = func(s string) { console.Print(console.Colorize("Bar", "\r"+s)) } + + // Use different unicodes for Linux, OS X and Windows. switch runtime.GOOS { case "linux": bar.Format("┃▓█░┃") @@ -166,11 +190,15 @@ func newProgressBar(total int64) *barSend { default: bar.Format("[=> ]") } + + // Look for incoming progress bar messages. for msg := range cmdCh { switch msg.Op { case pbBarSetCaption: + // Sets a new caption prefixed along with progress bar. bar.Prefix(fixateBarCaption(msg.Arg.(string), getFixedWidth(bar.GetWidth(), 18))) case pbBarProgress: + // Initializes the progerss bar, if already started bumps up the totalBytes. if bar.Total > 0 && !started { started = true bar.Start() @@ -180,17 +208,21 @@ func newProgressBar(total int64) *barSend { bar.Add64(msg.Arg.(int64)) } case pbBarPutError: + // Negates any put error of size from totalBytes. if totalBytesRead > msg.Arg.(int64) { bar.Set64(totalBytesRead - msg.Arg.(int64)) } case pbBarGetError: + // Retains any size transferred but failed. if msg.Arg.(int64) > 0 { bar.Add64(msg.Arg.(int64)) } case pbBarFinish: + // Progress finishes here. if started { bar.Finish() } + // All done send true. finishCh <- true return } @@ -198,51 +230,3 @@ func newProgressBar(total int64) *barSend { }(total, cmdCh, finishCh) return &barSend{cmdCh, finishCh} } - -/******************************** Scan Bar ************************************/ -// fixateScanBar truncates long text to fit within the terminal size. -func fixateScanBar(text string, width int) string { - if len([]rune(text)) > width { - // Trim text to fit within the screen - trimSize := len([]rune(text)) - width + 3 //"..." - if trimSize < len([]rune(text)) { - text = "..." + text[trimSize:] - } - } - return text -} - -// Progress bar function report objects being scaned. -type scanBarFunc func(string) - -// scanBarFactory returns a progress bar function to report URL scanning. -func scanBarFactory() scanBarFunc { - prevLineSize := 0 - prevSource := "" - fileCount := 0 - termSize, err := ts.GetSize() - if err != nil { - fatalIf(probe.NewError(err), "Unable to get terminal size. Please use --quiet option.") - } - termWidth := termSize.Col() - cursorCh := cursorAnimate() - - return func(source string) { - scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), string(<-cursorCh)) - cmnPrefix := commonPrefix(source, prevSource) - eraseLen := prevLineSize - len([]rune(scanPrefix+cmnPrefix)) - if eraseLen < 1 { - eraseLen = 0 - } - if prevLineSize != 0 { // erase previous line - console.PrintC("\r" + scanPrefix + cmnPrefix + strings.Repeat(" ", eraseLen)) - } - - source = fixateScanBar(source, termWidth-len([]rune(scanPrefix))-1) - barText := scanPrefix + source - console.PrintC("\r" + barText) - prevSource = source - prevLineSize = len([]rune(barText)) - fileCount++ - } -} diff --git a/scan-bar.go b/scan-bar.go new file mode 100644 index 00000000..2818fe08 --- /dev/null +++ b/scan-bar.go @@ -0,0 +1,75 @@ +/* + * Minio Client (C) 2014, 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "fmt" + "strings" + + "github.com/dustin/go-humanize" + "github.com/minio/mc/pkg/console" + "github.com/minio/minio-xl/pkg/probe" + "github.com/olekukonko/ts" +) + +/******************************** Scan Bar ************************************/ +// fixateScanBar truncates long text to fit within the terminal size. +func fixateScanBar(text string, width int) string { + if len([]rune(text)) > width { + // Trim text to fit within the screen + trimSize := len([]rune(text)) - width + 3 //"..." + if trimSize < len([]rune(text)) { + text = "..." + text[trimSize:] + } + } + return text +} + +// Progress bar function report objects being scaned. +type scanBarFunc func(string) + +// scanBarFactory returns a progress bar function to report URL scanning. +func scanBarFactory() scanBarFunc { + prevLineSize := 0 + prevSource := "" + fileCount := 0 + termSize, err := ts.GetSize() + if err != nil { + fatalIf(probe.NewError(err), "Unable to get terminal size. Please use --quiet option.") + } + termWidth := termSize.Col() + cursorCh := cursorAnimate() + + return func(source string) { + scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), string(<-cursorCh)) + cmnPrefix := commonPrefix(source, prevSource) + eraseLen := prevLineSize - len([]rune(scanPrefix+cmnPrefix)) + if eraseLen < 1 { + eraseLen = 0 + } + if prevLineSize != 0 { // erase previous line + console.PrintC("\r" + scanPrefix + cmnPrefix + strings.Repeat(" ", eraseLen)) + } + + source = fixateScanBar(source, termWidth-len([]rune(scanPrefix))-1) + barText := scanPrefix + source + console.PrintC("\r" + barText) + prevSource = source + prevLineSize = len([]rune(barText)) + fileCount++ + } +} diff --git a/session-legacy.go b/session-legacy.go index 8e4a828d..9e88f5be 100644 --- a/session-legacy.go +++ b/session-legacy.go @@ -31,6 +31,7 @@ import ( "github.com/minio/minio-xl/pkg/quick" ) +// sessionV1 legacy session version definition. type sessionV1 struct { Version string `json:"version"` Started time.Time `json:"started"` @@ -42,6 +43,7 @@ type sessionV1 struct { Lock *sync.Mutex `json:"-"` } +// Stringify session data. func (s sessionV1) String() string { message := console.Colorize("Time", fmt.Sprintf("[%s] ", s.Started.Local().Format(printDate))) message = message + console.Colorize("SessionID", fmt.Sprintf("%s", s.SessionID)) @@ -49,7 +51,7 @@ func (s sessionV1) String() string { return message } -// loadSession - reads session file if exists and re-initiates internal variables +// loadSessionV1 - reads session file if exists and re-initiates internal variables. func loadSessionV1(sid string) (*sessionV1, *probe.Error) { if !isSessionDirExists() { return nil, probe.NewError(errors.New("Session folder does not exist.")) @@ -62,7 +64,7 @@ func loadSessionV1(sid string) (*sessionV1, *probe.Error) { s := new(sessionV1) s.Version = "1.0.0" - // map of command and files copied + // map of command and files copied. s.URLs = nil s.Lock = new(sync.Mutex) s.Files = make(map[string]bool) @@ -77,6 +79,7 @@ func loadSessionV1(sid string) (*sessionV1, *probe.Error) { return qs.Data().(*sessionV1), nil } +// getSessionIDsV1 get session ids version 1. func getSessionIDsV1() (sids []string) { sessionDir, err := getSessionDir() fatalIf(err.Trace(), "Unable to determine session folder.") @@ -99,6 +102,7 @@ func getSessionIDsV1() (sids []string) { return sids } +// getSessionFileV1 get version 1 session file. func getSessionFileV1(sid string) (string, *probe.Error) { sessionDir, err := getSessionDir() if err != nil { @@ -125,7 +129,7 @@ func migrateSessionV1ToV2() { } } -// sessionV2Header +// sessionV2Header new session version 2 header. type sessionV2Header struct { Version string `json:"version"` When time.Time `json:"time"` @@ -137,7 +141,7 @@ type sessionV2Header struct { TotalObjects int `json:"total-objects"` } -// loadSession - reads session file if exists and re-initiates internal variables +// loadSessionV2 - reads session file if exists and re-initiates internal variables. func loadSessionV2(sid string) (*sessionV2Header, *probe.Error) { if !isSessionDirExists() { return nil, errInvalidArgument().Trace() @@ -150,7 +154,7 @@ func loadSessionV2(sid string) (*sessionV2Header, *probe.Error) { return nil, probe.NewError(err) } sessionHeader := &sessionV2Header{} - // V2 is actually v1.1. We later moved to a serial single digit version. + // V2 is actually v1.1. We have moved to a serial single digit version. sessionHeader.Version = "1.1.0" qs, err := quick.New(sessionHeader) if err != nil { diff --git a/session-main.go b/session-main.go index a8166541..f4f366e3 100644 --- a/session-main.go +++ b/session-main.go @@ -70,13 +70,14 @@ EXAMPLES: `, } -// bySessionWhen is a type for sorting session metadata by time +// bySessionWhen is a type for sorting session metadata by time. type bySessionWhen []*sessionV3 func (b bySessionWhen) Len() int { return len(b) } func (b bySessionWhen) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b bySessionWhen) Less(i, j int) bool { return b[i].Header.When.Before(b[j].Header.When) } +// listSessions list all current sessions. func listSessions() *probe.Error { var bySessions []*sessionV3 for _, sid := range getSessionIDs() { @@ -86,7 +87,7 @@ func listSessions() *probe.Error { } bySessions = append(bySessions, s) } - // sort sessions based on time + // sort sessions based on time. sort.Sort(bySessionWhen(bySessions)) for _, session := range bySessions { printMsg(session) @@ -95,18 +96,18 @@ func listSessions() *probe.Error { return nil } -// clearSessionMessage container for clearing session messages +// clearSessionMessage container for clearing session messages. type clearSessionMessage struct { Status string `json:"success"` SessionID string `json:"sessionId"` } -// String colorized clear session message +// String colorized clear session message. func (c clearSessionMessage) String() string { return console.Colorize("ClearSession", "Session ‘"+c.SessionID+"’ cleared successfully.") } -// JSON jsonified clear session message +// JSON jsonified clear session message. func (c clearSessionMessage) JSON() string { clearSessionJSONBytes, err := json.Marshal(c) fatalIf(probe.NewError(err), "Unable to marshal into JSON.") @@ -114,6 +115,7 @@ func (c clearSessionMessage) JSON() string { return string(clearSessionJSONBytes) } +// clearSession clear sessions. func clearSession(sid string) { if sid == "all" { for _, sid := range getSessionIDs() { @@ -127,7 +129,7 @@ func clearSession(sid string) { return } - if !isSession(sid) { + if !isSessionExists(sid) { fatalIf(errDummy().Trace(), "Session ‘"+sid+"’ not found.") } @@ -186,28 +188,25 @@ func mainSession(ctx *cli.Context) { } switch strings.TrimSpace(ctx.Args().First()) { - // list resumable sessions + // list all resumable sessions. case "list": fatalIf(listSessions().Trace(), "Unable to list sessions.") case "resume": sid := strings.TrimSpace(ctx.Args().Tail().First()) - if !isSession(sid) { + if !isSessionExists(sid) { fatalIf(errDummy().Trace(), "Session ‘"+sid+"’ not found.") } - s, err := loadSessionV3(sid) fatalIf(err.Trace(sid), "Unable to load session.") - - // extra check for testing purposes + // extra check for testing purposes. if s == nil { return } - savedCwd, e := os.Getwd() fatalIf(probe.NewError(e), "Unable to determine current working folder.") if s.Header.RootPath != "" { - // chdir to RootPath + // change folder to RootPath. e = os.Chdir(s.Header.RootPath) fatalIf(probe.NewError(e), "Unable to change working folder to root path while resuming session.") } @@ -218,11 +217,11 @@ func mainSession(ctx *cli.Context) { err = s.Delete() fatalIf(err.Trace(), "Unable to clear session files properly.") - // chdir back to saved path + // change folder back to saved path. e = os.Chdir(savedCwd) fatalIf(probe.NewError(e), "Unable to change working folder to saved path ‘"+savedCwd+"’.") - // purge a requested pending session, if "all" purge everything + // purge a requested pending session, if "all" purge everything. case "clear": clearSession(strings.TrimSpace(ctx.Args().Tail().First())) } diff --git a/session.go b/session.go index 63b6fa26..4eec8ce7 100644 --- a/session.go +++ b/session.go @@ -24,14 +24,16 @@ import ( "github.com/minio/minio-xl/pkg/probe" ) +// migrateSession migrates all previous migration to latest. func migrateSession() { - // Migrate session V1 to V2 + // Migrate session V1 to V2. migrateSessionV1ToV2() - // Migrate session V2 to V3 + // Migrate session V2 to V3. migrateSessionV2ToV3() } +// createSessionDir - create session directory. func createSessionDir() *probe.Error { sessionDir, err := getSessionDir() if err != nil { @@ -44,6 +46,7 @@ func createSessionDir() *probe.Error { return nil } +// getSessionDir - get session directory. func getSessionDir() (string, *probe.Error) { configDir, err := getMcConfigDir() if err != nil { @@ -54,6 +57,7 @@ func getSessionDir() (string, *probe.Error) { return sessionDir, nil } +// isSessionDirExists - verify if session directory exists. func isSessionDirExists() bool { sessionDir, err := getSessionDir() fatalIf(err.Trace(), "Unable to determine session folder.") @@ -64,6 +68,7 @@ func isSessionDirExists() bool { return true } +// getSessionFile - get current session file. func getSessionFile(sid string) (string, *probe.Error) { sessionDir, err := getSessionDir() if err != nil { @@ -74,7 +79,8 @@ func getSessionFile(sid string) (string, *probe.Error) { return sessionFile, nil } -func isSession(sid string) bool { +// isSessionExists verifies if given session exists. +func isSessionExists(sid string) bool { sessionFile, err := getSessionFile(sid) fatalIf(err.Trace(sid), "Unable to determine session filename for ‘"+sid+"’.") @@ -85,6 +91,7 @@ func isSession(sid string) bool { return true // Session exists. } +// getSessionDataFile - get session data file for a given session. func getSessionDataFile(sid string) (string, *probe.Error) { sessionDir, err := getSessionDir() if err != nil { @@ -95,6 +102,7 @@ func getSessionDataFile(sid string) (string, *probe.Error) { return sessionDataFile, nil } +// getSessionIDs - get all active sessions. func getSessionIDs() (sids []string) { sessionDir, err := getSessionDir() fatalIf(err.Trace(), "Unable to access session folder.") diff --git a/share-db-v1.go b/share-db-v1.go index 7df1fd66..e365bd7e 100644 --- a/share-db-v1.go +++ b/share-db-v1.go @@ -25,6 +25,7 @@ import ( "github.com/minio/minio-xl/pkg/quick" ) +// shareEntryV1 - container for each download/upload entries. type shareEntryV1 struct { URL string `json:"share"` // Object URL. Date time.Time `json:"date"` diff --git a/share-download-main.go b/share-download-main.go index 8b1bbf02..51be9738 100644 --- a/share-download-main.go +++ b/share-download-main.go @@ -97,7 +97,7 @@ func checkShareDownloadSyntax(ctx *cli.Context) { } -// doShareURL share files from target +// doShareURL share files from target. func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration) *probe.Error { clnt, err := url2Client(targetURL) if err != nil { diff --git a/share-main.go b/share-main.go index 5eb654ec..1f19830d 100644 --- a/share-main.go +++ b/share-main.go @@ -58,7 +58,7 @@ COMMANDS: `, } -// migrateShare migrate to newest version sequentially +// migrateShare migrate to newest version sequentially. func migrateShare() { if !isShareDirExists() { return @@ -74,7 +74,7 @@ func migrateShare() { } } -// mainShare - main handler for mc share command +// mainShare - main handler for mc share command. func mainShare(ctx *cli.Context) { if ctx.Args().First() != "" { // command help. cli.ShowCommandHelp(ctx, ctx.Args().First()) @@ -82,5 +82,5 @@ func mainShare(ctx *cli.Context) { cli.ShowAppHelp(ctx) } - // sub-commands like "upload" and "download" have their own main. + // Sub-commands like "upload" and "download" have their own main. } diff --git a/share.go b/share.go index f421837e..d69e4ded 100644 --- a/share.go +++ b/share.go @@ -32,7 +32,7 @@ import ( ) const ( - // Default expiry is 7 days (168h) + // Default expiry is 7 days (168h). shareDefaultExpiry = time.Duration(604800) * time.Second ) @@ -79,9 +79,9 @@ func (s shareMesssage) JSON() string { shareMessageBytes, e := json.Marshal(s) fatalIf(probe.NewError(e), "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. */ + // 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) shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003c"), []byte("<"), -1) shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003e"), []byte(">"), -1) @@ -111,7 +111,7 @@ func getShareDir() (string, *probe.Error) { return sharedURLsDataDir, nil } -// Get share dir name or die. (NOTE: This ‘Die’ approach is only OK for mc like tools.) +// Get share dir name or die. (NOTE: This ‘Die’ approach is only OK for mc like tools.). func mustGetShareDir() string { shareDir, err := getShareDir() fatalIf(err.Trace(), "Unable to determine share folder.") @@ -144,7 +144,7 @@ func getShareDownloadsFile() string { return filepath.Join(mustGetShareDir(), "downloads.json") } -// Check if share uploads file exists? +// Check if share uploads file exists?. func isShareUploadsExists() bool { if _, e := os.Stat(getShareUploadsFile()); e != nil { return false @@ -152,7 +152,7 @@ func isShareUploadsExists() bool { return true } -// Check if share downloads file exists? +// Check if share downloads file exists?. func isShareDownloadsExists() bool { if _, e := os.Stat(getShareDownloadsFile()); e != nil { return false @@ -174,19 +174,22 @@ func initShareDownloadsFile() *probe.Error { func initShareConfig() { // Share directory. if !isShareDirExists() { - fatalIf(createShareDir().Trace(), "Failed to create share ‘"+mustGetShareDir()+"’ folder.") + fatalIf(createShareDir().Trace(), + "Failed to create share ‘"+mustGetShareDir()+"’ folder.") console.Infof("Successfully created ‘%s’.\n", mustGetShareDir()) } // Uploads share file. if !isShareUploadsExists() { - fatalIf(initShareUploadsFile().Trace(), "Failed to initialize share uploads ‘"+getShareUploadsFile()+"’ file.") + fatalIf(initShareUploadsFile().Trace(), + "Failed to initialize share uploads ‘"+getShareUploadsFile()+"’ file.") console.Infof("Initialized share uploads ‘%s’ file.\n", getShareUploadsFile()) } // Downloads share file. if !isShareDownloadsExists() { - fatalIf(initShareDownloadsFile().Trace(), "Failed to initialize share downloads ‘"+getShareDownloadsFile()+"’ file.") + fatalIf(initShareDownloadsFile().Trace(), + "Failed to initialize share downloads ‘"+getShareDownloadsFile()+"’ file.") console.Infof("Initialized share downloads ‘%s’ file.\n", getShareDownloadsFile()) } } diff --git a/signals.go b/signals.go index 960683d9..1a0f531f 100644 --- a/signals.go +++ b/signals.go @@ -16,12 +16,12 @@ package main -// signalTrap traps the registered signals and notifies the caller. import ( "os" "os/signal" ) +// signalTrap traps the registered signals and notifies the caller. func signalTrap(sig ...os.Signal) <-chan bool { // channel to notify the caller. trapCh := make(chan bool, 1) @@ -35,10 +35,10 @@ func signalTrap(sig ...os.Signal) <-chan bool { // receive notifications of the specified signals. signal.Notify(sigCh, sig...) - // Wait for the signal + // Wait for the signal. <-sigCh - // Notify the caller + // Notify the caller. trapCh <- true }(trapCh) diff --git a/time.go b/time.go index 5faf6fed..b99af6e2 100644 --- a/time.go +++ b/time.go @@ -22,6 +22,7 @@ import ( "time" ) +// humanizedTime container to capture humanized time. type humanizedTime struct { Days int64 `json:"days,omitempty"` Hours int64 `json:"hours,omitempty"` @@ -43,6 +44,7 @@ func (r humanizedTime) String() string { return fmt.Sprintf("%d days %d hours %d minutes %d seconds", r.Days, r.Hours, r.Minutes, r.Seconds) } +// timeDurationToHumanizedTime convert golang time.Duration to a custom more readable humanizedTime. func timeDurationToHumanizedTime(duration time.Duration) humanizedTime { r := humanizedTime{} if duration.Seconds() < 60.0 { diff --git a/trie.go b/trie.go index fe4204df..7a37bf40 100644 --- a/trie.go +++ b/trie.go @@ -14,17 +14,18 @@ * limitations under the License. */ +// This file implements a simple trie tree to be used for 'mc' cli commands. package main -// This package borrows idea from - https://godoc.org/golang.org/x/text/internal/triegen +// This package borrows idea from - https://godoc.org/golang.org/x/text/internal/triegen. -// Trie trie container +// Trie is a trie container. type Trie struct { root *trieNode size int } -// newTrie get new trie +// newTrie create a new trie. func newTrie() *Trie { return &Trie{ root: newTrieNode(), @@ -32,13 +33,14 @@ func newTrie() *Trie { } } -// trieNode trie tree node container carries value and children +// trieNode trie tree node container carries value and children. type trieNode struct { exists bool value interface{} - child map[rune]*trieNode // runes as child + child map[rune]*trieNode // runes as child. } +// newTrieNode create a new trie node. func newTrieNode() *trieNode { return &trieNode{ exists: false, @@ -47,7 +49,7 @@ func newTrieNode() *trieNode { } } -// Insert insert a key +// Insert insert a key. func (t *Trie) Insert(key string) { curNode := t.root for _, v := range key { @@ -58,15 +60,15 @@ func (t *Trie) Insert(key string) { } if !curNode.exists { - // increment when new rune child is added + // increment when new rune child is added. t.size++ curNode.exists = true } - // value is stored for retrieval in future + // value is stored for retrieval in future. curNode.value = key } -// PrefixMatch - prefix match +// PrefixMatch - prefix match. func (t *Trie) PrefixMatch(key string) []interface{} { node, _ := t.findNode(key) if node != nil { @@ -75,7 +77,7 @@ func (t *Trie) PrefixMatch(key string) []interface{} { return []interface{}{} } -// walk the tree +// walk the tree. func (t *Trie) walk(node *trieNode) (ret []interface{}) { if node.exists { ret = append(ret, node.value) @@ -86,7 +88,7 @@ func (t *Trie) walk(node *trieNode) (ret []interface{}) { return } -// find nodes corresponding to key +// find nodes corresponding to key. func (t *Trie) findNode(key string) (node *trieNode, index int) { curNode := t.root f := false diff --git a/update-main.go b/update-main.go index b30a0682..d1433048 100644 --- a/update-main.go +++ b/update-main.go @@ -119,14 +119,16 @@ func getReleaseUpdate(updateURL string) { fatalIf(err.Trace(updateURL), "Unable to read from update URL ‘"+updateURL+"’.") if mcVersion == "UNOFFICIAL.GOGET" { - fatalIf(errDummy().Trace(mcVersion), "Update mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#mc") + fatalIf(errDummy().Trace(mcVersion), + "Update mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#mc") } current, e := time.Parse(time.RFC3339, mcVersion) fatalIf(probe.NewError(e), "Unable to parse version string as time.") if current.IsZero() { - fatalIf(errDummy().Trace(), "Updates not supported for custom builds. Version field is empty. Please download official releases from https://minio.io/#mc") + fatalIf(errDummy().Trace(), + "Updates not supported for custom builds. Version field is empty. Please download official releases from https://minio.io/#mc") } var updates mcUpdates @@ -141,7 +143,8 @@ func getReleaseUpdate(updateURL string) { } if latest.IsZero() { - fatalIf(errDummy().Trace(), "Unable to validate any update available at this time. Please open an issue at https://github.com/minio/mc/issues") + fatalIf(errDummy().Trace(), + "Unable to validate any update available at this time. Please open an issue at https://github.com/minio/mc/issues") } updateURLParse := clnt.GetURL() diff --git a/url.go b/url.go index f961966a..32ce80d0 100644 --- a/url.go +++ b/url.go @@ -24,7 +24,7 @@ import ( "github.com/minio/minio-xl/pkg/probe" ) -// ``...`` recursiveSeparator +// ``...`` recursiveSeparator. const ( recursiveSeparator = "..." ) @@ -68,7 +68,7 @@ func args2URLs(args []string) ([]string, *probe.Error) { return URLs, nil } -// url2Client - convenience wrapper for getNewClient +// url2Client - convenience wrapper for getNewClient. func url2Client(urlStr string) (client.Client, *probe.Error) { urlConfig, err := getHostConfig(urlStr) if err != nil { @@ -119,7 +119,7 @@ func url2DirContent(urlStr string) (content *client.Content, err *probe.Error) { return content, nil } -// Check if object key prefix exists +// Check if object key prefix exists. func prefixExists(urlStr string) bool { clnt, err := url2Client(urlStr) if err != nil { diff --git a/utils.go b/utils.go index ae353956..30f820a7 100644 --- a/utils.go +++ b/utils.go @@ -30,7 +30,7 @@ import ( var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") -// newRandomID generates a random id of regular lower case and uppercase english characters +// newRandomID generates a random id of regular lower case and uppercase english characters. func newRandomID(n int) string { rand.Seed(time.Now().UTC().UnixNano()) sid := make([]rune, n) @@ -40,6 +40,7 @@ func newRandomID(n int) string { return string(sid) } +// isBucketVirtualStyle is host virtual bucket style?. func isBucketVirtualStyle(host string) bool { s3Virtual, _ := filepath.Match("*.s3*.amazonaws.com", host) googleVirtual, _ := filepath.Match("*.storage.googleapis.com", host) @@ -48,6 +49,7 @@ func isBucketVirtualStyle(host string) bool { // user.Current is not implemented on 32bit, falling back and using a workaround instead. func userCurrent() (*user.User, *probe.Error) { + // Remove this check if golang fixes their code to support 32bit properly for user.Current. if runtime.GOARCH == "386" && runtime.GOOS == "linux" { return &user.User{ Uid: strconv.Itoa(os.Getuid()), diff --git a/verify-runtime.go b/verify-runtime.go index 90730c7c..dcc21b92 100644 --- a/verify-runtime.go +++ b/verify-runtime.go @@ -27,15 +27,18 @@ import ( "github.com/minio/minio-xl/pkg/probe" ) +// minGolangRuntimeVersion minimum golang runtime version required for 'mc'. var minGolangRuntimeVersion = "1.5.1" -// following code handles the current Golang release styles, we might have to update them in future -// if golang community divulges from the below formatting style. +// Following code handles the current Golang release styles. +// We might have to update them in future, if golang community +// divulges from the below release styles. const ( betaRegexp = "beta[0-9]" rcRegexp = "rc[0-9]" ) +// getNormalizedGolangVersion normalize golang version, handles beta, rc and stable releases. func getNormalizedGolangVersion() string { version := strings.TrimPrefix(runtime.Version(), "go") br := regexp.MustCompile(betaRegexp) @@ -47,20 +50,24 @@ func getNormalizedGolangVersion() string { return version } +// version struct captures the semantic versions. type version struct { major, minor, patch string } +// String stringify version. func (v1 version) String() string { return fmt.Sprintf("%s%s%s", v1.major, v1.minor, v1.patch) } +// Version return integer version of String(). func (v1 version) Version() int { ver, e := strconv.Atoi(v1.String()) fatalIf(probe.NewError(e), "Unable to convert version string to an integer.") return ver } +// LessThan figure out if the input version is lesser than current version. func (v1 version) LessThan(v2 version) bool { if v1.Version() < v2.Version() { return true @@ -68,6 +75,7 @@ func (v1 version) LessThan(v2 version) bool { return false } +// newVersion convert an input semantic version style string into version struct. func newVersion(v string) version { ver := version{} verSlice := strings.Split(v, ".") @@ -81,6 +89,7 @@ func newVersion(v string) version { return ver } +// checkGolangRuntimeVersion - verify currently compiled runtime version. func checkGolangRuntimeVersion() { v1 := newVersion(getNormalizedGolangVersion()) v2 := newVersion(minGolangRuntimeVersion) @@ -90,10 +99,11 @@ func checkGolangRuntimeVersion() { } } +// verifyMCRuntime - verify 'mc' compiled runtime version. func verifyMCRuntime() { checkGolangRuntimeVersion() - // .mc config folder. + // Check if mc config exists. if !isMcConfigExists() { err := createMcConfigDir() fatalIf(err.Trace(), "Unable to create ‘mc’ config folder.") @@ -107,12 +117,12 @@ func verifyMCRuntime() { console.Infoln("Configuration written to [" + mustGetMcConfigPath() + "]. Please update your access credentials.") } - // .mc/session folder. + // Check if mc session folder exists. if !isSessionDirExists() { fatalIf(createSessionDir().Trace(), "Unable to create session config folder.") } - // .mc/share folder. + // Check if mc share folder exists. if !isShareDirExists() { initShareConfig() }