From 726780c79d644144f4e7222975454a9583004547 Mon Sep 17 00:00:00 2001 From: "Anand Babu (AB) Periasamy" Date: Mon, 18 May 2015 19:57:06 -0700 Subject: [PATCH] diff command for mc --- cmd-diff.go | 213 +++++++++++++++++++++++++++++++++++++ cmd-ls.go | 15 --- cmd-options.go | 152 +++++++++++++++----------- common-methods.go | 20 ++++ pkg/client/fs/fs-errors.go | 6 +- pkg/client/fs/fs.go | 35 ++++-- 6 files changed, 353 insertions(+), 88 deletions(-) create mode 100644 cmd-diff.go diff --git a/cmd-diff.go b/cmd-diff.go new file mode 100644 index 00000000..1ee00e2f --- /dev/null +++ b/cmd-diff.go @@ -0,0 +1,213 @@ +/* + * 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 ( + "path/filepath" + + "github.com/minio/cli" + "github.com/minio/mc/pkg/client" + "github.com/minio/mc/pkg/console" + "github.com/minio/minio/pkg/iodine" +) + +// runDiffCmd - is a handler for mc diff command +func runDiffCmd(ctx *cli.Context) { + if len(ctx.Args()) != 2 || ctx.Args().First() == "help" { + cli.ShowCommandHelpAndExit(ctx, "diff", 1) // last argument is exit code + } + if !isMcConfigExist() { + console.Fatalln("\"mc\" is not configured. Please run \"mc config generate\".") + } + config, err := getMcConfig() + if err != nil { + console.Fatalf("Unable to read config file [%s]. Reason: [%s].\n", mustGetMcConfigPath(), iodine.ToError(err)) + } + + firstURL := ctx.Args().First() + secondURL := ctx.Args()[1] + + firstURL, err = getExpandedURL(firstURL, config.Aliases) + if err != nil { + switch iodine.ToError(err).(type) { + case errUnsupportedScheme: + console.Fatalf("Unknown type of URL [%s].\n", firstURL) + default: + console.Fatalf("Unable to parse argument [%s]. Reason: [%s].\n", firstURL, iodine.ToError(err)) + } + } + + _, err = getHostConfig(firstURL) + if err != nil { + console.Fatalf("Unable to read host configuration for [%s] from config file [%s]. Reason: [%s].\n", + firstURL, mustGetMcConfigPath(), iodine.ToError(err)) + } + + _, err = getHostConfig(secondURL) + if err != nil { + console.Fatalf("Unable to read host configuration for [%s] from config file [%s]. Reason: [%s].\n", + secondURL, mustGetMcConfigPath(), iodine.ToError(err)) + } + + secondURL, err = getExpandedURL(secondURL, config.Aliases) + if err != nil { + switch iodine.ToError(err).(type) { + case errUnsupportedScheme: + console.Fatalf("Unknown type of URL [%s].\n", secondURL) + default: + console.Fatalf("Unable to parse argument [%s]. Reason: [%s].\n", secondURL, iodine.ToError(err)) + } + } + + doDiffCmd(firstURL, secondURL) +} + +// urlJoinPath - Join a path to existing URL +func urlJoinPath(urlStr string, path string) (newURLStr string, err error) { + u, err := client.Parse(urlStr) + if err != nil { + return "", iodine.New(err, nil) + } + + u.Path = filepath.Join(u.Path, path) + newURLStr = u.String() + return newURLStr, nil +} + +// doDiffCmd - Execute the diff command +func doDiffCmd(firstURL string, secondURL string) { + _, firstContent, err := URL2Stat(firstURL) + if err != nil { + console.Fatalf("Failed to stat ‘%s’. Reason: [%s].\n", firstURL, iodine.ToError(err)) + } + + _, secondContent, err := URL2Stat(secondURL) + if err != nil { + console.Fatalf("Failed to stat ‘%s’. Reason: [%s].\n", secondURL, iodine.ToError(err)) + } + + if firstContent.Type.IsRegular() { + if !secondContent.Type.IsRegular() { + console.Infof("‘%s’ and ‘%s’ differs in type.\n", firstURL, secondURL) + return + } + doDiffCmdObjects(firstURL, secondURL) + return + } + + if firstContent.Type.IsDir() { + if !secondContent.Type.IsDir() { + console.Infof("‘%s’ and ‘%s’ differs in type.\n", firstURL, secondURL) + return + } + doDiffCmdDirs(firstURL, secondURL) + return + } + + console.Fatalf("‘%s’ is of unknown type.\n", firstURL) +} + +// doDiffCmdObjects - Diff two object URLs +func doDiffCmdObjects(firstURL string, secondURL string) { + if firstURL == secondURL { // kind of lame :p + return + } + _, firstContent, err := URL2Stat(firstURL) + if err != nil { + console.Fatalf("Failed to stat ‘%s’. Reason: [%s].\n", firstURL, iodine.ToError(err)) + } + + _, secondContent, err := URL2Stat(secondURL) + if err != nil { + console.Fatalf("Failed to stat ‘%s’. Reason: [%s].\n", secondURL, iodine.ToError(err)) + } + + if firstContent.Type.IsRegular() { + if !secondContent.Type.IsRegular() { + console.Infof("‘%s’ and ‘%s’ differs in type.\n", firstURL, secondURL) + return + } + } else { + console.Fatalf("‘%s’ is not an object. Please report this bug with ‘--debug’ option\n.", firstURL) + } + + if firstContent.Size != secondContent.Size { + console.Infof("‘%s’ and ‘%s’ differs in size.\n", firstURL, secondURL) + } +} + +// doDiffCmdDirs - Diff two Dir URLs +func doDiffCmdDirs(firstURL string, secondURL string) { + firstClnt, firstContent, err := URL2Stat(firstURL) + if err != nil { + console.Fatalf("Failed to stat ‘%s’. Reason: [%s].\n", firstURL, iodine.ToError(err)) + } + + _, secondContent, err := URL2Stat(secondURL) + if err != nil { + console.Fatalf("Failed to stat ‘%s’. Reason: [%s].\n", secondURL, iodine.ToError(err)) + } + + if firstContent.Type.IsDir() { + if !secondContent.Type.IsDir() { + console.Infof("‘%s’ and ‘%s’ differs in type.\n", firstURL, secondURL) + return + } + } else { + console.Fatalf("‘%s’ is not a directory. Please report this bug with ‘--debug’ option\n.", firstURL) + } + + for contentCh := range firstClnt.List() { + if contentCh.Err != nil { + console.Fatalf("Failed to list ‘%s’. Reason: [%s].\n", firstURL, iodine.ToError(contentCh.Err)) + } + + newFirstURL, err := urlJoinPath(firstURL, contentCh.Content.Name) + if err != nil { + console.Fatalf("Unable to construct new URL from ‘%s’ using ‘%s’. Reason: [%s].\n", firstURL, contentCh.Content.Name, iodine.ToError(err)) + } + + newSecondURL, err := urlJoinPath(secondURL, contentCh.Content.Name) + if err != nil { + console.Fatalf("Unable to construct new URL from ‘%s’ using ‘%s’. Reason: [%s].\n", secondURL, contentCh.Content.Name, iodine.ToError(err)) + } + + _, newFirstContent, err := URL2Stat(newFirstURL) + if err != nil { + console.Fatalf("Failed to stat ‘%s’. Reason: [%s].\n", newFirstURL, iodine.ToError(err)) + } + + _, newSecondContent, err := URL2Stat(newSecondURL) + if err != nil { + console.Infof("‘%s’ only in ‘%s’.\n", filepath.Base(newFirstContent.Name), firstURL) + continue + } + + if newFirstContent.Type.IsDir() { + if !newSecondContent.Type.IsDir() { + console.Infof("‘%s’ and ‘%s’ differs in type.\n", newFirstURL, newSecondURL) + continue + } + } else if newFirstContent.Type.IsRegular() { + if !newSecondContent.Type.IsRegular() { + console.Infof("‘%s’ and ‘%s’ differs in type.\n", newFirstURL, newSecondURL) + continue + } + doDiffCmdObjects(newFirstURL, newSecondURL) + } + } // End of for-loop +} diff --git a/cmd-ls.go b/cmd-ls.go index be7764fc..6be55772 100644 --- a/cmd-ls.go +++ b/cmd-ls.go @@ -17,9 +17,6 @@ package main import ( - "fmt" - "time" - "github.com/minio/cli" "github.com/minio/mc/pkg/console" "github.com/minio/minio/pkg/iodine" @@ -88,12 +85,6 @@ func doListCmd(targetURL string, targetConfig *hostConfig, debug bool) error { return iodine.New(err, map[string]string{"Target": targetURL}) } err = doList(clnt, targetURL) - for i := 0; i < globalMaxRetryFlag && err != nil && isValidRetry(err); i++ { - fmt.Println(console.Retry("Retrying ... %d", i)) - // Progressively longer delays - time.Sleep(time.Duration(i*i) * time.Second) - err = doList(clnt, targetURL) - } if err != nil { return iodine.New(err, nil) } @@ -107,12 +98,6 @@ func doListRecursiveCmd(targetURL string, targetConfig *hostConfig, debug bool) return iodine.New(err, map[string]string{"Target": targetURL}) } err = doListRecursive(clnt, targetURL) - for i := 0; i < globalMaxRetryFlag && err != nil && isValidRetry(err); i++ { - fmt.Println(console.Retry("Retrying ... %d", i)) - // Progressively longer delays - time.Sleep(time.Duration(i*i) * time.Second) - err = doListRecursive(clnt, targetURL) - } if err != nil { return iodine.New(err, nil) } diff --git a/cmd-options.go b/cmd-options.go index 4b4a4e9f..c3d1a19a 100644 --- a/cmd-options.go +++ b/cmd-options.go @@ -25,12 +25,11 @@ import ( ) // List of commands -var ( - accessCmd = cli.Command{ - Name: "access", - Usage: "Set permissions [public, private, readonly] for buckets and folders.", - Action: runAccessCmd, - CustomHelpTemplate: `Name: +var accessCmd = cli.Command{ + Name: "access", + Usage: "Set permissions [public, private, readonly] for buckets and folders.", + Action: runAccessCmd, + CustomHelpTemplate: `Name: mc {{.Name}} - {{.Usage}} USAGE: @@ -58,12 +57,13 @@ EXAMPLES: $ mc {{.Name}} public /shared/Music `, - } - catCmd = cli.Command{ - Name: "cat", - Usage: "Concantenate objects or files to standard output", - Action: runCatCmd, - CustomHelpTemplate: `NAME: +} + +var catCmd = cli.Command{ + Name: "cat", + Usage: "Concantenate objects or files to standard output", + Action: runCatCmd, + CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} USAGE: @@ -86,12 +86,13 @@ EXAMPLES: 3. Concantenate multiple files from local filesystem to standard output. $ mc {{.Name}} *.txt > newfile.txt `, - } - cpCmd = cli.Command{ - Name: "cp", - Usage: "Copy objects and files from multiple sources single destination", - Action: runCopyCmd, - CustomHelpTemplate: `NAME: +} + +var cpCmd = cli.Command{ + Name: "cp", + Usage: "Copy objects and files from multiple sources single destination", + Action: runCopyCmd, + CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} USAGE: @@ -121,13 +122,13 @@ EXAMPLES: $ mc {{.Name}} 本語 s3:andoria/本語 `, - } +} - lsCmd = cli.Command{ - Name: "ls", - Usage: "List files and objects", - Action: runListCmd, - CustomHelpTemplate: `NAME: +var lsCmd = cli.Command{ + Name: "ls", + Usage: "List files and objects", + Action: runListCmd, + CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} USAGE: @@ -168,13 +169,13 @@ EXAMPLES: [2015-05-19 17:28:22 PDT] 41B 本語 `, - } +} - syncCmd = cli.Command{ - Name: "sync", - Usage: "Copies files and objects from single source to multiple destinations", - Action: runSyncCmd, - CustomHelpTemplate: `NAME: +var syncCmd = cli.Command{ + Name: "sync", + Usage: "Copies files and objects from single source to multiple destinations", + Action: runSyncCmd, + CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} USAGE: @@ -204,12 +205,41 @@ EXAMPLES: $ mc {{.Name}} 本語 s3:mylocaldocuments C:\backup\2014 play:backup `, - } - mbCmd = cli.Command{ - Name: "mb", - Usage: "Make a bucket or a folder", - Action: runMakeBucketCmd, - CustomHelpTemplate: `NAME: +} + +var diffCmd = cli.Command{ + Name: "diff", + Usage: "Quickly check if the two objects or directories differ", + Description: "NOTE: This command *DOES NOT* check for content match, which means objects with same size, but different content will not be spotted.", + Action: runDiffCmd, + CustomHelpTemplate: `NAME: + mc {{.Name}} - {{.Usage}} + +USAGE: + mc {{.Name}} FIRST SECOND {{if .Description}} + +DESCRIPTION: + {{.Description}}{{end}}{{if .Flags}} + +FLAGS: + {{range .Flags}}{{.}} + {{end}}{{ end }} + +EXAMPLES: + 1. Compare foo.ogg on a local filesystem with bar.ogg on Amazon AWS cloud storage. + $ mc {{.Name}} foo.ogg https://s3.amazonaws.com/jukebox/bar.ogg + + 2. Compare two different directories on a local filesystem. + $ mc {{.Name}} ~/Photos /Media/Backup/Photos + +`, +} + +var mbCmd = cli.Command{ + Name: "mb", + Usage: "Make a bucket or a folder", + Action: runMakeBucketCmd, + CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} USAGE: @@ -233,22 +263,23 @@ EXAMPLES: $ mc {{.Name}} https://s3.amazonaws.com/public-photo-store http://play.minio.io:9000/mongodb-backup `, - } - // Configure minio client - // - // ---- - // NOTE: that the configure command only writes values to the config file. - // It does not use any configuration values from the environment variables. - // - // One needs to edit configuration file manually, this is purposefully done - // so to avoid taking credentials over cli arguments. It is a security precaution - // ---- - // - configCmd = cli.Command{ - Name: "config", - Usage: "Generate configuration \"" + mustGetMcConfigPath() + "\" file.", - Action: runConfigCmd, - CustomHelpTemplate: `NAME: +} + +// Configure minio client +// +// ---- +// NOTE: that the configure command only writes values to the config file. +// It does not use any configuration values from the environment variables. +// +// One needs to edit configuration file manually, this is purposefully done +// so to avoid taking credentials over cli arguments. It is a security precaution +// ---- +// +var configCmd = cli.Command{ + Name: "config", + Usage: "Generate configuration \"" + mustGetMcConfigPath() + "\" file.", + Action: runConfigCmd, + CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} USAGE: @@ -263,12 +294,13 @@ EXAMPLES: $ mc config alias zek https://s3.amazonaws.com/ `, - } - updateCmd = cli.Command{ - Name: "update", - Usage: "Check for new software updates", - Action: runUpdateCmd, - CustomHelpTemplate: `Name: +} + +var updateCmd = cli.Command{ + Name: "update", + Usage: "Check for new software updates", + Action: runUpdateCmd, + CustomHelpTemplate: `Name: mc {{.Name}} - {{.Usage}} USAGE: @@ -279,8 +311,7 @@ EXAMPLES: $ mc update `, - } -) +} // Collection of mc commands currently supported are // @@ -299,6 +330,7 @@ var commands = []cli.Command{ lsCmd, cpCmd, syncCmd, + diffCmd, catCmd, mbCmd, accessCmd, diff --git a/common-methods.go b/common-methods.go index d79644e9..c04021a9 100644 --- a/common-methods.go +++ b/common-methods.go @@ -74,3 +74,23 @@ func getNewClient(urlStr string, auth *hostConfig, debug bool) (clnt client.Clie } return nil, iodine.New(errInvalidURL{url: urlStr}, nil) } + +// URL2Stat - Returns client, config and its stat Content from the URL +func URL2Stat(urlStr string) (client client.Client, content *client.Content, err error) { + config, err := getHostConfig(urlStr) + if err != nil { + return nil, nil, iodine.New(err, map[string]string{"URL": urlStr}) + } + + client, err = getNewClient(urlStr, config, globalDebugFlag) + if err != nil { + return nil, nil, iodine.New(err, map[string]string{"URL": urlStr}) + } + + content, err = client.Stat() + if err != nil { + return nil, nil, iodine.New(err, map[string]string{"URL": urlStr}) + } + + return client, content, nil +} diff --git a/pkg/client/fs/fs-errors.go b/pkg/client/fs/fs-errors.go index d2d22e72..1a442731 100644 --- a/pkg/client/fs/fs-errors.go +++ b/pkg/client/fs/fs-errors.go @@ -25,19 +25,19 @@ type GenericFileError struct { type NotFound GenericFileError func (e NotFound) Error() string { - return "Requested file [" + e.path + "] not found" + return "Requested file ‘" + e.path + "’ not found" } // ISFolder (EISDIR) - accessed file is a folder type ISFolder GenericFileError func (e ISFolder) Error() string { - return "Requested file [" + e.path + "] is a folder" + return "Requested file ‘" + e.path + "’ is a folder" } // NotFolder (ENOTDIR) - accessed file is not a folder type NotFolder GenericFileError func (e NotFolder) Error() string { - return "Requested file [" + e.path + "] is not a folder" + return "Requested file ‘" + e.path + "’ is not a folder" } diff --git a/pkg/client/fs/fs.go b/pkg/client/fs/fs.go index 448b4b51..923543e1 100644 --- a/pkg/client/fs/fs.go +++ b/pkg/client/fs/fs.go @@ -39,12 +39,6 @@ func New(path string) (client.Client, error) { return nil, iodine.New(errors.New("Path is empty."), nil) } - // Golang strips trailing / if you clean(..) or - // EvalSymlinks(..). Adding '.' prevents it from doing so. - if strings.HasSuffix(path, string(filepath.Separator)) { - path = path + string('.') - } - return &fsClient{path: path}, nil } @@ -52,8 +46,15 @@ func New(path string) (client.Client, error) { // fsStat - wrapper function to get file stat func (f *fsClient) fsStat() (os.FileInfo, error) { + fpath := f.path + // Golang strips trailing / if you clean(..) or + // EvalSymlinks(..). Adding '.' prevents it from doing so. + if strings.HasSuffix(fpath, string(filepath.Separator)) { + fpath = fpath + "." + } + // Resolve symlinks - fpath, err := filepath.EvalSymlinks(f.path) + fpath, err := filepath.EvalSymlinks(fpath) if os.IsNotExist(err) { return nil, iodine.New(NotFound{path: f.path}, nil) } @@ -93,10 +94,17 @@ func (f *fsClient) GetObject(offset, length uint64) (io.ReadCloser, uint64, erro return nil, 0, iodine.New(client.InvalidRange{Offset: offset}, nil) } + fpath := f.path + // Golang strips trailing / if you clean(..) or + // EvalSymlinks(..). Adding '.' prevents it from doing so. + if strings.HasSuffix(fpath, string(filepath.Separator)) { + fpath = fpath + "." + } + // Resolve symlinks - fpath, err := filepath.EvalSymlinks(f.path) + fpath, err = filepath.EvalSymlinks(fpath) if os.IsNotExist(err) { - return nil, 0, iodine.New(NotFound{path: fpath}, nil) + return nil, 0, iodine.New(NotFound{path: f.path}, nil) } if offset == 0 && length == 0 { return f.get(content) @@ -123,8 +131,15 @@ func (f *fsClient) List() <-chan client.ContentOnChannel { func (f *fsClient) list(contentCh chan client.ContentOnChannel) { defer close(contentCh) + fpath := f.path + // Golang strips trailing / if you clean(..) or + // EvalSymlinks(..). Adding '.' prevents it from doing so. + if strings.HasSuffix(fpath, string(filepath.Separator)) { + fpath = fpath + "." + } + // Resolve symlinks - fpath, err := filepath.EvalSymlinks(f.path) + fpath, err := filepath.EvalSymlinks(fpath) if os.IsNotExist(err) { contentCh <- client.ContentOnChannel{ Content: nil,