From c10b429dcbeb7071e2758233afeda46d2ed688e5 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Mon, 9 Oct 2017 19:44:58 -0700 Subject: [PATCH] Refactor and fix find bugs (#2273) - Watch now avoids an unnecessary waitgroup and simplifies overall flow. - Watch now honors maxDepth parameter as well. - Parsing logic is fully outside in the mainFind() function. - Enhance and fix behavior of nameMatch to comply with unix find behavior. - Enhance and fix behavior of maxdepth to comply with unix find behavior. Fixes #2272 --- cmd/find-main.go | 148 ++++++++++++++----- cmd/find.go | 360 +++++++++++++++++++++------------------------- cmd/find_test.go | 249 +++++++++++++++++++++++++++++--- cmd/watch-main.go | 2 - cmd/watch.go | 3 - 5 files changed, 506 insertions(+), 256 deletions(-) diff --git a/cmd/find-main.go b/cmd/find-main.go index a0886eab..5c6afc61 100644 --- a/cmd/find-main.go +++ b/cmd/find-main.go @@ -18,31 +18,18 @@ package cmd import ( "strings" + "time" + humanize "github.com/dustin/go-humanize" "github.com/fatih/color" "github.com/minio/cli" "github.com/minio/mc/pkg/console" + "github.com/minio/mc/pkg/probe" ) -// find specific flags +// List of all flags supported by find command. var ( findFlags = []cli.Flag{ - cli.StringFlag{ - Name: "name", - Usage: "Find object names matching wildcard pattern", - }, - cli.StringFlag{ - Name: "path", - Usage: "Match directory names matching wildcard pattern", - }, - cli.StringFlag{ - Name: "regex", - Usage: "Match directory and object name with PCRE regex pattern", - }, - cli.StringFlag{ - Name: "print", - Usage: "Print in custom format to STDOUT (see FORMAT)", - }, cli.StringFlag{ Name: "exec", Usage: "Spawn an external process for each matching object (see FORMAT)", @@ -51,6 +38,10 @@ var ( Name: "ignore", Usage: "Exclude objects matching the wildcard pattern", }, + cli.StringFlag{ + Name: "name", + Usage: "Find object names matching wildcard pattern", + }, cli.StringFlag{ Name: "newer", Usage: "Match all objects newer than specified time in units (see UNITS)", @@ -59,6 +50,18 @@ var ( Name: "older", Usage: "Match all objects older than specified time in units (see UNITS)", }, + cli.StringFlag{ + Name: "path", + Usage: "Match directory names matching wildcard pattern", + }, + cli.StringFlag{ + Name: "print", + Usage: "Print in custom format to STDOUT (see FORMAT)", + }, + cli.StringFlag{ + Name: "regex", + Usage: "Match directory and object name with PCRE regex pattern", + }, cli.StringFlag{ Name: "larger", Usage: "Match all objects larger than specified size in units (see UNITS)", @@ -67,17 +70,13 @@ var ( Name: "smaller", Usage: "Match all objects smaller than specified size in units (see UNITS)", }, - cli.StringFlag{ + cli.UintFlag{ Name: "maxdepth", Usage: "Limit directory navigation to specified depth", }, cli.BoolFlag{ Name: "watch", - Usage: "Monitor specified location for newly created objects", - }, - cli.BoolFlag{ - Name: "or", - Usage: "Changes the matching criteria from an \"and\" to an \"or\"", + Usage: "Monitor a specified path for newly created files and objects", }, } ) @@ -163,24 +162,53 @@ EXAMPLES: // checkFindSyntax - validate the passed arguments func checkFindSyntax(ctx *cli.Context) { args := ctx.Args() - - // help message on [mc][find] if !args.Present() { - cli.ShowCommandHelpAndExit(ctx, "find", 1) + args = []string{"./"} // No args just default to present directory. + } else if args.Get(0) == "." { + args[0] = "./" // If the arg is '.' treat it as './'. } - if ctx.Bool("watch") && !strings.Contains(args[0], "/") { - console.Println("Users must specify a bucket name for watch") - console.Fatalln() - } - - // verify that there are no empty arguments for _, arg := range args { if strings.TrimSpace(arg) == "" { fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.") } } + // Extract input URLs and validate. + for _, url := range args { + _, _, err := url2Stat(url) + if err != nil && !isURLPrefixExists(url, false) { + // Bucket name empty is a valid error for 'find myminio' unless we are using watch, treat it as such. + if _, ok := err.ToGoError().(BucketNameEmpty); ok && !ctx.Bool("watch") { + continue + } + fatalIf(err.Trace(url), "Unable to stat `"+url+"`.") + } + } +} + +// Find context is container to hold all parsed input arguments, +// each parsed input is stored in its native typed form for +// ease of repurposing. +type findContext struct { + *cli.Context + execCmd string + ignorePattern string + namePattern string + pathPattern string + regexPattern string + maxDepth uint + printFmt string + olderThan time.Time + newerThan time.Time + largerSize uint64 + smallerSize uint64 + watch bool + + // Internal values + targetAlias string + targetURL string + clnt Client } // mainFind - handler for mc find commands @@ -191,13 +219,59 @@ func mainFind(ctx *cli.Context) error { checkFindSyntax(ctx) args := ctx.Args() - - if !ctx.Args().Present() { - args = []string{"."} + if !args.Present() { + args = []string{"./"} // Not args present default to present directory. + } else if args.Get(0) == "." { + args[0] = "./" // If the arg is '.' treat it as './'. } clnt, err := newClient(args[0]) - fatalIf(err.Trace(args...), "Unable to initialize `"+args[0]+"`") + fatalIf(err.Trace(args...), "Unable to initialize `"+args[0]+"`.") - return doFind(args[0], clnt, ctx) + var olderThan, newerThan time.Time + + if ctx.String("older") != "" { + olderThan, err = parseTime(ctx.String("older")) + fatalIf(err.Trace(ctx.String("older")), "Unable to parse input time.") + } + if ctx.String("newer") != "" { + newerThan, err = parseTime(ctx.String("newer")) + fatalIf(err.Trace(ctx.String("newer")), "Unable to parse input time.") + } + + // Use 'e' to indicate Go error, this is a convention followed in `mc`. For probe.Error we call it + // 'err' and regular Go error is called as 'e'. + var e error + var largerSize, smallerSize uint64 + + if ctx.String("larger") != "" { + largerSize, e = humanize.ParseBytes(ctx.String("larger")) + fatalIf(probe.NewError(e).Trace(ctx.String("larger")), "Unable to parse input bytes.") + } + + if ctx.String("smaller") != "" { + smallerSize, e = humanize.ParseBytes(ctx.String("smaller")) + fatalIf(probe.NewError(e).Trace(ctx.String("smaller")), "Unable to parse input bytes.") + } + + targetAlias, _, _, err := expandAlias(args[0]) + fatalIf(err.Trace(args[0]), "Unable to expand alias.") + + return doFind(&findContext{ + Context: ctx, + maxDepth: ctx.Uint("maxdepth"), + execCmd: ctx.String("exec"), + printFmt: ctx.String("print"), + namePattern: ctx.String("name"), + pathPattern: ctx.String("path"), + regexPattern: ctx.String("regex"), + olderThan: olderThan, + newerThan: newerThan, + largerSize: largerSize, + smallerSize: smallerSize, + watch: ctx.Bool("watch"), + targetAlias: targetAlias, + targetURL: args[0], + clnt: clnt, + }) } diff --git a/cmd/find.go b/cmd/find.go index e99e3b24..20f86b49 100644 --- a/cmd/find.go +++ b/cmd/find.go @@ -18,20 +18,16 @@ package cmd import ( "bytes" - "fmt" "os" "os/exec" - "path" "path/filepath" "regexp" "strconv" "strings" - "sync" "syscall" "time" "github.com/dustin/go-humanize" - "github.com/minio/cli" "github.com/minio/mc/pkg/console" "github.com/minio/mc/pkg/probe" @@ -55,7 +51,8 @@ func (f findMessage) JSON() string { } // nameMatch is similar to filepath.Match but only matches the -// base path of the input. +// base path of the input, if we couldn't find a match we +// also proceed to look for similar strings alone and print it. // // pattern: // { term } @@ -74,6 +71,14 @@ func (f findMessage) JSON() string { 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") + if !matched { + for _, pathComponent := range strings.Split(path, "/") { + matched = pathComponent == pattern + if matched { + break + } + } + } return matched } @@ -93,159 +98,180 @@ func regexMatch(pattern, path string) bool { 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(ctx *cli.Context, fileContent contentMessage) { - fileContent.Key = stringsReplace(ctx.String("print"), fileContent) - printMsg(findMessage{fileContent}) -} - -// doFindExec executes the input command line, additionally formats input +// execFind 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, " ") +func execFind(command string) { + commandArgs := strings.Split(command, " ") cmd := exec.Command(commandArgs[0], commandArgs[1:]...) var out bytes.Buffer cmd.Stdout = &out if err := cmd.Run(); err != nil { console.Fatalln(err) - console.Fatalln() } - console.Println(string(out.Bytes())) + console.Println(out.String()) } -// doFindWatch - enables listening on the input path, listens for all file/object +// watchFind - 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) { +func watchFind(ctx *findContext) { + // Watch is not enabled, return quickly. + if !ctx.watch { + return + } params := watchParams{ recursive: true, - accountID: fmt.Sprintf("%d", time.Now().Unix()), events: []string{"put"}, } + watchObj, err := ctx.clnt.Watch(params) + fatalIf(err.Trace(ctx.targetAlias), "Cannot watch with given params") - // Extract the hostname alias from the path name if present - targetAlias, _, _, err := expandAlias(path) - fatalIf(err.Trace(path), "Unable to expand alias.") + // Enables users to kill using the control + c + trapCh := signalTrap(os.Interrupt, syscall.SIGTERM) - clnt, content, err := url2Stat(path) - fatalIf(err.Trace(path), "Unable to lookup.") + // Loop until user CTRL-C the command line. + for { + select { + case <-trapCh: + console.Println() + close(watchObj.doneChan) + return + case event, ok := <-watchObj.Events(): + if !ok { + return + } - fileContent := parseContent(content) - watchEventsFind(ctx, clnt, params, targetAlias, fileContent) + time, e := time.Parse(time.RFC822, event.Time) + if e != nil { + errorIf(probe.NewError(e).Trace(event.Time), "Unable to parse event time") + continue + } + + find(ctx, contentMessage{ + Key: getAliasedPath(ctx, event.Path), + Time: time, + Size: event.Size, + }) + + case err, ok := <-watchObj.Errors(): + if !ok { + return + } + errorIf(err, "Unable to watch for events.") + return + } + } +} + +// Descend at most (a non-negative integer) levels of files +// below the starting-prefix and trims the suffix. This function +// returns path as is without manipulation if the maxDepth is 0 +// i.e (not set). +func trimSuffixAtMaxDepth(startPrefix, path, separator string, maxDepth uint) string { + if maxDepth == 0 { + return path + } + // Remove the requested prefix from consideration, maxDepth is + // only considered for all other levels excluding the starting prefix. + path = strings.TrimPrefix(path, startPrefix) + pathComponents := strings.SplitAfter(path, separator) + if len(pathComponents) >= int(maxDepth) { + pathComponents = pathComponents[:maxDepth] + } + pathComponents = append([]string{startPrefix}, pathComponents...) + return strings.Join(pathComponents, "") +} + +// Get aliased path used finally in printing, trim paths to ensure +// that we have removed the fully qualified paths and original +// start prefix (targetAlias) is retained. This function also honors +// maxDepth if set then the resultant path will be trimmed at requested +// maxDepth. +func getAliasedPath(ctx *findContext, path string) string { + separator := string(ctx.clnt.GetURL().Separator) + prefixPath := ctx.clnt.GetURL().String() + var aliasedPath string + if ctx.targetAlias != "" { + aliasedPath = ctx.targetAlias + strings.TrimPrefix(path, prefixPath) + } else { + aliasedPath = path + // look for prefix path, if found filter at that, Watch calls + // for example always provide absolute path. So for relative + // prefixes we need to employ this kind of code. + if i := strings.Index(path, prefixPath); i > 0 { + aliasedPath = path[i:] + } + } + return trimSuffixAtMaxDepth(ctx.targetURL, aliasedPath, separator, ctx.maxDepth) +} + +func find(ctx *findContext, fileContent contentMessage) { + // 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, string(ctx.clnt.GetURL().Separator)) { + return + } + + // Match the incoming content, didn't match return. + if !matchFind(ctx, fileContent) { + return + } // For all matching content + // proceed to either exec, format the output string. + switch { + case ctx.execCmd != "": + execFind(stringsReplace(ctx.execCmd, fileContent)) + case ctx.printFmt != "": + fileContent.Key = stringsReplace(ctx.printFmt, fileContent) + } + printMsg(findMessage{fileContent}) } // 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") +func doFind(ctx *findContext) error { + // If watch is enabled we will wait on the prefix perpetually + // for all I/O events until cancelled by user, if watch is not enabled + // following defer is a no-op. + defer watchFind(ctx) - separator := string(clnt.GetURL().Separator) // iterate over all content which is within the given directory - for content := range clnt.List(true, false, DirNone) { + for content := range ctx.clnt.List(true, false, DirNone) { if content.Err != nil { switch content.Err.ToGoError().(type) { // handle this specifically for filesystem related errors. case BrokenSymlink: - errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.") + errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list broken link.") continue case TooManyLevelsSymlink: - errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.") + errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list too many levels link.") continue case PathNotFound: - errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") + errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.") continue case PathInsufficientPermission: - errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") + errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.") continue case ObjectOnGlacier: - errorIf(content.Err.Trace(clnt.GetURL().String()), "") + errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "") continue } - fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") + fatalIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.") continue } - fileContent := parseContent(content) - if targetAlias != "" { - fileContent.Key = path.Join(targetAlias, fileContent.Key) - } + // Executes all the find functionalities. + find(ctx, contentMessage{ + Key: getAliasedPath(ctx, content.URL.String()), + Time: content.Time.Local(), + Size: content.Size, + }) - if ctx.String("maxdepth") != "" { - maxDepth, e := strconv.Atoi(ctx.String("maxdepth")) - fatalIf(probe.NewError(e), "Error parsing string passed to flag maxdepth") - - newPath := "" - - // 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) - - // 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 - } - - // Construct new path based on the requested maxDepth. - for j := 0; j <= maxDepth; j++ { - newPath += pathParts[j] - } - - fileContent.Key = newPath - } - - // 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, ctx.Args().Get(0)) - } } + + // Success, notice watch will execute in defer only if enabled and this call + // will return after watch is cancelled. return nil } @@ -316,89 +342,33 @@ func stringsReplace(args string, fileContent contentMessage) string { return str } -// 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.Trace(alias), "Cannot watch with given params") - - // enables users to kill using the control + c - trapCh := signalTrap(os.Interrupt, syscall.SIGTERM) - - wg := sync.WaitGroup{} - wg.Add(1) - - // opens a channel of all content created on the server, any errors detected, - // and scanning for the user input (Control + C) - go func() { - defer wg.Done() - - // loop until user kills the channel input - for { - select { - case <-trapCh: - console.Println() - close(watchObj.doneChan) - return - case event, ok := <-watchObj.Events(): - if !ok { - return - } - - time, _ := time.Parse(time.RFC822, event.Time) - fileContent := contentMessage{ - Key: alias + strings.TrimPrefix(event.Path, clnt.GetURL().String()), - Time: time, - Size: event.Size, - } - - // check to see if the newly create object matches the given params - match := doFindMatch(ctx, fileContent) - if match && ctx.String("exec") != "" { - doFindExec(ctx, fileContent) - } else if match && ctx.String("print") != "" { - doFindPrint(ctx, fileContent) - } else if match { - printMsg(findMessage{fileContent}) - } - - case err, ok := <-watchObj.Errors(): - if !ok { - return - } - errorIf(err, "Unable to watch for events.") - return - } - } - }() - - wg.Wait() -} - -// doFindMatch matches whether fileContent matches appropriately with standard +// matchFind 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) { +func matchFind(ctx *findContext, fileContent contentMessage) (match bool) { match = true - if !ctx.Bool("or") { - if ctx.String("ignore") != "" { - match = !pathMatch(ctx.String("ignore"), fileContent.Key) - } - return match + if match && ctx.ignorePattern != "" { + match = !pathMatch(ctx.ignorePattern, fileContent.Key) } - 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 && ctx.namePattern != "" { + match = nameMatch(ctx.namePattern, fileContent.Key) + } + if match && ctx.pathPattern != "" { + match = pathMatch(ctx.pathPattern, fileContent.Key) + } + if match && ctx.regexPattern != "" { + match = regexMatch(ctx.regexPattern, fileContent.Key) + } + if match && !ctx.olderThan.IsZero() { + match = fileContent.Time.Before(ctx.olderThan) + } + if match && !ctx.newerThan.IsZero() { + match = fileContent.Time.After(ctx.newerThan) || fileContent.Time.Equal(ctx.newerThan) + } + if match && ctx.largerSize > 0 { + match = int64(ctx.largerSize) < fileContent.Size + } + if match && ctx.smallerSize > 0 { + match = int64(ctx.smallerSize) > fileContent.Size } return match } @@ -450,7 +420,7 @@ func getShareURL(path string) string { fatalIf(err.Trace(path), "Unable to expand alias") clnt, err := newClientFromAlias(targetAlias, targetURLFull) - fatalIf(err.Trace(targetAlias, targetURLFull), "Unable to newClientFromAlias") + fatalIf(err.Trace(targetAlias, targetURLFull), "Unable to initialize client instance from alias.") content, err := clnt.Stat(false) fatalIf(err.Trace(targetURLFull, targetAlias), "Unable to lookup file/object.") diff --git a/cmd/find_test.go b/cmd/find_test.go index 8c7b71be..aaa1f0b6 100644 --- a/cmd/find_test.go +++ b/cmd/find_test.go @@ -21,6 +21,209 @@ import ( "time" ) +// Tests match find function with all supported inputs on +// file pattern, size and time. +func TestMatchFind(t *testing.T) { + // List of various contexts used in each tests, + // tests are run in the same order as this list. + var listFindContexts = []*findContext{ + &findContext{ + ignorePattern: "*.go", + }, + &findContext{ + namePattern: "console", + }, + &findContext{ + pathPattern: "*console*", + }, + &findContext{ + regexPattern: `^(\d+\.){3}\d+$`, + }, + &findContext{ + olderThan: time.Unix(12000, 0).UTC(), + }, + &findContext{ + newerThan: time.Unix(12000, 0).UTC(), + }, + &findContext{ + largerSize: 1024 * 1024, + }, + &findContext{ + smallerSize: 1024, + }, + &findContext{ + ignorePattern: "*.txt", + }, + &findContext{}, + } + + var testCases = []struct { + content contentMessage + expectedMatch bool + }{ + // Matches ignore pattern, so match will be false - Test 1. + { + content: contentMessage{ + Key: "pkg/console/console.go", + }, + expectedMatch: false, + }, + // Matches name pattern - Test 2. + { + content: contentMessage{ + Key: "pkg/console/console.go", + }, + expectedMatch: true, + }, + // Matches path pattern - Test 3. + { + content: contentMessage{ + Key: "pkg/console/console.go", + }, + expectedMatch: true, + }, + // Matches regex pattern - Test 4. + { + content: contentMessage{ + Key: "192.168.1.1", + }, + expectedMatch: true, + }, + // Matches older than time - Test 5. + { + content: contentMessage{ + Time: time.Unix(11999, 0).UTC(), + }, + expectedMatch: true, + }, + // Matches newer than time - Test 6. + { + content: contentMessage{ + Time: time.Unix(12001, 0).UTC(), + }, + expectedMatch: true, + }, + // Matches size larger - Test 7. + { + content: contentMessage{ + Size: 1024 * 1024 * 2, + }, + expectedMatch: true, + }, + // Matches size smaller - Test 8. + { + content: contentMessage{ + Size: 1023, + }, + expectedMatch: true, + }, + // Does not match ignore pattern, so match will be true - Test 9. + { + content: contentMessage{ + Key: "pkg/console/console.go", + }, + expectedMatch: true, + }, + // No matching inputs were provided, so nothing to match return value is true - Test 10. + { + content: contentMessage{}, + expectedMatch: true, + }, + } + + // Runs all the test cases and validate the expected conditions. + for i, testCase := range testCases { + gotMatch := matchFind(listFindContexts[i], testCase.content) + if testCase.expectedMatch != gotMatch { + t.Errorf("Test: %d, expected match %t, got %t", i+1, testCase.expectedMatch, gotMatch) + } + } +} + +// Tests suffix strings trimmed off correctly at maxdepth. +func TestSuffixTrimmingAtMaxDepth(t *testing.T) { + var testCases = []struct { + startPrefix string + path string + separator string + maxDepth uint + expectedNewPath string + }{ + // Tests at max depth 0. + { + startPrefix: "./", + path: ".git/refs/remotes", + separator: "/", + maxDepth: 0, + expectedNewPath: ".git/refs/remotes", + }, + // Tests at max depth 1. + { + startPrefix: "./", + path: ".git/refs/remotes", + separator: "/", + maxDepth: 1, + expectedNewPath: "./.git/", + }, + // Tests at max depth 2. + { + startPrefix: "./", + path: ".git/refs/remotes", + separator: "/", + maxDepth: 2, + expectedNewPath: "./.git/refs/", + }, + // Tests at max depth 3. + { + startPrefix: "./", + path: ".git/refs/remotes", + separator: "/", + maxDepth: 3, + expectedNewPath: "./.git/refs/remotes", + }, + // Tests with startPrefix empty. + { + startPrefix: "", + path: ".git/refs/remotes", + separator: "/", + maxDepth: 2, + expectedNewPath: ".git/refs/", + }, + // Tests with separator empty. + { + startPrefix: "", + path: ".git/refs/remotes", + separator: "", + maxDepth: 2, + expectedNewPath: ".g", + }, + // Tests with nested startPrefix paths - 1. + { + startPrefix: ".git/refs/", + path: ".git/refs/remotes", + separator: "/", + maxDepth: 1, + expectedNewPath: ".git/refs/remotes", + }, + // Tests with nested startPrefix paths - 2. + { + startPrefix: ".git/refs", + path: ".git/refs/remotes", + separator: "/", + maxDepth: 1, + expectedNewPath: ".git/refs/", + }, + } + + // Run all the test cases and validate for returned new path. + for i, testCase := range testCases { + gotNewPath := trimSuffixAtMaxDepth(testCase.startPrefix, testCase.path, testCase.separator, testCase.maxDepth) + if testCase.expectedNewPath != gotNewPath { + t.Errorf("Test: %d, expected path %s, got %s", i+1, testCase.expectedNewPath, gotNewPath) + } + } +} + // 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 @@ -30,42 +233,50 @@ func TestFindMatch(t *testing.T) { } var basicTests = []testFind{ - // Basic name and path tests + // Name match tests - success cases. {"*.jpg", "carter.jpg", "name", true}, + {"console", "pkg/console/console.go", "name", true}, + {"console.go", "pkg/console/console.go", "name", true}, + {"*XA==", "I/enjoy/morning/walks/XA==", "name ", true}, + {"*parser", "/This/might/mess up./the/parser", "name", true}, + {"*LTIxNDc0ODM2NDgvLTE=", "What/A/Naughty/String/LTIxNDc0ODM2NDgvLTE=", "name", true}, + {"*", "/bla/bla/bla/ ", "name", true}, + + // Name match tests - failure cases. {"*.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}, - // Regexp based. + // Path match tests - success cases. + {"*/test/*", "bob/test/likes/cake", "path", true}, + {"*/test/*", "/test/bob/likes/cake", "path", true}, + + // Path match tests - failure cases. + {"*.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==", "XA==/Height/is/a/social/construct", "path", false}, + {"*W", "/Word//this/is a/trickyTest", "path", false}, + {"LTIxNDc0ODM2NDgvLTE=", "LTIxNDc0ODM2NDgvLTE=/I/Am/One/Baaaaad/String", "path", false}, + {"/", "funky/path/name", "path", false}, + + // Regexp based - success cases. {"^[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}, + + // Regexp based - failure cases. + {"^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", "testbucket.", "regex", false}, {`^(\d+\.){3}\d+$`, "192.168.x.x", "regex", false}, } diff --git a/cmd/watch-main.go b/cmd/watch-main.go index 161a5e77..6bd5e887 100644 --- a/cmd/watch-main.go +++ b/cmd/watch-main.go @@ -23,7 +23,6 @@ import ( "strings" "sync" "syscall" - "time" humanize "github.com/dustin/go-humanize" "github.com/fatih/color" @@ -152,7 +151,6 @@ func mainWatch(ctx *cli.Context) error { params := watchParams{ recursive: recursive, - accountID: fmt.Sprintf("%d", time.Now().Unix()), events: events, prefix: prefix, suffix: suffix, diff --git a/cmd/watch.go b/cmd/watch.go index 44cd3c8c..dffee52c 100644 --- a/cmd/watch.go +++ b/cmd/watch.go @@ -17,7 +17,6 @@ package cmd import ( - "fmt" "sync" "time" @@ -53,7 +52,6 @@ type EventInfo struct { } type watchParams struct { - accountID string prefix string suffix string events []string @@ -148,7 +146,6 @@ func (w *Watcher) Join(client Client, recursive bool) *probe.Error { wo, err := client.Watch(watchParams{ recursive: recursive, events: []string{"put", "delete"}, - accountID: fmt.Sprintf("%d", w.sessionStartTime.Unix()), }) if err != nil { return err