From 41637a2155d2a5189f4bc3cc3b617a9724b1403b Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 28 Apr 2015 00:33:18 -0700 Subject: [PATCH] Review comments, part of #451 --- aliases_test.go | 72 ------- cmd-access.go | 2 +- cmd-cat.go | 8 +- cmd-common.go | 2 + cmd-common_test.go | 83 --------- cmd-config.go | 13 +- cmd-config_test.go | 58 ------ cmd-cp.go | 66 +++---- cmd-ls.go | 100 +++------- cmd-mb.go | 4 +- cmd-options.go | 4 +- cmd-update.go | 15 +- cmd_test.go | 176 +++++++++++++++--- copy-url.go | 113 +++++++++++ copy.go | 9 +- ls.go | 87 +++++++++ ...ager_test.go => mock_clientmethods_test.go | 0 pkg/client/client.go | 2 +- pkg/client/fs/fs.go | 23 ++- pkg/client/fs/fs_test.go | 2 +- pkg/client/mocks/Client.go | 8 +- pkg/client/s3/bucket_list.go | 17 +- url.go | 89 +-------- 23 files changed, 486 insertions(+), 467 deletions(-) delete mode 100644 aliases_test.go delete mode 100644 cmd-common_test.go delete mode 100644 cmd-config_test.go create mode 100644 copy-url.go create mode 100644 ls.go rename mock_clientManager_test.go => mock_clientmethods_test.go (100%) diff --git a/aliases_test.go b/aliases_test.go deleted file mode 100644 index 2df06bf2..00000000 --- a/aliases_test.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Mini Copy (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 ( - "testing" - - . "github.com/minio-io/check" -) - -type MySuite struct{} - -func Test(t *testing.T) { TestingT(t) } - -var _ = Suite(&MySuite{}) - -func (s *MySuite) TestIsvalidAliasName(c *C) { - c.Check(isValidAliasName("helloWorld0"), Equals, true) - c.Check(isValidAliasName("h0SFD2k24Fdsa"), Equals, true) - c.Check(isValidAliasName("fdslka-4"), Equals, true) - c.Check(isValidAliasName("fdslka-"), Equals, true) - c.Check(isValidAliasName("helloWorld$"), Equals, false) - c.Check(isValidAliasName("h0SFD2k2#Fdsa"), Equals, false) - c.Check(isValidAliasName("0dslka-4"), Equals, false) - c.Check(isValidAliasName("-fdslka"), Equals, false) - c.Check(isValidAliasName("help"), Equals, false) -} - -func (s *MySuite) TestEmptyExpansions(c *C) { - // c.Skip("Test still being written") - url, err := aliasExpand("hello", nil) - c.Assert(url, Equals, "hello") - c.Assert(err, IsNil) - - url, err = aliasExpand("minio://hello", nil) - c.Assert(url, Equals, "minio://hello") - c.Assert(err, IsNil) - - url, err = aliasExpand("$#\\", nil) - c.Assert(url, Equals, "$#\\") - c.Assert(err, IsNil) - - url, err = aliasExpand("foo:bar", map[string]string{"foo": "http://foo"}) - c.Assert(url, Equals, "http://foo/bar") - c.Assert(err, IsNil) - - url, err = aliasExpand("myfoo:bar", nil) - c.Assert(url, Equals, "myfoo:bar") - c.Assert(err, IsNil) - - url, err = aliasExpand("", nil) - c.Assert(url, Equals, "") - c.Assert(err, IsNil) - - url, err = aliasExpand("hello", nil) - c.Assert(url, Equals, "hello") - c.Assert(err, IsNil) -} diff --git a/cmd-access.go b/cmd-access.go index 00a433bf..133f6cfd 100644 --- a/cmd-access.go +++ b/cmd-access.go @@ -1,5 +1,5 @@ /* - * Mini Copy, (C) 2014, 2015 Minio, Inc. + * Mini Copy, (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. diff --git a/cmd-cat.go b/cmd-cat.go index 10bb5e82..aad8b2aa 100644 --- a/cmd-cat.go +++ b/cmd-cat.go @@ -1,5 +1,5 @@ /* - * Mini Copy, (C) 2014, 2015 Minio, Inc. + * Mini Copy, (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. @@ -26,6 +26,10 @@ import ( "github.com/minio-io/minio/pkg/utils/log" ) +const ( + standardOutput = "/dev/stdout" +) + func runCatCmd(ctx *cli.Context) { if !ctx.Args().Present() || ctx.Args().First() == "help" { cli.ShowCommandHelpAndExit(ctx, "cat", 1) // last argument is exit code @@ -55,7 +59,7 @@ func runCatCmd(ctx *cli.Context) { log.Debug.Println(iodine.New(err, nil)) console.Fatalf("reading host config for URL [%s] failed with following reason: [%s]\n", sourceURLs, iodine.ToError(err)) } - humanReadable, err := doCatCmd(mcClientMethods{}, sourceURLConfigMap, "/dev/stdout", globalDebugFlag) + humanReadable, err := doCatCmd(mcClientMethods{}, sourceURLConfigMap, standardOutput, globalDebugFlag) if err != nil { log.Debug.Println(iodine.New(err, nil)) console.Fatalln(humanReadable) diff --git a/cmd-common.go b/cmd-common.go index ee47dd47..6c8a2b9d 100644 --- a/cmd-common.go +++ b/cmd-common.go @@ -39,6 +39,8 @@ func isValidRetry(err error) bool { } // DNSError, Network Operation error switch e := iodine.ToError(err).(type) { + case *net.AddrError: + return true case *net.DNSError: return true case *net.OpError: diff --git a/cmd-common_test.go b/cmd-common_test.go deleted file mode 100644 index bd84ac62..00000000 --- a/cmd-common_test.go +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Mini Copy (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 ( - "time" - - "github.com/cheggaaa/pb" - - "errors" - "net" - - . "github.com/minio-io/check" - "github.com/minio-io/minio/pkg/iodine" -) - -type CommonSuite struct{} - -type testAddr struct{} - -func (ta *testAddr) Network() string { - return ta.String() -} -func (ta *testAddr) Error() string { - return ta.String() -} -func (ta *testAddr) String() string { - return "testAddr" -} - -var _ = Suite(&CommonSuite{}) - -func (s *CommonSuite) TestStatusBar(c *C) { - bar := startBar(1024) - c.Assert(bar, Not(IsNil)) - c.Assert(bar.Units, Equals, pb.U_BYTES) - c.Assert(bar.RefreshRate, Equals, time.Millisecond*10) - c.Assert(bar.NotPrint, Equals, true) - c.Assert(bar.ShowSpeed, Equals, true) -} - -func (s *CommonSuite) TestIsValidRetry(c *C) { - opError := &net.OpError{ - Op: "read", - Net: "net", - Addr: &testAddr{}, - Err: errors.New("Op Error"), - } - c.Assert(isValidRetry(nil), Equals, false) - c.Assert(isValidRetry(errors.New("hello")), Equals, false) - c.Assert(isValidRetry(iodine.New(errors.New("hello"), nil)), Equals, false) - c.Assert(isValidRetry(&net.DNSError{}), Equals, true) - c.Assert(isValidRetry(iodine.New(&net.DNSError{}, nil)), Equals, true) - // op error read - c.Assert(isValidRetry(opError), Equals, true) - c.Assert(isValidRetry(iodine.New(opError, nil)), Equals, true) - // op error write - opError.Op = "write" - c.Assert(isValidRetry(opError), Equals, true) - c.Assert(isValidRetry(iodine.New(opError, nil)), Equals, true) - // op error dial - opError.Op = "dial" - c.Assert(isValidRetry(opError), Equals, true) - c.Assert(isValidRetry(iodine.New(opError, nil)), Equals, true) - // op error foo - opError.Op = "foo" - c.Assert(isValidRetry(opError), Equals, false) - c.Assert(isValidRetry(iodine.New(opError, nil)), Equals, false) -} diff --git a/cmd-config.go b/cmd-config.go index 52d7827a..3116af1f 100644 --- a/cmd-config.go +++ b/cmd-config.go @@ -42,6 +42,7 @@ type configV1 struct { Hosts map[string]*hostConfig } +// getMcConfigDir - construct minio client configuration directory func getMcConfigDir() (string, error) { u, err := user.Current() if err != nil { @@ -56,6 +57,7 @@ func getMcConfigDir() (string, error) { } } +// createMcConfigDir - create minio client configuration directory func createMcConfigDir() error { p, err := getMcConfigDir() if err != nil { @@ -68,6 +70,7 @@ func createMcConfigDir() error { return nil } +// getMcConfigPath - construct minio client configuration path func getMcConfigPath() (string, error) { dir, err := getMcConfigDir() if err != nil { @@ -76,12 +79,13 @@ func getMcConfigPath() (string, error) { return path.Join(dir, mcConfigFile), nil } +// mustGetMcConfigPath - similar to getMcConfigPath, ignores errors func mustGetMcConfigPath() string { p, _ := getMcConfigPath() return p } -// getMcConfig returns the config +// getMcConfig - reads configuration file and returns config func getMcConfig() (config *configV1, err error) { if !isMcConfigExist() { return nil, iodine.New(errInvalidArgument{}, nil) @@ -113,7 +117,7 @@ func isMcConfigExist() bool { return true } -// writeConfig +// writeConfig - write configuration file func writeConfig(config quick.Config) error { err := createMcConfigDir() if err != nil { @@ -129,6 +133,7 @@ func writeConfig(config quick.Config) error { return nil } +// newConfigV1() - get new config version 1.0 func newConfigV1() *configV1 { conf := new(configV1) conf.Version = mcCurrentConfigVersion @@ -139,6 +144,7 @@ func newConfigV1() *configV1 { return conf } +// newConfig - get new config interface func newConfig() (config quick.Config) { conf := newConfigV1() s3HostConf := new(hostConfig) @@ -162,6 +168,7 @@ func newConfig() (config quick.Config) { return config } +// addAlias - add new aliases func addAlias(alias []string) (quick.Config, error) { if len(alias) < 2 { return nil, iodine.New(errInvalidArgument{}, nil) @@ -239,7 +246,7 @@ func doConfig(arg string, alias []string) (string, error) { case errConfigExists: return "Configuration file [" + configPath + "] already exists.", iodine.New(err, nil) case errInvalidArgument: - return "Incorrect usage, please use \"help\" ", iodine.New(err, nil) + return "Incorrect usage, please use \"mc config help\" ", iodine.New(err, nil) case errAliasExists: return "Alias [" + alias[0] + "] already exists", iodine.New(err, nil) case errInvalidAliasName: diff --git a/cmd-config_test.go b/cmd-config_test.go deleted file mode 100644 index a2794cea..00000000 --- a/cmd-config_test.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Mini Copy (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 ( - "os/user" - "path" - "runtime" - - . "github.com/minio-io/check" -) - -func mustGetMcConfigDir() string { - dir, _ := getMcConfigDir() - return dir -} - -func (s *MySuite) TestGetMcConfigDir(c *C) { - u, err := user.Current() - c.Assert(err, IsNil) - dir, err := getMcConfigDir() - c.Assert(err, IsNil) - if runtime.GOOS == "linux" { - c.Assert(dir, Equals, path.Join(u.HomeDir, ".mc/")) - } else if runtime.GOOS == "windows" { - c.Assert(dir, Equals, path.Join(u.HomeDir, "mc/")) - } else { - c.Fail() - } - c.Assert(mustGetMcConfigDir(), Equals, dir) -} - -func (s *MySuite) TestGetMcConfigPath(c *C) { - dir, err := getMcConfigPath() - c.Assert(err, IsNil) - if runtime.GOOS == "linux" { - c.Assert(dir, Equals, path.Join(mustGetMcConfigDir(), "config.json")) - } else if runtime.GOOS == "windows" { - c.Assert(dir, Equals, path.Join(mustGetMcConfigDir(), "config.json")) - } else { - c.Fail() - } - c.Assert(mustGetMcConfigPath(), Equals, dir) -} diff --git a/cmd-cp.go b/cmd-cp.go index 1e02e288..ca2b4c81 100644 --- a/cmd-cp.go +++ b/cmd-cp.go @@ -25,6 +25,39 @@ import ( "github.com/minio-io/minio/pkg/utils/log" ) +func runCopyCmd(ctx *cli.Context) { + if len(ctx.Args()) < 2 || ctx.Args().First() == "help" { + cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code + } + + config, err := getMcConfig() + if err != nil { + log.Debug.Println(iodine.New(err, nil)) + console.Fatalf("Unable to read config file [%s]. Reason: [%s].\n", mustGetMcConfigPath(), iodine.ToError(err)) + } + + // Convert arguments to URLs: expand alias, fix format... + urls, err := getURLs(ctx.Args(), config.Aliases) + if err != nil { + switch e := iodine.ToError(err).(type) { + case errUnsupportedScheme: + log.Debug.Println(iodine.New(err, nil)) + console.Fatalf("Unknown type of URL(s).\n") + default: + log.Debug.Println(iodine.New(err, nil)) + console.Fatalf("Unable to parse arguments. Reason: [%s].\n", e) + } + } + + methods := mcClientMethods{} + switch len(urls) { + case 2: + runCopyCmdSingleSource(methods, urls) + default: + runCopyCmdMultipleSources(methods, urls) + } +} + func runCopyCmdMultipleSources(methods clientMethods, urls []string) { sourceURLs := urls[:len(urls)-1] // All args are source except the last one targetURL := urls[len(urls)-1] // Last one is target @@ -83,36 +116,3 @@ func runCopyCmdSingleSource(methods clientMethods, urls []string) { } } - -func runCopyCmd(ctx *cli.Context) { - if len(ctx.Args()) < 2 || ctx.Args().First() == "help" { - cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code - } - - config, err := getMcConfig() - if err != nil { - log.Debug.Println(iodine.New(err, nil)) - console.Fatalf("Unable to read config file [%s]. Reason: [%s].\n", mustGetMcConfigPath(), iodine.ToError(err)) - } - - // Convert arguments to URLs: expand alias, fix format... - urls, err := getURLs(ctx.Args(), config.Aliases) - if err != nil { - switch e := iodine.ToError(err).(type) { - case errUnsupportedScheme: - log.Debug.Println(iodine.New(err, nil)) - console.Fatalf("Unknown type of URL(s).\n") - default: - log.Debug.Println(iodine.New(err, nil)) - console.Fatalf("Unable to parse arguments. Reason: [%s].\n", e) - } - } - - methods := mcClientMethods{} - switch len(urls) { - case 2: - runCopyCmdSingleSource(methods, urls) - default: - runCopyCmdMultipleSources(methods, urls) - } -} diff --git a/cmd-ls.go b/cmd-ls.go index a684c655..c0904282 100644 --- a/cmd-ls.go +++ b/cmd-ls.go @@ -18,72 +18,18 @@ package main import ( "fmt" - "os" "strings" "time" - "github.com/dustin/go-humanize" "github.com/minio-io/cli" - "github.com/minio-io/mc/pkg/client" "github.com/minio-io/mc/pkg/console" "github.com/minio-io/minio/pkg/iodine" "github.com/minio-io/minio/pkg/utils/log" ) -const ( - printDate = "2006-01-02 15:04:05 MST" -) - -// printItem prints item meta-data -func printItem(date time.Time, v int64, name string, fileType os.FileMode) { - fmt.Printf(console.Time("[%s] ", date.Local().Format(printDate))) - fmt.Printf(console.Size("%6s ", humanize.IBytes(uint64(v)))) - // just making it explicit - if fileType.IsDir() { - if strings.HasSuffix(name, "/") { - fmt.Println(console.Dir("%s", name)) - } else { - fmt.Println(console.Dir("%s/", name)) - } - } - if fileType.IsRegular() { - fmt.Println(console.File("%s", name)) - } -} - -func doListSingle(clnt client.Client, targetURL string) error { - var err error - for itemCh := range clnt.ListSingle() { - if itemCh.Err != nil { - err = itemCh.Err - break - } - printItem(itemCh.Item.Time, itemCh.Item.Size, itemCh.Item.Name, itemCh.Item.FileType) - } - if err != nil { - return iodine.New(err, map[string]string{"Target": targetURL}) - } - return nil -} - -func doList(clnt client.Client, targetURL string) error { - var err error - for itemCh := range clnt.List() { - if itemCh.Err != nil { - err = itemCh.Err - break - } - printItem(itemCh.Item.Time, itemCh.Item.Size, itemCh.Item.Name, itemCh.Item.FileType) - } - if err != nil { - return iodine.New(err, map[string]string{"Target": targetURL}) - } - return nil -} - -// runListCmd lists objects inside a bucket +// runListCmd - is a handler for mc ls command func runListCmd(ctx *cli.Context) { - if len(ctx.Args()) < 1 || ctx.Args().First() == "help" { + if !ctx.Args().Present() || ctx.Args().First() == "help" { cli.ShowCommandHelpAndExit(ctx, "ls", 1) // last argument is exit code } config, err := getMcConfig() @@ -116,14 +62,14 @@ func runListCmd(ctx *cli.Context) { if isURLRecursive(targetURL) { // if recursive strip off the "..." targetURL = strings.TrimSuffix(targetURL, recursiveSeparator) - err = doListCmd(mcClientMethods{}, targetURL, targetConfig, globalDebugFlag) + err = doListRecursiveCmd(mcClientMethods{}, targetURL, targetConfig, globalDebugFlag) err = iodine.New(err, nil) if err != nil { log.Debug.Println(err) console.Fatalf("Failed to list [%s]. Reason: [%s].\n", targetURL, iodine.ToError(err)) } } else { - err = doListSingleCmd(mcClientMethods{}, targetURL, targetConfig, globalDebugFlag) + err = doListCmd(mcClientMethods{}, targetURL, targetConfig, globalDebugFlag) if err != nil { if err != nil { log.Debug.Println(err) @@ -134,24 +80,7 @@ func runListCmd(ctx *cli.Context) { } } -func doListSingleCmd(methods clientMethods, targetURL string, targetConfig *hostConfig, debug bool) error { - clnt, err := methods.getNewClient(targetURL, targetConfig, globalDebugFlag) - if err != nil { - return iodine.New(err, map[string]string{"Target": targetURL}) - } - err = doListSingle(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 = doListSingle(clnt, targetURL) - } - if err != nil { - return iodine.New(err, nil) - } - return nil -} - +// doListCmd - func doListCmd(methods clientMethods, targetURL string, targetConfig *hostConfig, debug bool) error { clnt, err := methods.getNewClient(targetURL, targetConfig, globalDebugFlag) if err != nil { @@ -169,3 +98,22 @@ func doListCmd(methods clientMethods, targetURL string, targetConfig *hostConfig } return nil } + +// doListRecursiveCmd - +func doListRecursiveCmd(methods clientMethods, targetURL string, targetConfig *hostConfig, debug bool) error { + clnt, err := methods.getNewClient(targetURL, targetConfig, globalDebugFlag) + if err != nil { + 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) + } + return nil +} diff --git a/cmd-mb.go b/cmd-mb.go index c4437867..3f7d00e0 100644 --- a/cmd-mb.go +++ b/cmd-mb.go @@ -27,7 +27,7 @@ import ( "github.com/minio-io/minio/pkg/utils/log" ) -// doMakeBucketCmd creates a new bucket +// runMakeBucketCmd is the handler for mc mb command func runMakeBucketCmd(ctx *cli.Context) { if !ctx.Args().Present() || ctx.Args().First() == "help" { cli.ShowCommandHelpAndExit(ctx, "mb", 1) // last argument is exit code @@ -70,6 +70,7 @@ func runMakeBucketCmd(ctx *cli.Context) { } } +// doMakeBucketCmd - func doMakeBucketCmd(methods clientMethods, targetURL string, targetConfig *hostConfig, debug bool) (string, error) { var err error var clnt client.Client @@ -83,6 +84,7 @@ func doMakeBucketCmd(methods clientMethods, targetURL string, targetConfig *host return doMakeBucket(clnt, targetURL) } +// doMakeBucket - wrapper around PutBucket() API func doMakeBucket(clnt client.Client, targetURL string) (string, error) { err := clnt.PutBucket("") for i := 0; i < globalMaxRetryFlag && err != nil && isValidRetry(err); i++ { diff --git a/cmd-options.go b/cmd-options.go index 94859988..ff8e0150 100644 --- a/cmd-options.go +++ b/cmd-options.go @@ -167,7 +167,7 @@ EXAMPLES: mbCmd = cli.Command{ Name: "mb", - Usage: "Make a bucket", + Usage: "Make a directory or bucket", Action: runMakeBucketCmd, CustomHelpTemplate: `NAME: mc {{.Name}} - {{.Usage}} @@ -264,9 +264,9 @@ EXAMPLES: var commands = []cli.Command{ lsCmd, cpCmd, + catCmd, mbCmd, accessCmd, - catCmd, configCmd, updateCmd, // Add your new commands starting from here diff --git a/cmd-update.go b/cmd-update.go index 798c71b5..03a10cf5 100644 --- a/cmd-update.go +++ b/cmd-update.go @@ -40,7 +40,8 @@ type updateResults struct { Signature string } -func getReq(url string) (*http.Request, error) { +// getRequest - +func getRequest(url string) (*http.Request, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { msg := fmt.Sprintf("s3 client; invalid URL: %v", err) @@ -50,8 +51,9 @@ func getReq(url string) (*http.Request, error) { return req, nil } +// doUpdateCmd - func doUpdateCmd(ctx *cli.Context) { - req, err := getReq(mcUpdateURL) + req, err := getRequest(mcUpdateURL) if err != nil { log.Debug.Println(iodine.New(err, nil)) console.Fatalln("Unable to update:", mcUpdateURL) @@ -66,19 +68,18 @@ func doUpdateCmd(ctx *cli.Context) { log.Debug.Println(iodine.New(errors.New(msg), nil)) console.Fatalln(msg) } - ures := updateResults{} - err = json.NewDecoder(res.Body).Decode(&ures) + results := updateResults{} + err = json.NewDecoder(res.Body).Decode(&results) if err != nil { log.Debug.Println(iodine.New(err, nil)) console.Fatalln("Unable to parse JSON:", mcUpdateURL) } - latest, err := time.Parse(time.RFC3339Nano, ures.LatestBuild) + latest, err := time.Parse(time.RFC3339Nano, results.LatestBuild) if err != nil { log.Debug.Println(iodine.New(err, nil)) - console.Fatalln("Unable to parse update time:", ures.LatestBuild) + console.Fatalln("Unable to parse update time:", results.LatestBuild) } if latest.After(ctx.App.Compiled) { - // FIXME : find some proper versioning scheme here printUpdateNotify("new", "old") } } diff --git a/cmd_test.go b/cmd_test.go index 2892c3d1..e09ba31b 100644 --- a/cmd_test.go +++ b/cmd_test.go @@ -23,17 +23,25 @@ import ( "encoding/hex" "io" "io/ioutil" + "os/user" + "path" + "runtime" "sync" + "testing" "time" "errors" "net" + "github.com/cheggaaa/pb" . "github.com/minio-io/check" "github.com/minio-io/mc/pkg/client" clientMocks "github.com/minio-io/mc/pkg/client/mocks" + "github.com/minio-io/minio/pkg/iodine" ) +func Test(t *testing.T) { TestingT(t) } + type CmdTestSuite struct{} var _ = Suite(&CmdTestSuite{}) @@ -152,7 +160,7 @@ func (s *CmdTestSuite) TestCopyRecursive(c *C) { } } }() - cl1.On("List").Return(itemCh).Once() + cl1.On("ListRecursive").Return(itemCh).Once() sourceReader1 := ioutil.NopCloser(bytes.NewBufferString(data1)) sourceReader2 := ioutil.NopCloser(bytes.NewBufferString(data2)) methods.On("getSourceReader", sourceURL+"hello1", sourceConfig).Return(sourceReader1, dataLen1, etag1, nil).Once() @@ -173,6 +181,15 @@ func (s *CmdTestSuite) TestCopyRecursive(c *C) { cl1.AssertExpectations(c) } +type failClose struct{} + +func (c *failClose) Write(p []byte) (int, error) { + return len(p), nil +} +func (c *failClose) Close() error { + return errors.New("Expected Close Error") +} + func (s *CmdTestSuite) TestCopyCmdFailures(c *C) { methods := &MockclientMethods{} sourceURL, err := getURL("foo", nil) @@ -242,24 +259,15 @@ func (s *CmdTestSuite) TestCopyCmdFailures(c *C) { io.Copy(writer4, bytes.NewBufferString(data1)) wg.Done() }() - var failClose io.WriteCloser - failClose = &FailClose{} + var failclose io.WriteCloser + failclose = &failClose{} methods.On("getSourceReader", sourceURL, sourceConfig).Return(reader4, dataLen1, etag1, nil).Once() - methods.On("getTargetWriter", targetURL, targetConfig, etag1, dataLen1).Return(failClose, nil).Once() + methods.On("getTargetWriter", targetURL, targetConfig, etag1, dataLen1).Return(failclose, nil).Once() err = doCopySingleSource(methods, sourceURL, targetURL, sourceConfig, targetConfig) wg.Wait() c.Assert(err, Not(IsNil)) } -type FailClose struct{} - -func (c *FailClose) Write(p []byte) (int, error) { - return len(p), nil -} -func (c *FailClose) Close() error { - return errors.New("Expected Close Error") -} - func (s *CmdTestSuite) TestLsCmdWithBucket(c *C) { sourceURL, err := getURL("http://example.com/bucket1/", nil) c.Assert(err, IsNil) @@ -295,8 +303,8 @@ func (s *CmdTestSuite) TestLsCmdWithBucket(c *C) { } } }() - cl1.On("List").Return(itemCh).Once() - err = doListCmd(methods, sourceURL, sourceConfig, false) + cl1.On("ListRecursive").Return(itemCh).Once() + err = doListRecursiveCmd(methods, sourceURL, sourceConfig, false) c.Assert(err, IsNil) methods.AssertExpectations(c) @@ -339,8 +347,8 @@ func (s *CmdTestSuite) TestLsCmdWithFilePath(c *C) { } } }() - cl1.On("List").Return(itemCh).Once() - err = doListCmd(methods, sourceURL, sourceConfig, false) + cl1.On("ListRecursive").Return(itemCh).Once() + err = doListRecursiveCmd(methods, sourceURL, sourceConfig, false) c.Assert(err, IsNil) methods.AssertExpectations(c) @@ -376,8 +384,8 @@ func (s *CmdTestSuite) TestLsCmdListsBuckets(c *C) { } } }() - cl1.On("List").Return(itemCh).Once() - err = doListCmd(methods, sourceURL, sourceConfig, false) + cl1.On("ListRecursive").Return(itemCh).Once() + err = doListRecursiveCmd(methods, sourceURL, sourceConfig, false) c.Assert(err, IsNil) methods.AssertExpectations(c) @@ -485,7 +493,7 @@ func (s *CmdTestSuite) TestCatCmdObject(c *C) { cl1 := &clientMocks.Client{} cl2 := &clientMocks.Client{} - data1 := "hello1" + data1 := "hello world 1" binarySum1 := md5.Sum([]byte(data1)) etag1 := hex.EncodeToString(binarySum1[:]) dataLen1 := int64(len(data1)) @@ -538,7 +546,7 @@ func (s *CmdTestSuite) TestCatCmdFile(c *C) { cl1 := &clientMocks.Client{} cl2 := &clientMocks.Client{} - data1 := "hello1" + data1 := "hello world 1" binarySum1 := md5.Sum([]byte(data1)) etag1 := hex.EncodeToString(binarySum1[:]) dataLen1 := int64(len(data1)) @@ -581,3 +589,129 @@ func (s *CmdTestSuite) TestCatCmdFile(c *C) { cl1.AssertExpectations(c) cl2.AssertExpectations(c) } + +func mustGetMcConfigDir() string { + dir, _ := getMcConfigDir() + return dir +} + +func (s *CmdTestSuite) TestGetMcConfigDir(c *C) { + u, err := user.Current() + c.Assert(err, IsNil) + dir, err := getMcConfigDir() + c.Assert(err, IsNil) + if runtime.GOOS == "linux" { + c.Assert(dir, Equals, path.Join(u.HomeDir, ".mc/")) + } else if runtime.GOOS == "windows" { + c.Assert(dir, Equals, path.Join(u.HomeDir, "mc/")) + } else { + c.Fail() + } + c.Assert(mustGetMcConfigDir(), Equals, dir) +} + +func (s *CmdTestSuite) TestGetMcConfigPath(c *C) { + dir, err := getMcConfigPath() + c.Assert(err, IsNil) + if runtime.GOOS == "linux" { + c.Assert(dir, Equals, path.Join(mustGetMcConfigDir(), "config.json")) + } else if runtime.GOOS == "windows" { + c.Assert(dir, Equals, path.Join(mustGetMcConfigDir(), "config.json")) + } else { + c.Fail() + } + c.Assert(mustGetMcConfigPath(), Equals, dir) +} + +func (s *CmdTestSuite) TestIsvalidAliasName(c *C) { + c.Check(isValidAliasName("helloWorld0"), Equals, true) + c.Check(isValidAliasName("h0SFD2k24Fdsa"), Equals, true) + c.Check(isValidAliasName("fdslka-4"), Equals, true) + c.Check(isValidAliasName("fdslka-"), Equals, true) + c.Check(isValidAliasName("helloWorld$"), Equals, false) + c.Check(isValidAliasName("h0SFD2k2#Fdsa"), Equals, false) + c.Check(isValidAliasName("0dslka-4"), Equals, false) + c.Check(isValidAliasName("-fdslka"), Equals, false) + c.Check(isValidAliasName("help"), Equals, false) +} + +func (s *CmdTestSuite) TestEmptyExpansions(c *C) { + // c.Skip("Test still being written") + url, err := aliasExpand("hello", nil) + c.Assert(url, Equals, "hello") + c.Assert(err, IsNil) + + url, err = aliasExpand("minio://hello", nil) + c.Assert(url, Equals, "minio://hello") + c.Assert(err, IsNil) + + url, err = aliasExpand("$#\\", nil) + c.Assert(url, Equals, "$#\\") + c.Assert(err, IsNil) + + url, err = aliasExpand("foo:bar", map[string]string{"foo": "http://foo"}) + c.Assert(url, Equals, "http://foo/bar") + c.Assert(err, IsNil) + + url, err = aliasExpand("myfoo:bar", nil) + c.Assert(url, Equals, "myfoo:bar") + c.Assert(err, IsNil) + + url, err = aliasExpand("", nil) + c.Assert(url, Equals, "") + c.Assert(err, IsNil) + + url, err = aliasExpand("hello", nil) + c.Assert(url, Equals, "hello") + c.Assert(err, IsNil) +} + +type testAddr struct{} + +func (ta *testAddr) Network() string { + return ta.String() +} +func (ta *testAddr) Error() string { + return ta.String() +} +func (ta *testAddr) String() string { + return "testAddr" +} + +func (s *CmdTestSuite) TestStatusBar(c *C) { + bar := startBar(1024) + c.Assert(bar, Not(IsNil)) + c.Assert(bar.Units, Equals, pb.U_BYTES) + c.Assert(bar.RefreshRate, Equals, time.Millisecond*10) + c.Assert(bar.NotPrint, Equals, true) + c.Assert(bar.ShowSpeed, Equals, true) +} + +func (s *CmdTestSuite) TestIsValidRetry(c *C) { + opError := &net.OpError{ + Op: "read", + Net: "net", + Addr: &testAddr{}, + Err: errors.New("Op Error"), + } + c.Assert(isValidRetry(nil), Equals, false) + c.Assert(isValidRetry(errors.New("hello")), Equals, false) + c.Assert(isValidRetry(iodine.New(errors.New("hello"), nil)), Equals, false) + c.Assert(isValidRetry(&net.DNSError{}), Equals, true) + c.Assert(isValidRetry(iodine.New(&net.DNSError{}, nil)), Equals, true) + // op error read + c.Assert(isValidRetry(opError), Equals, true) + c.Assert(isValidRetry(iodine.New(opError, nil)), Equals, true) + // op error write + opError.Op = "write" + c.Assert(isValidRetry(opError), Equals, true) + c.Assert(isValidRetry(iodine.New(opError, nil)), Equals, true) + // op error dial + opError.Op = "dial" + c.Assert(isValidRetry(opError), Equals, true) + c.Assert(isValidRetry(iodine.New(opError, nil)), Equals, true) + // op error foo + opError.Op = "foo" + c.Assert(isValidRetry(opError), Equals, false) + c.Assert(isValidRetry(iodine.New(opError, nil)), Equals, false) +} diff --git a/copy-url.go b/copy-url.go new file mode 100644 index 00000000..507161b9 --- /dev/null +++ b/copy-url.go @@ -0,0 +1,113 @@ +/* + * Mini Copy (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 ( + "net/url" + "os" + "path/filepath" + "strings" + + "github.com/minio-io/mc/pkg/client" + "github.com/minio-io/minio/pkg/iodine" +) + +// getObjectKey - get object name from source url +func getObjectKey(sourceURL string) (objectName string) { + u, _ := url.Parse(sourceURL) + splits := strings.SplitN(u.Path, "/", 3) + if len(splits) == 3 { + return splits[2] + } + return "" +} + +// getNewURLRecursive - get new source and target URL for recursive copy +func getNewURLRecursive(sourceURL, targetURL, url string) (newSourceURL, newTargetURL string) { + switch client.GetType(sourceURL) { + case client.Object: + sourceURL = strings.TrimSuffix(sourceURL, getObjectKey(sourceURL)) + newSourceURL = strings.TrimSuffix(sourceURL, pathSeparator) + pathSeparator + url + newTargetURL = strings.TrimSuffix(targetURL, pathSeparator) + pathSeparator + url + case client.Filesystem: + newSourceURL = url + prefix := strings.TrimSuffix(sourceURL, pathSeparator) + pathSeparator + newTargetURL = strings.TrimSuffix(targetURL, pathSeparator) + pathSeparator + strings.TrimPrefix(url, prefix) + } + return newSourceURL, newTargetURL +} + +// getNewTargetURL - construct a new target URL object/fs alike +func getNewTargetURL(targetURL string, sourceURL string) (newTargetURL string, err error) { + switch client.GetType(targetURL) { + case client.Object: + return getNewTargetURLObject(targetURL, sourceURL) + case client.Filesystem: + return getNewTargetURLFilesystem(targetURL, sourceURL) + } + return "", iodine.New(errInvalidURL{url: targetURL}, nil) +} + +// getNewTargetURLObject - construct a new targetURL for object API +func getNewTargetURLObject(targetURL string, sourceURL string) (newTargetURL string, err error) { + if getObjectKey(targetURL) != "" { + return "", iodine.New(errIsNotBucket{path: targetURL}, nil) + } + switch client.GetType(sourceURL) { + case client.Filesystem: + _, s := filepath.Split(sourceURL) + if s == "" { + return "", iodine.New(errInvalidSource{path: sourceURL}, nil) + } + newTargetURL = strings.TrimSuffix(targetURL, pathSeparator) + pathSeparator + s + case client.Object: + object := getObjectKey(sourceURL) + if object == "" { + return "", iodine.New(errInvalidSource{path: sourceURL}, nil) + } + _, s := filepath.Split(object) + newTargetURL = filepath.Join(targetURL, s) + } + return newTargetURL, nil +} + +// getNewTargetURLFilesystem - construct a new targetURL for fs API +func getNewTargetURLFilesystem(targetURL string, sourceURL string) (newTargetURL string, err error) { + st, err := os.Stat(targetURL) + if err != nil { + return "", iodine.New(errIsNotDIR{path: targetURL}, nil) + } + if !st.IsDir() { + return "", iodine.New(errIsNotDIR{path: targetURL}, nil) + } + switch client.GetType(sourceURL) { + case client.Filesystem: + _, s := filepath.Split(sourceURL) + if s == "" { + return "", iodine.New(errInvalidSource{path: sourceURL}, nil) + } + newTargetURL = filepath.Join(targetURL, s) + case client.Object: + object := getObjectKey(sourceURL) + if object == "" { + return "", iodine.New(errInvalidSource{path: sourceURL}, nil) + } + _, s := filepath.Split(object) + newTargetURL = filepath.Join(targetURL, s) + } + return newTargetURL, nil +} diff --git a/copy.go b/copy.go index 50d7ead9..ecfdeff1 100644 --- a/copy.go +++ b/copy.go @@ -23,6 +23,9 @@ import ( "github.com/minio-io/minio/pkg/iodine" ) +/// Copy - related internal functions + +// doCopy func doCopy(methods clientMethods, reader io.ReadCloser, md5hex string, length int64, targetURL string, targetConfig *hostConfig) error { writeCloser, err := methods.getTargetWriter(targetURL, targetConfig, md5hex, length) if err != nil { @@ -55,6 +58,7 @@ func doCopy(methods clientMethods, reader io.ReadCloser, md5hex string, length i return nil } +// doCopySingleSource func doCopySingleSource(methods clientMethods, sourceURL, targetURL string, sourceConfig, targetConfig *hostConfig) error { reader, length, md5hex, err := methods.getSourceReader(sourceURL, sourceConfig) if err != nil { @@ -74,12 +78,13 @@ func doCopySingleSource(methods clientMethods, sourceURL, targetURL string, sour } } +// doCopySingleSourceRecursive func doCopySingleSourceRecursive(methods clientMethods, sourceURL, targetURL string, sourceConfig, targetConfig *hostConfig) error { sourceClnt, err := methods.getNewClient(sourceURL, sourceConfig, globalDebugFlag) if err != nil { return iodine.New(err, nil) } - for itemCh := range sourceClnt.List() { + for itemCh := range sourceClnt.ListRecursive() { if itemCh.Err != nil { continue } @@ -89,7 +94,7 @@ func doCopySingleSourceRecursive(methods clientMethods, sourceURL, targetURL str return nil } -// doCopyCmd copies objects into and from a bucket or between buckets +// doCopyMultipleSources - func doCopyMultipleSources(methods clientMethods, sourceURLConfigMap map[string]*hostConfig, targetURL string, targetConfig *hostConfig) error { sourceURLReaderMap, err := getSourceReaders(methods, sourceURLConfigMap) if err != nil { diff --git a/ls.go b/ls.go new file mode 100644 index 00000000..f7440693 --- /dev/null +++ b/ls.go @@ -0,0 +1,87 @@ +/* + * Mini Copy (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 ( + "fmt" + "os" + "strings" + "time" + + "github.com/dustin/go-humanize" + "github.com/minio-io/mc/pkg/client" + "github.com/minio-io/mc/pkg/console" + "github.com/minio-io/minio/pkg/iodine" +) + +/// LS - related internal functions + +// iso8601 date +const ( + printDate = "2006-01-02 15:04:05 MST" +) + +// printItem prints item meta-data +func printItem(date time.Time, v int64, name string, fileType os.FileMode) { + fmt.Printf(console.Time("[%s] ", date.Local().Format(printDate))) + fmt.Printf(console.Size("%6s ", humanize.IBytes(uint64(v)))) + + // just making it explicit + if fileType.IsDir() { + // if one finds a prior suffix no need to append a new one + if strings.HasSuffix(name, "/") { + fmt.Println(console.Dir("%s", name)) + } else { + fmt.Println(console.Dir("%s/", name)) + } + } + if fileType.IsRegular() { + fmt.Println(console.File("%s", name)) + } +} + +// doList - list all entities inside a directory +func doList(clnt client.Client, targetURL string) error { + var err error + for itemCh := range clnt.List() { + if itemCh.Err != nil { + err = itemCh.Err + break + } + printItem(itemCh.Item.Time, itemCh.Item.Size, itemCh.Item.Name, itemCh.Item.FileType) + } + if err != nil { + return iodine.New(err, map[string]string{"Target": targetURL}) + } + return nil +} + +// doListRecursive - list all entities inside directories and sub-directories recursively +func doListRecursive(clnt client.Client, targetURL string) error { + var err error + for itemCh := range clnt.ListRecursive() { + if itemCh.Err != nil { + err = itemCh.Err + break + } + printItem(itemCh.Item.Time, itemCh.Item.Size, itemCh.Item.Name, itemCh.Item.FileType) + } + if err != nil { + return iodine.New(err, map[string]string{"Target": targetURL}) + } + return nil +} diff --git a/mock_clientManager_test.go b/mock_clientmethods_test.go similarity index 100% rename from mock_clientManager_test.go rename to mock_clientmethods_test.go diff --git a/pkg/client/client.go b/pkg/client/client.go index 75b2590a..1c4b5388 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -30,8 +30,8 @@ type Client interface { // Common operations Stat() (item *Item, err error) - ListSingle() <-chan ItemOnChannel List() <-chan ItemOnChannel + ListRecursive() <-chan ItemOnChannel // Bucket operations PutBucket(acl string) error diff --git a/pkg/client/fs/fs.go b/pkg/client/fs/fs.go index 1317f9c6..5704db76 100644 --- a/pkg/client/fs/fs.go +++ b/pkg/client/fs/fs.go @@ -123,13 +123,14 @@ func (f *fsClient) GetPartial(offset, length int64) (io.ReadCloser, int64, strin return body, length, md5Str, nil } -func (f *fsClient) ListSingle() <-chan client.ItemOnChannel { +// List - list files and directories inside a directory +func (f *fsClient) List() <-chan client.ItemOnChannel { itemCh := make(chan client.ItemOnChannel) - go f.listSingle(itemCh) + go f.list(itemCh) return itemCh } -func (f *fsClient) listSingle(itemCh chan client.ItemOnChannel) { +func (f *fsClient) list(itemCh chan client.ItemOnChannel) { defer close(itemCh) dir, err := os.Open(f.path) if err != nil { @@ -147,6 +148,11 @@ func (f *fsClient) listSingle(itemCh chan client.ItemOnChannel) { } defer dir.Close() if fi.Mode().IsDir() { + // do not use ioutil.ReadDir(), since it tries to sort its + // output at our scale we are expecting that to slow down + // instead we take raw output and provide it back to the user + // - such a thing is helpful when we are moving in and out + // large quantities of files files, err := dir.Readdir(-1) if err != nil { itemCh <- client.ItemOnChannel{ @@ -181,13 +187,14 @@ func (f *fsClient) listSingle(itemCh chan client.ItemOnChannel) { } } -func (f *fsClient) List() <-chan client.ItemOnChannel { +// ListRecursive - list all files and directories recursivelys +func (f *fsClient) ListRecursive() <-chan client.ItemOnChannel { itemCh := make(chan client.ItemOnChannel) - go f.listInGoroutine(itemCh) + go f.listRecursive(itemCh) return itemCh } -func (f *fsClient) listInGoroutine(itemCh chan client.ItemOnChannel) { +func (f *fsClient) listRecursive(itemCh chan client.ItemOnChannel) { defer close(itemCh) visitFS := func(fp string, fi os.FileInfo, err error) error { if err != nil { @@ -217,6 +224,7 @@ func (f *fsClient) listInGoroutine(itemCh chan client.ItemOnChannel) { } } +// isValidBucketACL - is acl a valid ACL? func isValidBucketACL(acl string) bool { switch acl { case "private": @@ -232,6 +240,7 @@ func isValidBucketACL(acl string) bool { } } +// aclToPerm - convert acl to filesystem mode func aclToPerm(acl string) os.FileMode { switch acl { case "private": @@ -274,7 +283,7 @@ func (f *fsClient) getFSMetadata() (item *client.Item, err error) { return item, nil } -// Stat - +// Stat - get metadata from path func (f *fsClient) Stat() (item *client.Item, err error) { return f.getFSMetadata() } diff --git a/pkg/client/fs/fs_test.go b/pkg/client/fs/fs_test.go index a0a2efcc..c9e765d8 100644 --- a/pkg/client/fs/fs_test.go +++ b/pkg/client/fs/fs_test.go @@ -69,7 +69,7 @@ func (s *MySuite) TestList(c *C) { fsc = New(root) var items []*client.Item - for itemCh := range fsc.List() { + for itemCh := range fsc.ListRecursive() { items = append(items, itemCh.Item) } c.Assert(err, IsNil) diff --git a/pkg/client/mocks/Client.go b/pkg/client/mocks/Client.go index cc94e41c..31680789 100644 --- a/pkg/client/mocks/Client.go +++ b/pkg/client/mocks/Client.go @@ -51,15 +51,15 @@ func (m *Client) Stat() (*client.Item, error) { return r0, r1 } -// ListSingle is a mock method -func (m *Client) ListSingle() <-chan client.ItemOnChannel { +// List is a mock method +func (m *Client) List() <-chan client.ItemOnChannel { ret := m.Called() r0 := ret.Get(0).(chan client.ItemOnChannel) return r0 } -// List is a mock method -func (m *Client) List() <-chan client.ItemOnChannel { +// ListRecursive is a mock method +func (m *Client) ListRecursive() <-chan client.ItemOnChannel { ret := m.Called() r0 := ret.Get(0).(chan client.ItemOnChannel) return r0 diff --git a/pkg/client/s3/bucket_list.go b/pkg/client/s3/bucket_list.go index 94f5b508..1afb2eab 100644 --- a/pkg/client/s3/bucket_list.go +++ b/pkg/client/s3/bucket_list.go @@ -33,14 +33,14 @@ import ( /// Bucket API operations -// ListSingle - list delimited path not recursive -func (c *s3Client) ListSingle() <-chan client.ItemOnChannel { +// List - list at delimited path not recursive +func (c *s3Client) List() <-chan client.ItemOnChannel { itemCh := make(chan client.ItemOnChannel) - go c.listSingle(itemCh) + go c.list(itemCh) return itemCh } -func (c *s3Client) listSingle(itemCh chan client.ItemOnChannel) { +func (c *s3Client) list(itemCh chan client.ItemOnChannel) { defer close(itemCh) var items []*client.Item bucket, objectPrefix := c.url2BucketAndObject() @@ -87,14 +87,14 @@ func (c *s3Client) listSingle(itemCh chan client.ItemOnChannel) { } } -// List - list buckets and objects -func (c *s3Client) List() <-chan client.ItemOnChannel { +// ListRecursive - list buckets and objects recursively +func (c *s3Client) ListRecursive() <-chan client.ItemOnChannel { itemCh := make(chan client.ItemOnChannel) - go c.listInGoroutine(itemCh) + go c.listRecursive(itemCh) return itemCh } -func (c *s3Client) listInGoroutine(itemCh chan client.ItemOnChannel) { +func (c *s3Client) listRecursive(itemCh chan client.ItemOnChannel) { defer close(itemCh) var items []*client.Item @@ -190,6 +190,7 @@ func (c *s3Client) filterItems(startAt, marker, prefix, delimiter string, conten return items, nextMarker, nil } +// Populare query URL for Listobjects requests func (c *s3Client) getQueryURL(bucket, marker, prefix, delimiter string, fetchN int) string { var buffer bytes.Buffer buffer.WriteString(fmt.Sprintf("%s?max-keys=%d", c.bucketURL(bucket), fetchN)) diff --git a/url.go b/url.go index f0c9ee01..1c7d311c 100644 --- a/url.go +++ b/url.go @@ -18,105 +18,24 @@ package main import ( "net/url" - "os" - "path/filepath" "strings" "github.com/minio-io/mc/pkg/client" "github.com/minio-io/minio/pkg/iodine" ) +// re-usable constants const ( recursiveSeparator = "..." pathSeparator = "/" ) +// isURLRecursive - find out if requested url is recursive func isURLRecursive(urlStr string) bool { return strings.HasSuffix(urlStr, recursiveSeparator) } -func getObjectKey(sourceURL string) (objectName string) { - u, _ := url.Parse(sourceURL) - splits := strings.SplitN(u.Path, "/", 3) - if len(splits) == 3 { - return splits[2] - } - return "" -} - -func getNewURLRecursive(sourceURL, targetURL, url string) (newSourceURL, newTargetURL string) { - switch client.GetType(sourceURL) { - case client.Object: - sourceURL = strings.TrimSuffix(sourceURL, getObjectKey(sourceURL)) - newSourceURL = strings.TrimSuffix(sourceURL, pathSeparator) + pathSeparator + url - newTargetURL = strings.TrimSuffix(targetURL, pathSeparator) + pathSeparator + url - case client.Filesystem: - newSourceURL = url - prefix := strings.TrimSuffix(sourceURL, pathSeparator) + pathSeparator - newTargetURL = strings.TrimSuffix(targetURL, pathSeparator) + pathSeparator + strings.TrimPrefix(url, prefix) - } - return newSourceURL, newTargetURL -} - -func getNewTargetURL(targetURL string, sourceURL string) (newTargetURL string, err error) { - switch client.GetType(targetURL) { - case client.Object: - return getNewTargetURLObject(targetURL, sourceURL) - case client.Filesystem: - return getNewTargetURLFilesystem(targetURL, sourceURL) - } - return "", iodine.New(errInvalidURL{url: targetURL}, nil) -} - -func getNewTargetURLObject(targetURL string, sourceURL string) (newTargetURL string, err error) { - if getObjectKey(targetURL) != "" { - return "", iodine.New(errIsNotBucket{path: targetURL}, nil) - } - switch client.GetType(sourceURL) { - case client.Filesystem: - _, s := filepath.Split(sourceURL) - if s == "" { - return "", iodine.New(errInvalidSource{path: sourceURL}, nil) - } - newTargetURL = strings.TrimSuffix(targetURL, pathSeparator) + pathSeparator + s - case client.Object: - object := getObjectKey(sourceURL) - if object == "" { - return "", iodine.New(errInvalidSource{path: sourceURL}, nil) - } - _, s := filepath.Split(object) - newTargetURL = filepath.Join(targetURL, s) - } - return newTargetURL, nil -} - -func getNewTargetURLFilesystem(targetURL string, sourceURL string) (newTargetURL string, err error) { - st, err := os.Stat(targetURL) - if err != nil { - return "", iodine.New(errIsNotDIR{path: targetURL}, nil) - } - if !st.IsDir() { - return "", iodine.New(errIsNotDIR{path: targetURL}, nil) - } - switch client.GetType(sourceURL) { - case client.Filesystem: - _, s := filepath.Split(sourceURL) - if s == "" { - return "", iodine.New(errInvalidSource{path: sourceURL}, nil) - } - newTargetURL = filepath.Join(targetURL, s) - case client.Object: - object := getObjectKey(sourceURL) - if object == "" { - return "", iodine.New(errInvalidSource{path: sourceURL}, nil) - } - _, s := filepath.Split(object) - newTargetURL = filepath.Join(targetURL, s) - } - return newTargetURL, nil -} - -// getURL extracts URL string from a single cmd-line argument +// getURL - extracts URL string from a single cmd-line argument func getURL(arg string, aliases map[string]string) (urlStr string, err error) { _, err = url.Parse(arg) if err != nil { @@ -137,7 +56,7 @@ func getURL(arg string, aliases map[string]string) (urlStr string, err error) { return urlStr, nil } -// getURLs extracts multiple URL strings from a single cmd-line argument +// getURLs - extracts multiple URL strings from a single cmd-line argument func getURLs(args []string, aliases map[string]string) (urls []string, err error) { for _, arg := range args { u, err := getURL(arg, aliases)