From 25254c76225dabdf5e0085950d80930e415c95a8 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Thu, 5 Oct 2017 15:29:54 -0700 Subject: [PATCH] refactor find command to be simpler (#2264) --- cmd/find-main.go | 28 ++- cmd/find.go | 512 ++++++++++++++++++++++------------------------- cmd/find_test.go | 232 +++++++++++++++++---- 3 files changed, 443 insertions(+), 329 deletions(-) diff --git a/cmd/find-main.go b/cmd/find-main.go index ce94aa3c..a0886eab 100644 --- a/cmd/find-main.go +++ b/cmd/find-main.go @@ -14,7 +14,6 @@ * limitations under the License. */ -// Package cmd stores all of the mc utilities package cmd import ( @@ -110,6 +109,20 @@ UNITS rate of conversion being 7 days in 1 week, 30 days in 1 month, and 365 days in one year. +FORMAT + Support string substitutions with special interpretations for following keywords. + Keywords supported if target is filesystem or object storage: + + {} --> Substitutes to full path. + {base} --> Substitutes to basename of path. + {dir} --> Substitutes to dirname of the path. + {size} --> Substitutes to file size of the path. + {time} --> Substitutes to file modified time of the path. + + Keywords supported if target is object storage: + + {url} --> Substitutes to a shareable URL of the path. + EXAMPLES: 01. Find all files named foo from all buckets. $ {{.HelpName}} s3 --name "file" @@ -175,8 +188,6 @@ func mainFind(ctx *cli.Context) error { // Additional command specific theme customization. console.SetColor("Find", color.New(color.FgGreen, color.Bold)) - var cErr error - checkFindSyntax(ctx) args := ctx.Args() @@ -185,13 +196,8 @@ func mainFind(ctx *cli.Context) error { args = []string{"."} } - for _, targetURL := range args { - var clnt Client - clnt, err := newClient(targetURL) - fatalIf(err.Trace(targetURL), "Unable to initialize `"+targetURL+"`") + clnt, err := newClient(args[0]) + fatalIf(err.Trace(args...), "Unable to initialize `"+args[0]+"`") - doFind(clnt, ctx) - - } - return cErr + return doFind(args[0], clnt, ctx) } diff --git a/cmd/find.go b/cmd/find.go index edcdfbfc..e99e3b24 100644 --- a/cmd/find.go +++ b/cmd/find.go @@ -14,7 +14,6 @@ * limitations under the License. */ -// Package cmd stores all of the mc utilities package cmd import ( @@ -40,47 +39,100 @@ import ( "github.com/minio/minio/pkg/wildcard" ) -// findMSG holds JSON and string values for printing -type findMSG struct { +// findMessage holds JSON and string values for printing find command output. +type findMessage struct { contentMessage } -// String calls tells the console what to print and how to print it -func (f findMSG) String() string { +// String calls tells the console what to print and how to print it. +func (f findMessage) String() string { return console.Colorize("Find", f.contentMessage.Key) } -// JSON formats output to be JSON output -func (f findMSG) JSON() string { +// JSON formats output to be JSON output. +func (f findMessage) JSON() string { return f.contentMessage.JSON() } -// nameMatch pattern matches off of the base of the filepath -func nameMatch(path, pattern string) (bool, error) { - base := filepath.Base(path) - - return filepath.Match(pattern, base) +// nameMatch is similar to filepath.Match but only matches the +// base path of the input. +// +// pattern: +// { term } +// term: +// '*' matches any sequence of non-Separator characters +// '?' matches any single non-Separator character +// '[' [ '^' ] { character-range } ']' +// character class (must be non-empty) +// c matches character c (c != '*', '?', '\\', '[') +// '\\' c matches character c +// character-range: +// c matches character c (c != '\\', '-', ']') +// '\\' c matches character c +// lo '-' hi matches character c for lo <= c <= hi +// +func nameMatch(pattern, path string) bool { + matched, e := filepath.Match(pattern, filepath.Base(path)) + errorIf(probe.NewError(e).Trace(pattern, path), "Unable to match with input pattern") + return matched } -// pathMatch pattern matches off of of the entire filepath -func pathMatch(path, pattern string) bool { +// pathMatch reports whether path matches the wildcard pattern. +// supports '*' and '?' wildcards in the pattern string. +// unlike path.Match(), considers a path as a flat name space +// while matching the pattern. The difference is illustrated in +// the example here https://play.golang.org/p/Ega9qgD4Qz . +func pathMatch(pattern, path string) bool { return wildcard.Match(pattern, path) } -// regexMatch pattern matches off of the entire filepath using regex library -func regexMatch(path, pattern string) (bool, error) { - return regexp.MatchString(pattern, path) +// regexMatch reports whether path matches the regex pattern. +func regexMatch(pattern, path string) bool { + matched, e := regexp.MatchString(pattern, path) + errorIf(probe.NewError(e).Trace(pattern), "Unable to regex match with input pattern") + return matched +} + +// olderThanMatch matches whether if the createTime is older than the allowed threshold. +func olderThanMatch(threshold string, createTime time.Time) bool { + t, err := parseTime(threshold) + fatalIf(err.Trace(threshold), "Unable to parse input threshold value into time.Time") + return createTime.Before(t) +} + +// newerThanMatch matches whether if the createTime is newer than the allowed threshold. +func newerThanMatch(threshold string, createTime time.Time) bool { + t, err := parseTime(threshold) + fatalIf(err.Trace(threshold), "Unable to parse input threshold value into time.Time") + return createTime.After(t) || createTime.Equal(t) +} + +// largerSizeMatch matches whether if the input size bytes is larger than the allowed threshold. +func largerSizeMatch(bytesFmt string, size int64) bool { + i, e := humanize.ParseBytes(bytesFmt) + fatalIf(probe.NewError(e).Trace(bytesFmt), "Unable to parse input threshold value into size bytes") + + return int64(i) < size +} + +// smallerSizeMatch matches whether if the input size bytes is smaller than the allowed threshold. +func smallerSizeMatch(bytesFmt string, size int64) bool { + i, e := humanize.ParseBytes(bytesFmt) + fatalIf(probe.NewError(e).Trace(bytesFmt), "Unable to parse input threshold value into size bytes") + + return int64(i) > size } // doFindPrint prints the output in accordance with the supplied substitution arguments -func doFindPrint(path string, ctx *cli.Context, fileContent contentMessage) { - fileContent.Key = SubArgsHelper(ctx.String("print"), path, fileContent) - printMsg(findMSG{fileContent}) +func doFindPrint(ctx *cli.Context, fileContent contentMessage) { + fileContent.Key = stringsReplace(ctx.String("print"), fileContent) + printMsg(findMessage{fileContent}) } -// doFindExec passes the users input along to the command line, also dealing with substitution arguments -func doFindExec(ctx *cli.Context, path string, fileContent contentMessage) { - commandString := SubArgsHelper(ctx.String("exec"), path, fileContent) +// doFindExec executes the input command line, additionally formats input +// for the command line in accordance with subsititution arguments. +func doFindExec(ctx *cli.Context, fileContent contentMessage) { + commandString := stringsReplace(ctx.String("exec"), fileContent) commandArgs := strings.Split(commandString, " ") cmd := exec.Command(commandArgs[0], commandArgs[1:]...) @@ -93,77 +145,34 @@ func doFindExec(ctx *cli.Context, path string, fileContent contentMessage) { console.Println(string(out.Bytes())) } -// doFindWatch watches the server side to see if a given action is preformed, if yes then a can provided by exec can be executed -func doFindWatch(path string, ctx *cli.Context) { +// doFindWatch - enables listening on the input path, listens for all file/object +// created actions. Asynchronously executes the input command line, also allows +// formatting for the command line in accordance with subsititution arguments. +func doFindWatch(ctx *cli.Context, path string) { params := watchParams{ recursive: true, accountID: fmt.Sprintf("%d", time.Now().Unix()), events: []string{"put"}, } - pathnameParts := strings.SplitAfter(path, "/") - alias := strings.TrimSuffix(pathnameParts[0], "/") - - _, e := getHostConfig(alias) // extract the hostname alias from the path name if present - noAlias := (e == nil) + // Extract the hostname alias from the path name if present + targetAlias, _, _, err := expandAlias(path) + fatalIf(err.Trace(path), "Unable to expand alias.") clnt, content, err := url2Stat(path) - fatalIf(err, "Unable to construct client") + fatalIf(err.Trace(path), "Unable to lookup.") fileContent := parseContent(content) - if noAlias { - //pass hostname (alias) to to watchEvents so that it can remove from pathnames returned from watch - watchEvents(ctx, clnt, params, alias, fileContent) - return - } - watchEvents(ctx, clnt, params, "", fileContent) - return + watchEventsFind(ctx, clnt, params, targetAlias, fileContent) } -// doFindOlder checks to see if the given object was created before or after the given time at which an object was created -func doFindOlder(createTime time.Time, pattern string) bool { - i, err := TimeHelper(pattern) - now := time.Now() - fatalIf(probe.NewError(err), "Error parsing string passed to flag older") - - //find all time in which the time in which the object was just created is after the current time - t := time.Date(now.Year(), now.Month(), now.Day()-i, now.Hour(), now.Minute(), 0, 0, time.UTC) - return createTime.Before(t) -} - -// doFindNewer checks to see if the given object was created before the given threshold -func doFindNewer(createTime time.Time, pattern string) bool { - i, err := TimeHelper(pattern) - now := time.Now() - - fatalIf(probe.NewError(err), "Error parsing string passed to flag newer") - - t := time.Date(now.Year(), now.Month(), now.Day()-i, now.Hour(), now.Minute(), 0, 0, time.UTC) - return createTime.After(t) || createTime.Equal(t) -} - -// doFindLargerSize checks to see if the given object is larger than the given threshold -func doFindLargerSize(size int64, pattern string) bool { - i, err := humanize.ParseBytes(pattern) - fatalIf(probe.NewError(err), "Error parsing string passed to flag larger") - - return int64(i) < size -} - -// doFindSmallerSize checks to see if the given object is smaller than the given threshold -func doFindSmallerSize(size int64, pattern string) bool { - i, err := humanize.ParseBytes(pattern) - fatalIf(probe.NewError(err), "Error parsing string passed to flag smaller") - - return int64(i) > size -} - -// doFind is used to handle most of the users input -func doFind(clnt Client, ctx *cli.Context) { - pathnameParts := strings.SplitAfter(ctx.Args().Get(0), "/") - alias := strings.TrimSuffix(pathnameParts[0], "/") - _, err := getHostConfig(alias) +// doFind - find is main function body which interprets and executes +// all the input parameters. +func doFind(targetURL string, clnt Client, ctx *cli.Context) error { + targetAlias, _, _, err := expandAlias(targetURL) + fatalIf(err.Trace(targetURL), "Unable to expand alias") + separator := string(clnt.GetURL().Separator) // iterate over all content which is within the given directory for content := range clnt.List(true, false, DirNone) { if content.Err != nil { @@ -190,142 +199,128 @@ func doFind(clnt Client, ctx *cli.Context) { } fileContent := parseContent(content) - filePath := fileContent.Key - - // traversing in a object store not a file path - if err == nil { - filePath = path.Join(alias, filePath) + if targetAlias != "" { + fileContent.Key = path.Join(targetAlias, fileContent.Key) } if ctx.String("maxdepth") != "" { - i, e := strconv.Atoi(ctx.String("maxdepth")) - s := "" - + maxDepth, e := strconv.Atoi(ctx.String("maxdepth")) fatalIf(probe.NewError(e), "Error parsing string passed to flag maxdepth") - // we are going to be parsing the path by x amounts - pathParts := strings.SplitAfter(filePath, "/") + newPath := "" - // handle invalid params - // ex. user specifies: - // maxdepth 2, but the given object only has a maxdepth of 1 - if (len(pathParts)-1) < i || i < 0 { + // We are going to convert path into newPath based on the + // maxdepth value, split the strings at separator properly. + pathParts := strings.SplitAfter(fileContent.Key, separator) - // -1 is meant to handle each the array being 0 indexed, but the size not being 0 indexed - i = len(pathParts) - 1 + // Check if max-depth is 2, but if the given object only + // has a maximum depth of 1 use that instead. + if (len(pathParts)-1) < maxDepth || maxDepth < 0 { + maxDepth = len(pathParts) - 1 } - // append portions of path into a string - for j := 0; j <= i; j++ { - s += pathParts[j] + // Construct new path based on the requested maxDepth. + for j := 0; j <= maxDepth; j++ { + newPath += pathParts[j] } - filePath = s - fileContent.Key = s + fileContent.Key = newPath } - // maxdepth can modify the filepath to end in a directory - // to be consistent with find we do not want to be listing directories - // so any parms which end in / will be ignored - if !strings.HasSuffix(filePath, "/") { - - orBool := ctx.Bool("or") - - match := fileContentMatch(fileContent, orBool, ctx) - - if match && ctx.String("print") != "" { - doFindPrint(filePath, ctx, fileContent) - } else if match { - printMsg(findMSG{fileContent}) - } - - if !ctx.Bool("watch") && match && ctx.String("exec") != "" { - doFindExec(ctx, filePath, fileContent) - } + // Maxdepth can modify the filepath to end as a directory prefix + // to be consistent with the find behavior, we wont list directories + // so any paths which end with a separator are ignored. + if strings.HasSuffix(fileContent.Key, separator) { + continue } + match := doFindMatch(ctx, fileContent) + if !ctx.Bool("watch") && match && ctx.String("exec") != "" { + doFindExec(ctx, fileContent) + } else if match && ctx.String("print") != "" { + doFindPrint(ctx, fileContent) + } else if match { + printMsg(findMessage{fileContent}) + } if ctx.Bool("watch") { - doFindWatch(ctx.Args().Get(0), ctx) + doFindWatch(ctx, ctx.Args().Get(0)) } } - + return nil } -// SubArgsHelper formats the string to remove {} and replace each with the appropriate argument -func SubArgsHelper(args, path string, fileContent contentMessage) string { - +// stringsReplace - formats the string to remove {} and replace each +// with the appropriate argument +func stringsReplace(args string, fileContent contentMessage) string { // replace all instances of {} str := args if strings.Contains(str, "{}") { - str = strings.Replace(str, "{}", path, -1) + str = strings.Replace(str, "{}", fileContent.Key, -1) + } + + // replace all instances of {""} + if strings.Contains(str, `{""}`) { + str = strings.Replace(str, `{""}`, strconv.Quote(fileContent.Key), -1) } // replace all instances of {base} if strings.Contains(str, "{base}") { - str = strings.Replace(str, "{base}", filepath.Base(path), -1) + str = strings.Replace(str, "{base}", filepath.Base(fileContent.Key), -1) + } + + // replace all instances of {"base"} + if strings.Contains(str, `{"base"}`) { + str = strings.Replace(str, `{"base"}`, strconv.Quote(filepath.Base(fileContent.Key)), -1) } // replace all instances of {dir} if strings.Contains(str, "{dir}") { - str = strings.Replace(str, "{dir}", filepath.Dir(path), -1) + str = strings.Replace(str, "{dir}", filepath.Dir(fileContent.Key), -1) + } + + // replace all instances of {"dir"} + if strings.Contains(str, `{"dir"}`) { + str = strings.Replace(str, `{"dir"}`, strconv.Quote(filepath.Dir(fileContent.Key)), -1) } // replace all instances of {size} if strings.Contains(str, "{size}") { - s := humanize.IBytes(uint64(fileContent.Size)) - str = strings.Replace(str, "{size}", s, -1) + str = strings.Replace(str, "{size}", humanize.IBytes(uint64(fileContent.Size)), -1) } - if strings.Contains(str, "{url}") { - s := GetPurl(path) - str = strings.Replace(str, "{url}", s, -1) + // replace all instances of {"size"} + if strings.Contains(str, `{"size"}`) { + str = strings.Replace(str, `{"size"}`, strconv.Quote(humanize.IBytes(uint64(fileContent.Size))), -1) } + // replace all instances of {time} if strings.Contains(str, "{time}") { - t := fileContent.Time.String() - str = strings.Replace(str, "{time}", t, -1) + str = strings.Replace(str, "{time}", fileContent.Time.Format(printDate), -1) } - // replace all instances of {""} - if strings.Contains(str, "{\""+"\"}") { - str = strings.Replace(str, "{\""+"\"}", strconv.Quote(path), -1) + // replace all instances of {"time"} + if strings.Contains(str, `{"time"}`) { + str = strings.Replace(str, `{"time"}`, strconv.Quote(fileContent.Time.Format(printDate)), -1) } - // replace all instances of {"base"} - if strings.Contains(str, "{\""+"base"+"\"}") { - str = strings.Replace(str, "{\""+"base"+"\"}", strconv.Quote(filepath.Base(path)), -1) + // replace all instances of {url} + if strings.Contains(str, "{url}") { + str = strings.Replace(str, "{url}", getShareURL(fileContent.Key), -1) } - // replace all instances of {"dir"} - if strings.Contains(str, "{\""+"dir"+"\"}") { - str = strings.Replace(str, "{\""+"dir"+"\"}", strconv.Quote(filepath.Dir(path)), -1) - } - - if strings.Contains(str, "{\""+"url"+"\"}") { - s := GetPurl(path) - str = strings.Replace(str, "{\""+"url"+"\"}", strconv.Quote(s), -1) - } - - if strings.Contains(str, "{\""+"size"+"\"}") { - s := humanize.IBytes(uint64(fileContent.Size)) - str = strings.Replace(str, "{\""+"size"+"\"}", strconv.Quote(s), -1) - } - - if strings.Contains(str, "{\""+"time"+"\"}") { - str = strings.Replace(str, "{\""+"time"+"\"}", strconv.Quote(fileContent.Time.String()), -1) + // replace all instances of {"url"} + if strings.Contains(str, `{"url"}`) { + str = strings.Replace(str, `{"url"}`, strconv.Quote(getShareURL(fileContent.Key)), -1) } return str } -// watchEvents used in conjunction with doFindWatch method to detect and preform desired action when an object is created -func watchEvents(ctx *cli.Context, clnt Client, params watchParams, alias string, fileContent contentMessage) { +// watchEventsFind used in conjunction with doFindWatch method to detect +// and preform desired action when an object is created +func watchEventsFind(ctx *cli.Context, clnt Client, params watchParams, alias string, fileContent contentMessage) { watchObj, err := clnt.Watch(params) - fatalIf(err, "Cannot watch with given params") - - // get client url and remove - cliTemp, _ := getHostConfig(alias) - cliTempURL := cliTemp.URL + fatalIf(err.Trace(alias), "Cannot watch with given params") // enables users to kill using the control + c trapCh := signalTrap(os.Interrupt, syscall.SIGTERM) @@ -351,25 +346,20 @@ func watchEvents(ctx *cli.Context, clnt Client, params watchParams, alias string } time, _ := time.Parse(time.RFC822, event.Time) - msg := contentMessage{ - Key: alias + strings.TrimPrefix(event.Path, cliTempURL), + fileContent := contentMessage{ + Key: alias + strings.TrimPrefix(event.Path, clnt.GetURL().String()), Time: time, Size: event.Size, } - msg.Key = alias + msg.Key - // check to see if the newly create object matches the given params - match := fileContentMatch(msg, ctx.Bool("or"), ctx) - + match := doFindMatch(ctx, fileContent) if match && ctx.String("exec") != "" { - doFindExec(ctx, msg.Key, fileContent) - } - - if match && ctx.String("print") != "" { - doFindExec(ctx, msg.Key, fileContent) + doFindExec(ctx, fileContent) + } else if match && ctx.String("print") != "" { + doFindPrint(ctx, fileContent) } else if match { - printMsg(findMSG{msg}) + printMsg(findMessage{fileContent}) } case err, ok := <-watchObj.Errors(): @@ -385,59 +375,41 @@ func watchEvents(ctx *cli.Context, clnt Client, params watchParams, alias string wg.Wait() } -// fileContentMatch is used to take the params passed to find, in addition to the current -// file and call the appropriate "pattern matching methods" -func fileContentMatch(fileContent contentMessage, orOp bool, ctx *cli.Context) bool { - match := true - - if (match && !orOp) && ctx.String("ignore") != "" { - match = !pathMatch(fileContent.Key, ctx.String("ignore")) +// doFindMatch matches whether fileContent matches appropriately with standard +// "pattern matching" flags requested by the user, such as "name", "path", "regex" ..etc. +func doFindMatch(ctx *cli.Context, fileContent contentMessage) (match bool) { + match = true + if !ctx.Bool("or") { + if ctx.String("ignore") != "" { + match = !pathMatch(ctx.String("ignore"), fileContent.Key) + } + return match } - - // verify that the newly added object matches all of the other specified params - if (match || orOp) && ctx.String("name") != "" { - tmp, err := nameMatch(fileContent.Key, ctx.String("name")) - match = tmp - - fatalIf(probe.NewError(err), "Name could not be matched") + if ctx.String("name") != "" { + match = nameMatch(ctx.String("name"), fileContent.Key) + } else if ctx.String("path") != "" { + match = pathMatch(ctx.String("path"), fileContent.Key) + } else if ctx.String("regex") != "" { + match = regexMatch(ctx.String("regex"), fileContent.Key) + } else if ctx.String("older") != "" { + match = olderThanMatch(ctx.String("older"), fileContent.Time) + } else if ctx.String("newer") != "" { + match = newerThanMatch(ctx.String("newer"), fileContent.Time) + } else if ctx.String("larger") != "" { + match = largerSizeMatch(ctx.String("larger"), fileContent.Size) + } else if ctx.String("smaller") != "" { + match = smallerSizeMatch(ctx.String("smaller"), fileContent.Size) } - - if (match || orOp) && ctx.String("path") != "" { - match = pathMatch(fileContent.Key, ctx.String("path")) - } - - if (match || orOp) && ctx.String("regex") != "" { - temp, e := regexMatch(fileContent.Key, ctx.String("regex")) - match = temp - - fatalIf(probe.NewError(e), "Regex could not be matched") - } - - if (match || orOp) && ctx.String("older") != "" { - match = doFindOlder(fileContent.Time, ctx.String("older")) - } - - if (match || orOp) && ctx.String("newer") != "" { - match = doFindNewer(fileContent.Time, ctx.String("newer")) - } - - if (match || orOp) && ctx.String("larger") != "" { - match = doFindLargerSize(fileContent.Size, ctx.String("larger")) - } - - if (match || orOp) && ctx.String("smaller") != "" { - match = doFindSmallerSize(fileContent.Size, ctx.String("smaller")) - } - return match } -// TimeHelper is used in conjunction with the Newer and Older flags to convert the input -// into an interperable integer (in days) -func TimeHelper(pattern string) (int, error) { - var i int - var t string - var err error +// parseTime - parses input value into a corresponding time value in +// time.Time by adding the input time duration to local UTC time.Now(). +func parseTime(duration string) (time.Time, *probe.Error) { + if duration == "" { + return time.Time{}, errInvalidArgument().Trace(duration) + } + conversion := map[string]int{ "d": 1, "w": 7, @@ -445,66 +417,56 @@ func TimeHelper(pattern string) (int, error) { "y": 365, } - // parse - i, err = strconv.Atoi(pattern) - - if err == nil { - return i, err + // Parse the incoming pattern if its exact number. + i, e := strconv.Atoi(duration) + if e != nil { + // If cant parse as regular string look for + // a conversion multiplier, either d,w,m,y. + p := duration[len(duration)-1:] + i, e = strconv.Atoi(duration[:len(duration)-1]) + if e != nil { + // if we still cant parse, user input is invalid, return error. + return time.Time{}, probe.NewError(e) + } + i = i * conversion[strings.ToLower(p)] } - // if cant parse check for conversion multiplier - t = pattern[len(pattern)-1:] - i, err = strconv.Atoi(pattern[:len(pattern)-1]) + now := UTCNow() - // if still cant parse, user input is invalid, error will be - // thrown by method which called TimeHelper - if err != nil { - return 0, err - } + // Find all time in which the time in which the object was just created is after the current time + t := time.Date(now.Year(), now.Month(), now.Day()-i, now.Hour(), now.Minute(), 0, 0, time.UTC) // if we reach this line, user has passed a valid alphanumeric string - return i * conversion[strings.ToLower(t)], nil + return t, nil } -// GetPurl is used in conjunction with the {url} substitution argument to return presigned URLs -func GetPurl(path string) string { +// 7 days in seconds. +var defaultSevenDays = time.Duration(604800) * time.Second + +// getShareURL is used in conjunction with the {url} substitution +// argument to generate and return presigned URLs, returns error if any. +func getShareURL(path string) string { targetAlias, targetURLFull, _, err := expandAlias(path) - fatalIf(err, "Error with expand alias") + fatalIf(err.Trace(path), "Unable to expand alias") + clnt, err := newClientFromAlias(targetAlias, targetURLFull) - fatalIf(err, "Error with newClientFromAlias") + fatalIf(err.Trace(targetAlias, targetURLFull), "Unable to newClientFromAlias") - isIncomplete := false + content, err := clnt.Stat(false) + fatalIf(err.Trace(targetURLFull, targetAlias), "Unable to lookup file/object.") - objectsCh := make(chan *clientContent) - - content, err := clnt.Stat(isIncomplete) - - fatalIf(err, "Error with client stat") - - // piping all content into the object channel to be processed - go func() { - defer close(objectsCh) - objectsCh <- content - }() - - // get content from channel to be converted into presigned URL - for content := range objectsCh { - fatalIf(content.Err, "Error with content") - - if content.Type.IsDir() { - continue - } - - objectURL := content.URL.String() - newClnt, err := newClientFromAlias(targetAlias, objectURL) - fatalIf(err, "Error with newClientFromAlias") - - // set default expiry for each url (point of no longer valid), to be 7 days - expiry := time.Duration(604800) * time.Second - shareURL, err := newClnt.ShareDownload(expiry) - fatalIf(err, "Error with ShareDownloa") - - return shareURL + // Skip if its a directory. + if content.Type.IsDir() { + return "" } - return "" + + objectURL := content.URL.String() + newClnt, err := newClientFromAlias(targetAlias, objectURL) + fatalIf(err.Trace(targetAlias, objectURL), "Unable to initialize new client from alias.") + + // Set default expiry for each url (point of no longer valid), to be 7 days + shareURL, err := newClnt.ShareDownload(defaultSevenDays) + fatalIf(err.Trace(targetAlias, objectURL), "Unable to generate share url.") + + return shareURL } diff --git a/cmd/find_test.go b/cmd/find_test.go index 317cef55..8c7b71be 100644 --- a/cmd/find_test.go +++ b/cmd/find_test.go @@ -18,62 +18,208 @@ package cmd import ( "testing" + "time" ) -//TestFind is the structure used to contain params pertinent to find related tests -type TestFind struct { - pattern, filePath, flagName string - match bool -} +// Tests matching functions for name, path and regex. +func TestFindMatch(t *testing.T) { + // testFind is the structure used to contain params pertinent to find related tests + type testFind struct { + pattern, filePath, flagName string + match bool + } -var basicTests = []TestFind{ - //basic name and path tests - {"*.jpg", "carter.jpg", "name", true}, - {"*.jpg", "carter.jpeg", "name", false}, - {"*/test/*", "/test/bob/likes/cake", "name", false}, - {"*/test/*", "/test/bob/likes/cake", "path", true}, - {"*test/*", "bob/test/likes/cake", "name", false}, - {"*/test/*", "bob/test/likes/cake", "path", true}, - {"*test/*", "bob/likes/test/cake", "name", false}, + var basicTests = []testFind{ + // Basic name and path tests + {"*.jpg", "carter.jpg", "name", true}, + {"*.jpg", "carter.jpeg", "name", false}, + {"*/test/*", "/test/bob/likes/cake", "name", false}, + {"*/test/*", "/test/bob/likes/cake", "path", true}, + {"*test/*", "bob/test/likes/cake", "name", false}, + {"*/test/*", "bob/test/likes/cake", "path", true}, + {"*test/*", "bob/likes/test/cake", "name", false}, - //more advanced name and path tests - {"*/test/*", "bob/likes/cake/test", "name", false}, - {"*.jpg", ".jpg/elves/are/evil", "name", false}, - {"*.jpg", ".jpg/elves/are/evil", "path", false}, - {"*/test/*", "test1/test2/test3/test", "path", false}, - {"*/ test /*", "test/test1/test2/test3/test", "path", false}, - {"*/test/*", " test /I/have/Really/Long/hair", "path", false}, - {"*XA==", "I/enjoy/morning/walks/XA==", "name ", true}, - {"*XA==", "XA==/Height/is/a/social/construct", "path", false}, - {"*W", "/Word//this/is a/trickyTest", "path", false}, - {"*parser", "/This/might/mess up./the/parser", "name", true}, - {"*", "/bla/bla/bla/ ", "name", true}, - {"*LTIxNDc0ODM2NDgvLTE=", "What/A/Naughty/String/LTIxNDc0ODM2NDgvLTE=", "name", true}, - {"LTIxNDc0ODM2NDgvLTE=", "LTIxNDc0ODM2NDgvLTE=/I/Am/One/Baaaaad/String", "path", false}, - {"wq3YgNiB2ILYg9iE2IXYnNud3I/hoI7igIvigIzigI3igI7igI/igKrigKvigKzigK3igK7igaDi", "An/Even/Bigger/String/wq3YgNiB2ILYg9iE2IXYnNud3I/hoI7igIvigIzigI3igI7igI/igKrigKvigKzigK3igK7igaDi", "name", false}, - {"/", "funky/path/name", "path", false}, - {"๐•ฟ๐–๐–Š", "well/this/isAN/odd/font/THE", "name", false}, - {"๐•ฟ๐–๐–Š", "well/this/isAN/odd/font/The", "name", false}, - {"๐•ฟ๐–๐–Š", "well/this/isAN/odd/font/๐“ฃ๐“ฑ๐“ฎ", "name", false}, - {"๐•ฟ๐–๐–Š", "what/a/strange/turn/of/events/๐“ฃhe", "name", false}, - {"๐•ฟ๐–๐–Š", "well/this/isAN/odd/font/๐•ฟ๐–๐–Š", "name", true}, + // More advanced name and path tests + {"*/test/*", "bob/likes/cake/test", "name", false}, + {"*.jpg", ".jpg/elves/are/evil", "name", false}, + {"*.jpg", ".jpg/elves/are/evil", "path", false}, + {"*/test/*", "test1/test2/test3/test", "path", false}, + {"*/ test /*", "test/test1/test2/test3/test", "path", false}, + {"*/test/*", " test /I/have/Really/Long/hair", "path", false}, + {"*XA==", "I/enjoy/morning/walks/XA==", "name ", true}, + {"*XA==", "XA==/Height/is/a/social/construct", "path", false}, + {"*W", "/Word//this/is a/trickyTest", "path", false}, + {"*parser", "/This/might/mess up./the/parser", "name", true}, + {"*", "/bla/bla/bla/ ", "name", true}, + {"*LTIxNDc0ODM2NDgvLTE=", "What/A/Naughty/String/LTIxNDc0ODM2NDgvLTE=", "name", true}, + {"LTIxNDc0ODM2NDgvLTE=", "LTIxNDc0ODM2NDgvLTE=/I/Am/One/Baaaaad/String", "path", false}, + {"wq3YgNiB2ILYg9iE2IXYnNud3I/hoI7igIvigIzigI3igI7igI/igKrigKvigKzigK3igK7igaDi", + "An/Even/Bigger/String/wq3YgNiB2ILYg9iE2IXYnNud3I/hoI7igIvigIzigI3igI7igI/igKrigKvigKzigK3igK7igaDi", "name", false}, + {"/", "funky/path/name", "path", false}, + {"๐•ฟ๐–๐–Š", "well/this/isAN/odd/font/THE", "name", false}, + {"๐•ฟ๐–๐–Š", "well/this/isAN/odd/font/The", "name", false}, + {"๐•ฟ๐–๐–Š", "well/this/isAN/odd/font/๐“ฃ๐“ฑ๐“ฎ", "name", false}, + {"๐•ฟ๐–๐–Š", "what/a/strange/turn/of/events/๐“ฃhe", "name", false}, + {"๐•ฟ๐–๐–Š", "well/this/isAN/odd/font/๐•ฟ๐–๐–Š", "name", true}, - //implement some tests of regex + // Regexp based. + {"^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", "testbucket-1", "regex", true}, + {"^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", "testbucket.", "regex", false}, + {`^(\d+\.){3}\d+$`, "192.168.1.1", "regex", true}, + {`^(\d+\.){3}\d+$`, "192.168.x.x", "regex", false}, + } -} - -func TestFindMethod(t *testing.T) { for _, test := range basicTests { switch test.flagName { case "name": - if testMatch, _ := nameMatch(test.filePath, test.pattern); testMatch != test.match { - t.Fatalf("Unexpected result %t, with pattern %s, flag %s and filepath %s \n", !test.match, test.pattern, test.flagName, test.filePath) + testMatch := nameMatch(test.pattern, test.filePath) + if testMatch != test.match { + t.Fatalf("Unexpected result %t, with pattern %s, flag %s and filepath %s \n", + !test.match, test.pattern, test.flagName, test.filePath) } case "path": - if testMatch := pathMatch(test.filePath, test.pattern); testMatch != test.match { - t.Fatalf("Unexpected result %t, with pattern %s, flag %s and filepath %s \n", !test.match, test.pattern, test.flagName, test.filePath) + testMatch := pathMatch(test.pattern, test.filePath) + if testMatch != test.match { + t.Fatalf("Unexpected result %t, with pattern %s, flag %s and filepath %s \n", + !test.match, test.pattern, test.flagName, test.filePath) + } + case "regex": + testMatch := regexMatch(test.pattern, test.filePath) + if testMatch != test.match { + t.Fatalf("Unexpected result %t, with pattern %s, flag %s and filepath %s \n", + !test.match, test.pattern, test.flagName, test.filePath) } + } + } +} +// Tests for parsing time layout. +func TestParseTime(t *testing.T) { + testCases := []struct { + value string + success bool + }{ + // Parses 1 day successfully. + { + value: "1d", + success: true, + }, + // Parses 1 week successfully. + { + value: "1w", + success: true, + }, + // Parses 1 year successfully. + { + value: "1y", + success: true, + }, + // Parses 2 months successfully. + { + value: "2m", + success: true, + }, + // Failure to parse "xd". + { + value: "xd", + success: false, + }, + // Failure to parse empty string. + { + value: "", + success: false, + }, + } + for i, testCase := range testCases { + pt, err := parseTime(testCase.value) + if err != nil && testCase.success { + t.Errorf("Test: %d, Expected to be successful, but found error %s, for time value %s", i+1, err, testCase.value) + } + if pt.IsZero() && testCase.success { + t.Errorf("Test: %d, Expected time to be non zero, but found zero time for time value %s", i+1, testCase.value) + } + if err == nil && !testCase.success { + t.Errorf("Test: %d, Expected error but found to be successful for time value %s", i+1, testCase.value) + } + } +} + +// Tests string substritution function. +func TestStringReplace(t *testing.T) { + testCases := []struct { + str string + expectedStr string + content contentMessage + }{ + // Tests string replace {} without quotes. + { + str: "{}", + expectedStr: "path/1", + content: contentMessage{Key: "path/1"}, + }, + // Tests string replace {} with quotes. + { + str: `{""}`, + expectedStr: `"path/1"`, + content: contentMessage{Key: "path/1"}, + }, + // Tests string replace {base} + { + str: "{base}", + expectedStr: "1", + content: contentMessage{Key: "path/1"}, + }, + // Tests string replace {"base"} with quotes. + { + str: `{"base"}`, + expectedStr: `"1"`, + content: contentMessage{Key: "path/1"}, + }, + // Tests string replace {dir} + { + str: `{dir}`, + expectedStr: `path`, + content: contentMessage{Key: "path/1"}, + }, + // Tests string replace {"dir"} with quotes. + { + str: `{"dir"}`, + expectedStr: `"path"`, + content: contentMessage{Key: "path/1"}, + }, + // Tests string replace {"size"} with quotes. + { + str: `{"size"}`, + expectedStr: `"0B"`, + content: contentMessage{Size: 0}, + }, + // Tests string replace {"time"} with quotes. + { + str: `{"time"}`, + expectedStr: `"2038-01-19 03:14:07 UTC"`, + content: contentMessage{ + Time: time.Unix(2147483647, 0).UTC(), + }, + }, + // Tests string replace {size} + { + str: `{size}`, + expectedStr: `1.0MiB`, + content: contentMessage{Size: 1024 * 1024}, + }, + // Tests string replace {time} + { + str: `{time}`, + expectedStr: `2038-01-19 03:14:07 UTC`, + content: contentMessage{ + Time: time.Unix(2147483647, 0).UTC(), + }, + }, + } + for i, testCase := range testCases { + gotStr := stringsReplace(testCase.str, testCase.content) + if gotStr != testCase.expectedStr { + t.Errorf("Test %d: Expected %s, got %s", i+1, testCase.expectedStr, gotStr) } } }