Merge pull request #1331 from krishnasrinivas/diff-prefix-recursive-fix

diff, mirror always take directories as arguments and always does rec…
This commit is contained in:
Harshavardhana
2015-11-15 22:34:00 -08:00
5 changed files with 111 additions and 283 deletions
+106 -48
View File
@@ -17,17 +17,21 @@
package main
import (
"encoding/json"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
)
// Compute differences between two files or folders.
var diffCmd = cli.Command{
Name: "diff",
Usage: "Compute differences between two files or folders.",
Usage: "Compute differences between two folders.",
Description: "NOTE: This command *DOES NOT* check for content similarity, which means objects with same size, but different content will not be spotted.",
Action: mainDiff,
CustomHelpTemplate: `NAME:
@@ -37,14 +41,11 @@ USAGE:
mc {{.Name}} FIRST SECOND
EXAMPLES:
1. Compare foo.ogg on a local filesystem with bar.ogg on Amazon AWS cloud storage.
$ mc {{.Name}} foo.ogg https://bucketName.s3.amazonaws.com/jukebox/bar.ogg
2. Compare two different folders on a local filesystem with out recursion.
1. Compare two different folders on a local filesystem.
$ mc {{.Name}} ~/Photos /Media/Backup/Photos
2. Compare two different folders recursively.
$ mc {{.Name}} ~/Photos/... https://bucketName.s3.amazonaws.com/Photos
2. Compare a local folder with a folder on cloud storage.
$ mc {{.Name}} ~/Photos https://s3.amazonaws.com/MyBucket/Photos
`,
}
@@ -57,53 +58,96 @@ func checkDiffSyntax(ctx *cli.Context) {
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
}
if isURLRecursive(ctx.Args().Last()) {
fatalIf(errInvalidArgument().Trace(), "Second argument ‘"+ctx.Args().Last()+"’ cannot be recursive.")
}
// diffMessage json container for diff messages
type diffMessage struct {
FirstURL string `json:"first"`
SecondURL string `json:"second"`
Diff string `json:"diff"`
Error *probe.Error `json:"error,omitempty"`
}
// String colorized diff message
func (d diffMessage) String() string {
msg := ""
switch d.Diff {
case "only-in-first":
msg = console.Colorize("DiffMessage",
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
case "type":
msg = console.Colorize("DiffMessage",
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffType", " - differ in type.")
case "size":
msg = console.Colorize("DiffMessage",
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffSize", " - differ in size.")
default:
fatalIf(errDummy().Trace(),
"Unhandled difference between ‘"+d.FirstURL+"’ and ‘"+d.SecondURL+"’.")
}
return msg
}
// JSON jsonified diff message
func (d diffMessage) JSON() string {
diffJSONBytes, err := json.Marshal(d)
fatalIf(probe.NewError(err),
"Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+d.Diff+"’.")
return string(diffJSONBytes)
}
// doDiffMain runs the diff.
func doDiffMain(firstURL, secondURL string, recursive bool) <-chan diffMessage {
func doDiffMain(firstURL, secondURL string) <-chan diffMessage {
ch := make(chan diffMessage, 10000)
go doDiffInRoutine(firstURL, secondURL, recursive, ch)
return ch
}
go func() {
defer close(ch)
// source and targets are always directories
sourceSeparator := string(client.NewURL(firstURL).Separator)
if !strings.HasSuffix(firstURL, sourceSeparator) {
firstURL = firstURL + sourceSeparator
}
targetSeparator := string(client.NewURL(secondURL).Separator)
if !strings.HasSuffix(secondURL, targetSeparator) {
secondURL = secondURL + targetSeparator
}
// doDiffInRoutine run diff in a go-routine sending back messages over all channel.
func doDiffInRoutine(firstURL, secondURL string, recursive bool, ch chan diffMessage) {
defer close(ch)
_, firstContent, err := url2Stat(firstURL)
if err != nil {
ch <- diffMessage{
Error: err.Trace(firstURL),
firstClient, err := url2Client(firstURL)
if err != nil {
ch <- diffMessage{Error: err.Trace(firstURL)}
return
}
return
}
_, secondContent, err := url2Stat(secondURL)
if err != nil {
ch <- diffMessage{
Error: err.Trace(secondURL),
difference, err := objectDifferenceFactory(secondURL)
if err != nil {
ch <- diffMessage{Error: err.Trace(secondURL)}
return
}
return
}
// if first target is a folder and second target is not then throw a type mismatch
if firstContent.Type.IsDir() && !secondContent.Type.IsDir() {
ch <- diffMessage{
FirstURL: firstContent.URL.String(),
SecondURL: secondContent.URL.String(),
Diff: "type",
isRecursive := true
for sourceContent := range firstClient.List(isRecursive, false) {
if sourceContent.Err != nil {
ch <- diffMessage{Error: sourceContent.Err.Trace()}
continue
}
if sourceContent.Content.Type.IsDir() {
continue
}
suffix := strings.TrimPrefix(sourceContent.Content.URL.String(), firstURL)
differ, err := difference(suffix, sourceContent.Content.Type, sourceContent.Content.Size)
if err != nil {
ch <- diffMessage{Error: err.Trace()}
continue
}
if differ == differNone {
continue
}
ch <- diffMessage{
FirstURL: sourceContent.Content.URL.String(),
SecondURL: urlJoinPath(secondURL, suffix),
Diff: differ,
}
}
return
}
// if first target is a regular file, handle basic cases
if firstContent.Type.IsRegular() {
diffMsg := diffObjects(firstContent, secondContent)
if diffMsg != nil {
ch <- *diffMsg
}
return
}
diffFolders(firstURL, secondURL, recursive, ch)
}()
return ch
}
// mainDiff main for 'diff'.
@@ -123,15 +167,29 @@ func mainDiff(ctx *cli.Context) {
firstURL := getAliasURL(firstArg, config.Aliases)
secondURL := getAliasURL(secondArg, config.Aliases)
newFirstURL := stripRecursiveURL(firstURL)
for diff := range doDiffMain(newFirstURL, secondURL, isURLRecursive(firstURL)) {
_, firstContent, err := url2Stat(firstURL)
if err != nil {
fatalIf(err.Trace(), fmt.Sprintf("Unable to stat '%s'", firstURL))
}
if !firstContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("‘%s’ is not a folder", firstURL))
}
_, secondContent, err := url2Stat(secondURL)
if err != nil {
fatalIf(err.Trace(), fmt.Sprintf("Unable to stat '%s'", secondURL))
}
if !secondContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("‘%s’ is not a folder", secondURL))
}
for diff := range doDiffMain(firstURL, secondURL) {
if diff.Error != nil {
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
if !globalQuietFlag && !globalJSONFlag {
console.Eraseline()
}
}
fatalIf(diff.Error.Trace(newFirstURL, secondURL), "Failed to diff ‘"+firstURL+"’ and ‘"+secondURL+"’.")
fatalIf(diff.Error.Trace(firstURL, secondURL), "Failed to diff ‘"+firstURL+"’ and ‘"+secondURL+"’.")
printMsg(diff)
}
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
-175
View File
@@ -1,175 +0,0 @@
/*
* Minio Client (C) 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 (
"encoding/json"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
)
//
// NOTE: All the parse rules should reduced to 1: Diff(First, Second).
//
// Valid cases
// =======================
// 1: diff(f, f) -> diff(f, f)
// 2: diff(f, d) -> diff(f, d/f) -> 1
// 3. diff(d1, d2) -> []diff(d1/f, d2/f) -> []1
// 4: diff(d1..., d2) -> []diff(d1/f, d2/f) -> []1
//
// Invalid cases
// =======================
// 1. diff(d1..., d2/f) -> INVALID
// 2. diff(d1..., d2...) -> INVALID
//
// diffMessage json container for diff messages
type diffMessage struct {
FirstURL string `json:"first"`
SecondURL string `json:"second"`
Diff string `json:"diff"`
Error *probe.Error `json:"error,omitempty"`
}
// String colorized diff message
func (d diffMessage) String() string {
msg := ""
switch d.Diff {
case "only-in-first":
msg = console.Colorize("DiffMessage",
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
case "type":
msg = console.Colorize("DiffMessage",
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffType", " - differ in type.")
case "size":
msg = console.Colorize("DiffMessage",
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffSize", " - differ in size.")
default:
fatalIf(errDummy().Trace(),
"Unhandled difference between ‘"+d.FirstURL+"’ and ‘"+d.SecondURL+"’.")
}
return msg
}
// JSON jsonified diff message
func (d diffMessage) JSON() string {
diffJSONBytes, err := json.Marshal(d)
fatalIf(probe.NewError(err),
"Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+d.Diff+"’.")
return string(diffJSONBytes)
}
// diffObjects - diff two incoming object contents, this is the most basic types.
//
// 1: diff(f, f) -> diff(f, f) -> VALID
// 2: diff(f, d) -> diff(f, d/f) -> VALID
func diffObjects(firstContent, secondContent *client.Content) *diffMessage {
if firstContent.URL.String() == secondContent.URL.String() {
return nil
}
if firstContent.Type.IsRegular() && secondContent.Type.IsRegular() {
if firstContent.Size != secondContent.Size {
return &diffMessage{
FirstURL: firstContent.URL.String(),
SecondURL: secondContent.URL.String(),
Diff: "size",
}
}
return nil
}
if firstContent.Type.IsRegular() && secondContent.Type.IsDir() {
newSecondURLStr := urlJoinPath(secondContent.URL.String(), firstContent.URL.String())
_, newSecondContent, err := url2Stat(newSecondURLStr)
if err != nil {
return &diffMessage{
FirstURL: firstContent.URL.String(),
SecondURL: newSecondURLStr,
Diff: "only-in-first",
}
}
if firstContent.Size != newSecondContent.Size {
return &diffMessage{
FirstURL: firstContent.URL.String(),
SecondURL: newSecondContent.URL.String(),
Diff: "size",
}
}
return nil
}
if firstContent.Type.IsRegular() && !secondContent.Type.IsRegular() {
return &diffMessage{
FirstURL: firstContent.URL.String(),
SecondURL: secondContent.URL.String(),
Diff: "type",
}
}
return nil
}
// calculate difference between two folders
// recursive - indicates whether the difference should be calculated at the top
// level or if it should recurse into sub-directories
func diffFolders(sourceURL string, targetURL string, recursive bool, outCh chan<- diffMessage) {
// source and targets are always directories
sourceSeparator := string(client.NewURL(sourceURL).Separator)
if !strings.HasSuffix(sourceURL, sourceSeparator) {
sourceURL = sourceURL + sourceSeparator
}
targetSeparator := string(client.NewURL(targetURL).Separator)
if !strings.HasSuffix(targetURL, targetSeparator) {
targetURL = targetURL + targetSeparator
}
sourceClient, err := url2Client(sourceURL)
if err != nil {
outCh <- diffMessage{Error: err.Trace(sourceURL)}
return
}
difference, err := objectDifferenceFactory(targetURL, recursive)
if err != nil {
outCh <- diffMessage{Error: err.Trace(targetURL)}
return
}
for sourceContent := range sourceClient.List(recursive, false) {
if sourceContent.Err != nil {
outCh <- diffMessage{Error: sourceContent.Err.Trace()}
continue
}
if sourceContent.Content.Type.IsDir() {
continue
}
suffix := strings.TrimPrefix(sourceContent.Content.URL.String(), sourceURL)
differ, err := difference(suffix, sourceContent.Content.Type, sourceContent.Content.Size)
if err != nil {
outCh <- diffMessage{Error: err.Trace()}
continue
}
if differ == differNone {
continue
}
outCh <- diffMessage{
FirstURL: sourceContent.Content.URL.String(),
SecondURL: urlJoinPath(targetURL, suffix),
Diff: differ,
}
}
}
+1 -47
View File
@@ -28,33 +28,6 @@ import (
. "gopkg.in/check.v1"
)
func (s *TestSuite) TestDiffObjects(c *C) {
/// filesystem
root1, e := ioutil.TempDir(os.TempDir(), "cmd-")
c.Assert(e, IsNil)
defer os.RemoveAll(root1)
root2, e := ioutil.TempDir(os.TempDir(), "cmd-")
c.Assert(e, IsNil)
defer os.RemoveAll(root2)
objectPath1 := filepath.Join(root1, "object1")
data := "hello"
dataLen := len(data)
err := putTarget(objectPath1, int64(dataLen), bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
objectPath2 := filepath.Join(root2, "object1")
data = "hello"
dataLen = len(data)
err = putTarget(objectPath2, int64(dataLen), bytes.NewReader([]byte(data)))
c.Assert(err, IsNil)
for diff := range doDiffMain(objectPath1, objectPath2, false) {
c.Assert(diff.Error, IsNil)
}
}
func (s *TestSuite) TestDiffDirs(c *C) {
/// filesystem
root1, e := ioutil.TempDir(os.TempDir(), "cmd-")
@@ -94,12 +67,7 @@ func (s *TestSuite) TestDiffDirs(c *C) {
c.Assert(err, IsNil)
}
// non-recursive
for diff := range doDiffMain(root1, root2, false) {
c.Assert(diff.Error, IsNil)
}
// recursive
for diff := range doDiffMain(root1, root2, true) {
for diff := range doDiffMain(root1, root2) {
c.Assert(diff.Error, IsNil)
}
}
@@ -111,18 +79,4 @@ func (s *TestSuite) TestDiffContext(c *C) {
// reset back
console.IsExited = false
err = app.Run([]string{os.Args[0], "diff", server.URL + "/bucket...", server.URL + "/bucket"})
c.Assert(err, IsNil)
c.Assert(console.IsExited, Equals, false)
// reset back
console.IsExited = false
err = app.Run([]string{os.Args[0], "diff", server.URL + "/invalid", server.URL + "/invalid..."})
c.Assert(err, IsNil)
c.Assert(console.IsExited, Equals, true)
// reset back
console.IsExited = false
}
+3 -2
View File
@@ -38,13 +38,14 @@ const (
// objectDifferenceFactory returns objectDifference function to check for difference
// between sourceURL and targetURL
// for usage reference check diff and mirror commands
func objectDifferenceFactory(targetURL string, recursive bool) (objectDifference, *probe.Error) {
func objectDifferenceFactory(targetURL string) (objectDifference, *probe.Error) {
clnt, err := url2Client(targetURL)
if err != nil {
return nil, err.Trace(targetURL)
}
isIncomplete := false
ch := clnt.List(recursive, isIncomplete)
isRecursive := true
ch := clnt.List(isRecursive, isIncomplete)
current := targetURL
reachedEOF := false
ok := false
+1 -11
View File
@@ -18,7 +18,6 @@ package main
import (
"fmt"
"path/filepath"
"strings"
"github.com/minio/cli"
@@ -101,16 +100,10 @@ func checkMirrorSyntax(ctx *cli.Context) {
func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan<- mirrorURLs) {
defer close(mirrorURLsCh)
sourceURL = stripRecursiveURL(sourceURL)
sourceBaseDir := ""
// source and targets are always directories
sourceSeparator := string(client.NewURL(sourceURL).Separator)
if !strings.HasSuffix(sourceURL, sourceSeparator) {
// if source is dir1/dir2/dir3 and target is dir4/dir5/dir6 then we should copy dir3/* into dir4/dir5/dir6/dir3/
// if source is dir1/dir2/dir3/ and target is dir4/dir5/dir6 then we should copy dir3/* into dir4/dir5/dir6/
// sourceBaseDir is used later for this purpose
sourceBaseDir = filepath.Base(sourceURL)
sourceURL = sourceURL + sourceSeparator
}
for i, url := range targetURLs {
@@ -125,7 +118,7 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan
for i := range targetURLs {
var err *probe.Error
objectDifferenceArray[i], err = objectDifferenceFactory(targetURLs[i], true)
objectDifferenceArray[i], err = objectDifferenceFactory(targetURLs[i])
if err != nil {
mirrorURLsCh <- mirrorURLs{Error: err.Trace()}
return
@@ -147,9 +140,6 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan
continue
}
suffix := strings.TrimPrefix(sourceContent.Content.URL.String(), sourceURL)
if sourceBaseDir != "" {
suffix = urlJoinPath(sourceBaseDir, suffix)
}
targetContents := []*client.Content{}
for i, difference := range objectDifferenceArray {
differ, err := difference(suffix, sourceContent.Content.Type, sourceContent.Content.Size)