From fe5b2f97e3d22324474e742edd15d9562467ef75 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 16 Feb 2016 03:05:10 -0800 Subject: [PATCH] fs/s3: move the code for fs and s3 out to the top-level. Now the interface moves to the top level - fixes #1604 --- pkg/client/errors.go => client-errors.go | 29 +-- pkg/client/fs/fs.go => client-fs.go | 231 +++++++++++++----- pkg/client/fs/fs_test.go => client-fs_test.go | 55 ++--- .../s3/trace_v2.go => client-s3-trace_v2.go | 16 +- .../s3/trace_v4.go => client-s3-trace_v4.go | 16 +- pkg/client/s3/s3.go => client-s3.go | 123 +++++----- pkg/client/s3/s3_test.go => client-s3_test.go | 29 +-- pkg/client/client.go => client.go | 12 +- common-methods.go | 15 +- config-fix.go | 3 +- config-utils.go | 20 +- cp-main.go | 13 +- cp-url-syntax.go | 3 +- cp-url.go | 39 ++- diff-main.go | 7 +- difference.go | 3 +- .../fs/path-utils.go => fs-pathutils.go | 2 +- ...utils_windows.go => fs-pathutils_window.go | 2 +- ls-main.go | 3 +- ls.go | 13 +- mirror-main.go | 13 +- mirror-url.go | 17 +- pkg/client/client_test.go | 69 ------ pkg/client/fs/.gitignore | 1 - pkg/client/fs/fs-common.go | 86 ------- pkg/client/fs/fs-utils.go | 168 ------------- pkg/client/url.go | 162 ------------ share-upload-main.go | 5 +- url.go | 151 +++++++++++- .../github.com/minio/minio-go/CONTRIBUTING.md | 4 +- vendor/github.com/minio/minio-go/api.go | 60 +---- .../minio/minio-go/api_functional_v2_test.go | 8 +- .../minio/minio-go/api_functional_v4_test.go | 8 +- .../minio/minio/pkg/ioutils/filepath.go | 143 +++++++++++ .../minio/minio/pkg/ioutils/ioutils_test.go | 43 ++++ vendor/vendor.json | 9 +- 36 files changed, 728 insertions(+), 853 deletions(-) rename pkg/client/errors.go => client-errors.go (88%) rename pkg/client/fs/fs.go => client-fs.go (75%) rename pkg/client/fs/fs_test.go => client-fs_test.go (86%) rename pkg/client/s3/trace_v2.go => client-s3-trace_v2.go (84%) rename pkg/client/s3/trace_v4.go => client-s3-trace_v4.go (88%) rename pkg/client/s3/s3.go => client-s3.go (87%) rename pkg/client/s3/s3_test.go => client-s3_test.go (95%) rename pkg/client/client.go => client.go (90%) rename pkg/client/fs/path-utils.go => fs-pathutils.go (98%) rename pkg/client/fs/path-utils_windows.go => fs-pathutils_window.go (98%) delete mode 100644 pkg/client/client_test.go delete mode 100644 pkg/client/fs/.gitignore delete mode 100644 pkg/client/fs/fs-common.go delete mode 100644 pkg/client/fs/fs-utils.go delete mode 100644 pkg/client/url.go create mode 100644 vendor/github.com/minio/minio/pkg/ioutils/filepath.go create mode 100644 vendor/github.com/minio/minio/pkg/ioutils/ioutils_test.go diff --git a/pkg/client/errors.go b/client-errors.go similarity index 88% rename from pkg/client/errors.go rename to client-errors.go index bb20dfe5..8d1d0776 100644 --- a/pkg/client/errors.go +++ b/client-errors.go @@ -14,12 +14,9 @@ * limitations under the License. */ -package client +package main -import ( - "fmt" - "strconv" -) +import "fmt" /// Collection of standard errors @@ -33,15 +30,6 @@ func (e APINotImplemented) Error() string { return "‘" + e.API + "’ feature " + "is not implemented for ‘" + e.APIType + "’." } -// InvalidRange - invalid range requested -type InvalidRange struct { - Offset int64 -} - -func (e InvalidRange) Error() string { - return "Invalid range offset: ‘" + strconv.FormatInt(e.Offset, 10) + "’." -} - // GenericBucketError - generic bucket operations error type GenericBucketError struct { Bucket string @@ -75,12 +63,6 @@ func (e BucketNameEmpty) Error() string { return "Bucket name cannot be empty." } -// GenericObjectError - generic object operations error -type GenericObjectError struct { - Bucket string - Object string -} - // ObjectAlreadyExists - typed return for MethodNotAllowed type ObjectAlreadyExists struct { Object string @@ -90,13 +72,6 @@ func (e ObjectAlreadyExists) Error() string { return "Object ‘" + e.Object + "’ already exists." } -// InvalidObjectName - object requested is invalid -type InvalidObjectName GenericObjectError - -func (e InvalidObjectName) Error() string { - return "Object ‘" + e.Object + "’ at ‘" + e.Bucket + "’ is invalid." -} - // BucketNameTopLevel - generic error type BucketNameTopLevel struct{} diff --git a/pkg/client/fs/fs.go b/client-fs.go similarity index 75% rename from pkg/client/fs/fs.go rename to client-fs.go index 0a03a366..a9840300 100644 --- a/pkg/client/fs/fs.go +++ b/client-fs.go @@ -14,44 +14,45 @@ * limitations under the License. */ -package fs +package main import ( "io" "os" "path/filepath" "runtime" + "sort" "strings" "time" "io/ioutil" - "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/hookreader" + "github.com/minio/minio/pkg/ioutils" "github.com/minio/minio/pkg/probe" ) // filesystem client type fsClient struct { - PathURL *client.URL + PathURL *clientURL } const ( - partSuffix = ".part.mc" + partSuffix = ".part.minio" ) -// New - instantiate a new fs client. -func New(path string) (client.Client, *probe.Error) { +// fsNew - instantiate a new fs +func fsNew(path string) (Client, *probe.Error) { if strings.TrimSpace(path) == "" { - return nil, probe.NewError(client.EmptyPath{}) + return nil, probe.NewError(EmptyPath{}) } return &fsClient{ - PathURL: client.NewURL(normalizePath(path)), + PathURL: newURL(normalizePath(path)), }, nil } // URL get url. -func (f *fsClient) GetURL() client.URL { +func (f *fsClient) GetURL() clientURL { return *f.PathURL } @@ -71,7 +72,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres if e == nil { // If the destination exists and is not a regular file. if !st.Mode().IsRegular() { - return 0, probe.NewError(client.PathIsNotRegular{ + return 0, probe.NewError(PathIsNotRegular{ Path: objectPath, }) } @@ -143,7 +144,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres // corruption return here. if readAtSize != writtenSize { // Unexpected write (less data was written than expected). - return 0, probe.NewError(client.UnexpectedShortWrite{ + return 0, probe.NewError(UnexpectedShortWrite{ InputSize: readAtSize, WriteSize: writtenSize, }) @@ -194,14 +195,14 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres if size > 0 { // Unexpected EOF reached (less data was written than expected). if totalWritten < size { - return totalWritten, probe.NewError(client.UnexpectedEOF{ + return totalWritten, probe.NewError(UnexpectedEOF{ TotalSize: size, TotalWritten: totalWritten, }) } // Unexpected ExcessRead (more data was written than expected). if totalWritten > size { - return totalWritten, probe.NewError(client.UnexpectedExcessRead{ + return totalWritten, probe.NewError(UnexpectedExcessRead{ TotalSize: size, TotalWritten: totalWritten, }) @@ -217,7 +218,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres // ShareDownload - share download not implemented for filesystem. func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) { - return "", probe.NewError(client.APINotImplemented{ + return "", probe.NewError(APINotImplemented{ API: "ShareDownload", APIType: "filesystem", }) @@ -225,7 +226,7 @@ func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) { // ShareUpload - share upload not implemented for filesystem. func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) { - return nil, probe.NewError(client.APINotImplemented{ + return nil, probe.NewError(APINotImplemented{ API: "ShareUpload", APIType: "filesystem", }) @@ -266,8 +267,8 @@ func (f *fsClient) Remove(incomplete bool) *probe.Error { } // List - list files and folders. -func (f *fsClient) List(recursive, incomplete bool) <-chan *client.Content { - contentCh := make(chan *client.Content) +func (f *fsClient) List(recursive, incomplete bool) <-chan *clientContent { + contentCh := make(chan *clientContent) switch recursive { case true: go f.listRecursiveInRoutine(contentCh, incomplete) @@ -277,13 +278,50 @@ func (f *fsClient) List(recursive, incomplete bool) <-chan *client.Content { return contentCh } +// byDirName implements sort.Interface. +type byDirName []os.FileInfo + +func (f byDirName) Len() int { return len(f) } +func (f byDirName) Less(i, j int) bool { + // For directory add an ending separator fortrue lexical + // order. + if f[i].Mode().IsDir() { + return f[i].Name()+string(filepath.Separator) < f[j].Name() + } + // For directory add an ending separator for true lexical + // order. + if f[j].Mode().IsDir() { + return f[i].Name() < f[j].Name()+string(filepath.Separator) + } + return f[i].Name() < f[j].Name() +} +func (f byDirName) Swap(i, j int) { f[i], f[j] = f[j], f[i] } + +// readDir reads the directory named by dirname and returns +// a list of sorted directory entries. +func readDir(dirname string) ([]os.FileInfo, error) { + f, e := os.Open(dirname) + if e != nil { + return nil, e + } + list, e := f.Readdir(-1) + if e != nil { + return nil, e + } + if e = f.Close(); e != nil { + return nil, e + } + sort.Sort(byDirName(list)) + return list, nil +} + // listPrefixes - list all files for any given prefix. -func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, incomplete bool) { +func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent, incomplete bool) { dirName := filepath.Dir(prefix) files, e := readDir(dirName) if e != nil { err := f.toClientError(e, dirName) - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: err.Trace(dirName), } return @@ -303,7 +341,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, newPath := filepath.Join(prefix, fi.Name()) lfi, le := f.handleWindowsSymlinks(newPath) if le != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: le.Trace(newPath), } continue @@ -318,19 +356,19 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, } } pathURL.Path = filepath.Join(pathURL.Path, lfi.Name()) - contentCh <- &client.Content{ + contentCh <- &clientContent{ URL: pathURL, Time: lfi.ModTime(), Size: lfi.Size(), Type: lfi.Mode(), - Err: probe.NewError(client.PathInsufficientPermission{ + Err: probe.NewError(PathInsufficientPermission{ Path: pathURL.Path, }), } continue } else { - contentCh <- &client.Content{ - Err: probe.NewError(client.PathInsufficientPermission{ + contentCh <- &clientContent{ + Err: probe.NewError(PathInsufficientPermission{ Path: pathURL.Path, }), } @@ -338,15 +376,15 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, } } if os.IsNotExist(e) { - contentCh <- &client.Content{ - Err: probe.NewError(client.BrokenSymlink{ + contentCh <- &clientContent{ + Err: probe.NewError(BrokenSymlink{ Path: pathURL.Path, }), } continue } if e != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(e), } continue @@ -362,8 +400,8 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, continue } } - contentCh <- &client.Content{ - URL: *client.NewURL(file), + contentCh <- &clientContent{ + URL: *newURL(file), Time: st.ModTime(), Size: st.Size(), Type: st.Mode(), @@ -382,8 +420,8 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, continue } } - contentCh <- &client.Content{ - URL: *client.NewURL(file), + contentCh <- &clientContent{ + URL: *newURL(file), Time: fi.ModTime(), Size: fi.Size(), Type: fi.Mode(), @@ -394,7 +432,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, return } -func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bool) { +func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete bool) { // close the channel when the function returns. defer close(contentCh) @@ -404,14 +442,14 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo fst, err := f.fsStat() if err != nil { - if _, ok := err.ToGoError().(client.PathNotFound); ok { + if _, ok := err.ToGoError().(PathNotFound); ok { // If file does not exist treat it like a prefix and list all prefixes if any. prefix := fpath f.listPrefixes(prefix, contentCh, incomplete) return } // For all other errors we return genuine error back to the caller. - contentCh <- &client.Content{Err: err.Trace(fpath)} + contentCh <- &clientContent{Err: err.Trace(fpath)} return } @@ -427,7 +465,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo case true: files, e := readDir(fpath) if err != nil { - contentCh <- &client.Content{Err: probe.NewError(e)} + contentCh <- &clientContent{Err: probe.NewError(e)} return } for _, file := range files { @@ -443,7 +481,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo newPath := filepath.Join(fpath, fi.Name()) lfi, le := f.handleWindowsSymlinks(newPath) if le != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: le.Trace(newPath), } continue @@ -459,29 +497,29 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo } pathURL = *f.PathURL pathURL.Path = filepath.Join(pathURL.Path, lfi.Name()) - contentCh <- &client.Content{ + contentCh <- &clientContent{ URL: pathURL, Time: lfi.ModTime(), Size: lfi.Size(), Type: lfi.Mode(), - Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}), + Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}), } continue } else { - contentCh <- &client.Content{ - Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}), + contentCh <- &clientContent{ + Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}), } continue } } if os.IsNotExist(e) { - contentCh <- &client.Content{ - Err: probe.NewError(client.BrokenSymlink{Path: file.Name()}), + contentCh <- &clientContent{ + Err: probe.NewError(BrokenSymlink{Path: file.Name()}), } continue } if e != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(e), } continue @@ -499,7 +537,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo } pathURL = *f.PathURL pathURL.Path = filepath.Join(pathURL.Path, fi.Name()) - contentCh <- &client.Content{ + contentCh <- &clientContent{ URL: pathURL, Time: fi.ModTime(), Size: fi.Size(), @@ -518,7 +556,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo return } } - contentCh <- &client.Content{ + contentCh <- &clientContent{ URL: pathURL, Time: fst.ModTime(), Size: fst.Size(), @@ -528,7 +566,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo } } -func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomplete bool) { +func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, incomplete bool) { // close channels upon return. defer close(contentCh) var dirName string @@ -555,7 +593,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp !strings.HasPrefix(filePrefix, fp) { if e == nil { if fi.IsDir() { - return errSkipDir + return ioutils.ErrSkipDir } return nil } @@ -571,7 +609,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp if e != nil { // If operation is not permitted, we throw quickly back. if strings.Contains(e.Error(), "operation not permitted") { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(e), } return nil @@ -580,7 +618,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp if runtime.GOOS == "windows" { lfi, le := f.handleWindowsSymlinks(fp) if le != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: le.Trace(fp), } return nil @@ -596,7 +634,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp return nil } } - contentCh <- &client.Content{ + contentCh <- &clientContent{ URL: pathURL, Time: lfi.ModTime(), Size: lfi.Size(), @@ -604,8 +642,8 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp Err: probe.NewError(e), } } else { - contentCh <- &client.Content{ - Err: probe.NewError(client.PathInsufficientPermission{Path: fp}), + contentCh <- &clientContent{ + Err: probe.NewError(PathInsufficientPermission{Path: fp}), } } return nil @@ -619,7 +657,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp if runtime.GOOS == "windows" { lfi, le := f.handleWindowsSymlinks(fp) if le != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: le.Trace(fp), } return nil @@ -635,7 +673,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp return nil } } - contentCh <- &client.Content{ + contentCh <- &clientContent{ URL: pathURL, Time: lfi.ModTime(), Size: lfi.Size(), @@ -644,22 +682,22 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp } return nil } - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(e), } return nil } // Ignore in-accessible broken symlinks. if os.IsNotExist(e) { - contentCh <- &client.Content{ - Err: probe.NewError(client.BrokenSymlink{Path: fp}), + contentCh <- &clientContent{ + Err: probe.NewError(BrokenSymlink{Path: fp}), } return nil } // Ignore symlink loops. if strings.Contains(e.Error(), "too many levels of symbolic links") { - contentCh <- &client.Content{ - Err: probe.NewError(client.TooManyLevelsSymlink{Path: fp}), + contentCh <- &clientContent{ + Err: probe.NewError(TooManyLevelsSymlink{Path: fp}), } return nil } @@ -676,8 +714,8 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp return nil } } - contentCh <- &client.Content{ - URL: *client.NewURL(fp), + contentCh <- &clientContent{ + URL: *newURL(fp), Time: fi.ModTime(), Size: fi.Size(), Type: fi.Mode(), @@ -703,9 +741,9 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp filePrefix = pathURL.Path } // walks invokes our custom function. - e := walk(dirName, visitFS) + e := ioutils.FTW(dirName, visitFS) if e != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(e), } } @@ -722,24 +760,83 @@ func (f *fsClient) MakeBucket(region string) *probe.Error { // GetBucketACL - get bucket access. func (f *fsClient) GetBucketAccess() (acl string, err *probe.Error) { - return "", probe.NewError(client.APINotImplemented{API: "GetBucketAccess", APIType: "filesystem"}) + return "", probe.NewError(APINotImplemented{API: "GetBucketAccess", APIType: "filesystem"}) } // SetBucketAccess - set bucket access. func (f *fsClient) SetBucketAccess(acl string) *probe.Error { - return probe.NewError(client.APINotImplemented{API: "SetBucketAccess", APIType: "filesystem"}) + return probe.NewError(APINotImplemented{API: "SetBucketAccess", APIType: "filesystem"}) } // Stat - get metadata from path. -func (f *fsClient) Stat() (content *client.Content, err *probe.Error) { +func (f *fsClient) Stat() (content *clientContent, err *probe.Error) { st, err := f.fsStat() if err != nil { return nil, err.Trace(f.PathURL.String()) } - content = new(client.Content) + content = &clientContent{} content.URL = *f.PathURL content.Size = st.Size() content.Time = st.ModTime() content.Type = st.Mode() return content, nil } + +// toClientError error constructs a typed client error for known filesystem errors. +func (f *fsClient) toClientError(e error, fpath string) *probe.Error { + if os.IsPermission(e) { + return probe.NewError(PathInsufficientPermission{Path: fpath}) + } + if os.IsNotExist(e) { + return probe.NewError(PathNotFound{Path: fpath}) + } + return probe.NewError(e) +} + +// handle windows symlinks - eg: junction files. +func (f *fsClient) handleWindowsSymlinks(fpath string) (os.FileInfo, *probe.Error) { + // On windows there are directory symlinks which are called junction files. + // These files carry special meaning on windows they cannot be, + // accessed with regular operations. + file, e := os.Lstat(fpath) + if e != nil { + err := f.toClientError(e, fpath) + return nil, err.Trace(fpath) + } + return file, nil +} + +// fsStat - wrapper function to get file stat. +func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) { + fpath := f.PathURL.Path + // Golang strips trailing / if you clean(..) or + // EvalSymlinks(..). Adding '.' prevents it from doing so. + if strings.HasSuffix(fpath, string(f.PathURL.Separator)) { + fpath = fpath + "." + } + fpath, e := filepath.EvalSymlinks(fpath) + if e != nil { + if os.IsPermission(e) { + if runtime.GOOS == "windows" { + return f.handleWindowsSymlinks(f.PathURL.Path) + } + return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path}) + } + err := f.toClientError(e, f.PathURL.Path) + return nil, err.Trace(fpath) + } + st, e := os.Stat(fpath) + if e != nil { + if os.IsPermission(e) { + if runtime.GOOS == "windows" { + return f.handleWindowsSymlinks(fpath) + } + return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path}) + } + if os.IsNotExist(e) { + return nil, probe.NewError(PathNotFound{Path: f.PathURL.Path}) + } + return nil, probe.NewError(e) + } + return st, nil +} diff --git a/pkg/client/fs/fs_test.go b/client-fs_test.go similarity index 86% rename from pkg/client/fs/fs_test.go rename to client-fs_test.go index 26416c92..13e2cf2d 100644 --- a/pkg/client/fs/fs_test.go +++ b/client-fs_test.go @@ -14,7 +14,7 @@ * limitations under the License. */ -package fs_test +package main import ( "bytes" @@ -22,28 +22,19 @@ import ( "io/ioutil" "os" "path/filepath" - "testing" - "github.com/minio/mc/pkg/client" - "github.com/minio/mc/pkg/client/fs" . "gopkg.in/check.v1" ) -func Test(t *testing.T) { TestingT(t) } - -type MySuite struct{} - -var _ = Suite(&MySuite{}) - // Test list files in a folder. -func (s *MySuite) TestList(c *C) { +func (s *TestSuite) TestList(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) // Create multiple files. objectPath := filepath.Join(root, "object1") - fsClient, err := fs.New(objectPath) + fsClient, err := fsNew(objectPath) c.Assert(err, IsNil) data := "hello" @@ -55,7 +46,7 @@ func (s *MySuite) TestList(c *C) { c.Assert(n, Equals, int64(len(data))) objectPath = filepath.Join(root, "object2") - fsClient, err = fs.New(objectPath) + fsClient, err = fsNew(objectPath) c.Assert(err, IsNil) reader = bytes.NewReader([]byte(data)) @@ -63,11 +54,11 @@ func (s *MySuite) TestList(c *C) { c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) - fsClient, err = fs.New(root) + fsClient, err = fsNew(root) c.Assert(err, IsNil) // Verify previously create files and list them. - var contents []*client.Content + var contents []*clientContent for content := range fsClient.List(false, false) { if content.Err != nil { err = content.Err @@ -81,7 +72,7 @@ func (s *MySuite) TestList(c *C) { // Create another file. objectPath = filepath.Join(root, "test1/newObject1") - fsClient, err = fs.New(objectPath) + fsClient, err = fsNew(objectPath) c.Assert(err, IsNil) reader = bytes.NewReader([]byte(data)) @@ -89,7 +80,7 @@ func (s *MySuite) TestList(c *C) { c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) - fsClient, err = fs.New(root) + fsClient, err = fsNew(root) c.Assert(err, IsNil) contents = nil @@ -105,7 +96,7 @@ func (s *MySuite) TestList(c *C) { c.Assert(len(contents), Equals, 1) c.Assert(contents[0].Type.IsDir(), Equals, true) - fsClient, err = fs.New(root) + fsClient, err = fsNew(root) c.Assert(err, IsNil) contents = nil @@ -139,27 +130,27 @@ func (s *MySuite) TestList(c *C) { } // Test put bucket aka 'mkdir()' operation. -func (s *MySuite) TestPutBucket(c *C) { +func (s *TestSuite) TestPutBucket(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) bucketPath := filepath.Join(root, "bucket") - fsClient, err := fs.New(bucketPath) + fsClient, err := fsNew(bucketPath) c.Assert(err, IsNil) err = fsClient.MakeBucket("us-east-1") c.Assert(err, IsNil) } // Test stat bucket aka 'stat()' operation. -func (s *MySuite) TestStatBucket(c *C) { +func (s *TestSuite) TestStatBucket(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) bucketPath := filepath.Join(root, "bucket") - fsClient, err := fs.New(bucketPath) + fsClient, err := fsNew(bucketPath) c.Assert(err, IsNil) err = fsClient.MakeBucket("us-east-1") c.Assert(err, IsNil) @@ -168,13 +159,13 @@ func (s *MySuite) TestStatBucket(c *C) { } // Test bucket acl fails for directories. -func (s *MySuite) TestBucketACLFails(c *C) { +func (s *TestSuite) TestBucketACLFails(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) bucketPath := filepath.Join(root, "bucket") - fsClient, err := fs.New(bucketPath) + fsClient, err := fsNew(bucketPath) c.Assert(err, IsNil) err = fsClient.MakeBucket("us-east-1") c.Assert(err, IsNil) @@ -187,13 +178,13 @@ func (s *MySuite) TestBucketACLFails(c *C) { } // Test creating a file. -func (s *MySuite) TestPut(c *C) { +func (s *TestSuite) TestPut(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) objectPath := filepath.Join(root, "object") - fsClient, err := fs.New(objectPath) + fsClient, err := fsNew(objectPath) c.Assert(err, IsNil) data := "hello" @@ -205,13 +196,13 @@ func (s *MySuite) TestPut(c *C) { } // Test read a file. -func (s *MySuite) TestGet(c *C) { +func (s *TestSuite) TestGet(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) objectPath := filepath.Join(root, "object") - fsClient, err := fs.New(objectPath) + fsClient, err := fsNew(objectPath) c.Assert(err, IsNil) data := "hello" @@ -231,13 +222,13 @@ func (s *MySuite) TestGet(c *C) { } // Test get range in a file. -func (s *MySuite) TestGetRange(c *C) { +func (s *TestSuite) TestGetRange(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) objectPath := filepath.Join(root, "object") - fsClient, err := fs.New(objectPath) + fsClient, err := fsNew(objectPath) c.Assert(err, IsNil) data := "hello world" @@ -260,13 +251,13 @@ func (s *MySuite) TestGetRange(c *C) { } // Test stat file. -func (s *MySuite) TestStatObject(c *C) { +func (s *TestSuite) TestStatObject(c *C) { root, e := ioutil.TempDir(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) objectPath := filepath.Join(root, "object") - fsClient, err := fs.New(objectPath) + fsClient, err := fsNew(objectPath) c.Assert(err, IsNil) data := "hello" diff --git a/pkg/client/s3/trace_v2.go b/client-s3-trace_v2.go similarity index 84% rename from pkg/client/s3/trace_v2.go rename to client-s3-trace_v2.go index e67e32aa..3b22fc16 100644 --- a/pkg/client/s3/trace_v2.go +++ b/client-s3-trace_v2.go @@ -14,7 +14,7 @@ * limitations under the License. */ -package s3 +package main import ( "net/http" @@ -25,16 +25,16 @@ import ( "github.com/minio/mc/pkg/httptracer" ) -// TraceV2 - tracing structure -type TraceV2 struct{} +// traceV2 - tracing structure for signature version '2'. +type traceV2 struct{} -// NewTraceV2 - initialize Trace structure -func NewTraceV2() httptracer.HTTPTracer { - return TraceV2{} +// newTraceV2 - initialize Trace structure +func newTraceV2() httptracer.HTTPTracer { + return traceV2{} } // Request - Trace HTTP Request -func (t TraceV2) Request(req *http.Request) (err error) { +func (t traceV2) Request(req *http.Request) (err error) { origAuth := req.Header.Get("Authorization") if strings.TrimSpace(origAuth) != "" { @@ -57,7 +57,7 @@ func (t TraceV2) Request(req *http.Request) (err error) { } // Response - Trace HTTP Response -func (t TraceV2) Response(res *http.Response) (err error) { +func (t traceV2) Response(res *http.Response) (err error) { var resTrace []byte // For errors we make sure to dump response body as well. if res.StatusCode != http.StatusOK && diff --git a/pkg/client/s3/trace_v4.go b/client-s3-trace_v4.go similarity index 88% rename from pkg/client/s3/trace_v4.go rename to client-s3-trace_v4.go index 27c07d59..6de56361 100644 --- a/pkg/client/s3/trace_v4.go +++ b/client-s3-trace_v4.go @@ -14,7 +14,7 @@ * limitations under the License. */ -package s3 +package main import ( "net/http" @@ -26,16 +26,16 @@ import ( "github.com/minio/mc/pkg/httptracer" ) -// TraceV4 - tracing structure -type TraceV4 struct{} +// traceV4 - tracing structure for signature version '4'. +type traceV4 struct{} -// NewTraceV4 - initialize Trace structure -func NewTraceV4() httptracer.HTTPTracer { - return TraceV4{} +// newTraceV4 - initialize Trace structure +func newTraceV4() httptracer.HTTPTracer { + return traceV4{} } // Request - Trace HTTP Request -func (t TraceV4) Request(req *http.Request) (err error) { +func (t traceV4) Request(req *http.Request) (err error) { origAuth := req.Header.Get("Authorization") if strings.TrimSpace(origAuth) != "" { @@ -66,7 +66,7 @@ func (t TraceV4) Request(req *http.Request) (err error) { } // Response - Trace HTTP Response -func (t TraceV4) Response(res *http.Response) (err error) { +func (t traceV4) Response(res *http.Response) (err error) { var resTrace []byte // For errors we make sure to dump response body as well. if res.StatusCode != http.StatusOK && diff --git a/pkg/client/s3/s3.go b/client-s3.go similarity index 87% rename from pkg/client/s3/s3.go rename to client-s3.go index c0b955f9..52a6addd 100644 --- a/pkg/client/s3/s3.go +++ b/client-s3.go @@ -14,7 +14,7 @@ * limitations under the License. */ -package s3 +package main import ( "errors" @@ -29,7 +29,6 @@ import ( "sync" "time" - "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/httptracer" "github.com/minio/minio-go" "github.com/minio/minio/pkg/probe" @@ -38,27 +37,27 @@ import ( // S3 client type s3Client struct { mutex *sync.Mutex - targetURL *client.URL - api minio.CloudStorageClient + targetURL *clientURL + api *minio.Client virtualStyle bool } // newFactory encloses New function with client cache. -func newFactory() func(config *client.Config) (client.Client, *probe.Error) { - clientCache := make(map[uint32]minio.CloudStorageClient) +func newFactory() func(config *Config) (Client, *probe.Error) { + clientCache := make(map[uint32]*minio.Client) mutex := &sync.Mutex{} // Return New function. - return func(config *client.Config) (client.Client, *probe.Error) { + return func(config *Config) (Client, *probe.Error) { // Creates a parsed URL. - targetURL := client.NewURL(config.HostURL) + targetURL := newURL(config.HostURL) // By default enable HTTPs. inSecure := false if targetURL.Scheme == "http" { inSecure = true } - // Instantiate s3 client. + // Instantiate s3 s3Clnt := &s3Client{} // Allocate a new mutex. s3Clnt.mutex = new(sync.Mutex) @@ -88,10 +87,10 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) { // Lookup previous cache by hash. mutex.Lock() defer mutex.Unlock() - var api minio.CloudStorageClient + var api *minio.Client found := false if api, found = clientCache[confSum]; !found { - // Not found. Instantiate a new minio client. + // Not found. Instantiate a new minio var e error if config.Signature == "S3v2" { // if Signature version '2' use NewV2 directly. @@ -112,10 +111,10 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) { if config.Debug { transport := http.DefaultTransport if config.Signature == "S3v4" { - transport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport) + transport = httptracer.GetNewTraceTransport(newTraceV4(), http.DefaultTransport) } if config.Signature == "S3v2" { - transport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport) + transport = httptracer.GetNewTraceTransport(newTraceV2(), http.DefaultTransport) } // Set custom transport. api.SetCustomTransport(transport) @@ -128,12 +127,12 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) { } } -// New returns an initialized s3Client structure. If debug is enabled, +// s3New returns an initialized s3Client structure. If debug is enabled, // it also enables an internal trace transport. -var New = newFactory() +var s3New = newFactory() // GetURL get url. -func (c *s3Client) GetURL() client.URL { +func (c *s3Client) GetURL() clientURL { return *c.targetURL } @@ -144,7 +143,7 @@ func (c *s3Client) Get() (io.Reader, *probe.Error) { if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "AccessDenied" { - return nil, probe.NewError(client.PathInsufficientPermission{Path: c.targetURL.String()}) + return nil, probe.NewError(PathInsufficientPermission{Path: c.targetURL.String()}) } return nil, probe.NewError(e) } @@ -165,28 +164,28 @@ func (c *s3Client) Put(reader io.Reader, size int64, contentType string, progres if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "UnexpectedEOF" || e == io.EOF { - return n, probe.NewError(client.UnexpectedEOF{ + return n, probe.NewError(UnexpectedEOF{ TotalSize: size, TotalWritten: n, }) } if errResponse.Code == "AccessDenied" { - return n, probe.NewError(client.PathInsufficientPermission{ + return n, probe.NewError(PathInsufficientPermission{ Path: c.targetURL.String(), }) } if errResponse.Code == "MethodNotAllowed" { - return n, probe.NewError(client.ObjectAlreadyExists{ + return n, probe.NewError(ObjectAlreadyExists{ Object: object, }) } if errResponse.Code == "NoSuchBucket" { - return n, probe.NewError(client.BucketDoesNotExist{ + return n, probe.NewError(BucketDoesNotExist{ Bucket: bucket, }) } if errResponse.Code == "InvalidArgument" { - return n, probe.NewError(client.ObjectMissing{}) + return n, probe.NewError(ObjectMissing{}) } return n, probe.NewError(e) } @@ -233,7 +232,7 @@ func isValidBucketName(bucketName string) *probe.Error { func (c *s3Client) MakeBucket(region string) *probe.Error { bucket, object := c.url2BucketAndObject() if object != "" { - return probe.NewError(client.BucketNameTopLevel{}) + return probe.NewError(BucketNameTopLevel{}) } if err := isValidBucketName(bucket); err != nil { return err.Trace(bucket) @@ -249,10 +248,10 @@ func (c *s3Client) MakeBucket(region string) *probe.Error { func (c *s3Client) GetBucketAccess() (acl string, err *probe.Error) { bucket, object := c.url2BucketAndObject() if object != "" { - return "", probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)}) + return "", probe.NewError(InvalidBucketName{Bucket: filepath.Join(bucket, object)}) } if bucket == "" { - return "", probe.NewError(client.BucketNameEmpty{}) + return "", probe.NewError(BucketNameEmpty{}) } bucketACL, e := c.api.GetBucketACL(bucket) if e != nil { @@ -265,10 +264,10 @@ func (c *s3Client) GetBucketAccess() (acl string, err *probe.Error) { func (c *s3Client) SetBucketAccess(acl string) *probe.Error { bucket, object := c.url2BucketAndObject() if object != "" { - return probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)}) + return probe.NewError(InvalidBucketName{Bucket: filepath.Join(bucket, object)}) } if bucket == "" { - return probe.NewError(client.BucketNameEmpty{}) + return probe.NewError(BucketNameEmpty{}) } e := c.api.SetBucketACL(bucket, minio.BucketACL(acl)) if e != nil { @@ -278,9 +277,9 @@ func (c *s3Client) SetBucketAccess(acl string) *probe.Error { } // Stat - send a 'HEAD' on a bucket or object to fetch its metadata. -func (c *s3Client) Stat() (*client.Content, *probe.Error) { +func (c *s3Client) Stat() (*clientContent, *probe.Error) { c.mutex.Lock() - objectMetadata := new(client.Content) + objectMetadata := &clientContent{} bucket, object := c.url2BucketAndObject() switch { // valid case for 'ls -r s3/' @@ -291,7 +290,7 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) { return nil, probe.NewError(e) } c.mutex.Unlock() - return &client.Content{URL: *c.targetURL, Type: os.ModeDir}, nil + return &clientContent{URL: *c.targetURL, Type: os.ModeDir}, nil } if object != "" { metadata, e := c.api.StatObject(bucket, object) @@ -309,12 +308,12 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) { if objectStat.Err != nil { return nil, probe.NewError(objectStat.Err) } - content := client.Content{} + content := clientContent{} content.URL = *c.targetURL content.Type = os.ModeDir return &content, nil } - return nil, probe.NewError(client.PathNotFound{Path: c.targetURL.Path}) + return nil, probe.NewError(PathNotFound{Path: c.targetURL.Path}) } return nil, probe.NewError(e) } @@ -330,7 +329,7 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) { c.mutex.Unlock() return nil, probe.NewError(e) } - bucketMetadata := new(client.Content) + bucketMetadata := &clientContent{} bucketMetadata.URL = *c.targetURL bucketMetadata.Type = os.ModeDir c.mutex.Unlock() @@ -390,11 +389,11 @@ func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) { /// Bucket API operations. // List - list at delimited path, if not recursive. -func (c *s3Client) List(recursive, incomplete bool) <-chan *client.Content { +func (c *s3Client) List(recursive, incomplete bool) <-chan *clientContent { c.mutex.Lock() defer c.mutex.Unlock() - contentCh := make(chan *client.Content) + contentCh := make(chan *clientContent) if incomplete { if recursive { go c.listIncompleteRecursiveInRoutine(contentCh) @@ -411,7 +410,7 @@ func (c *s3Client) List(recursive, incomplete bool) <-chan *client.Content { return contentCh } -func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) { +func (c *s3Client) listIncompleteInRoutine(contentCh chan *clientContent) { defer close(contentCh) // get bucket and object from URL. b, o := c.url2BucketAndObject() @@ -419,7 +418,7 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) { case b == "" && o == "": buckets, err := c.api.ListBuckets() if err != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(err), } return @@ -428,12 +427,12 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) { for _, bucket := range buckets { for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) { if object.Err != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(object.Err), } return } - content := new(client.Content) + content := &clientContent{} url := *c.targetURL // Join bucket with - incoming object key. url.Path = filepath.Join(string(url.Separator), bucket.Name, object.Key) @@ -459,12 +458,12 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) { isRecursive := false for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) { if object.Err != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(object.Err), } return } - content := new(client.Content) + content := &clientContent{} url := *c.targetURL // Join bucket with - incoming object key. url.Path = filepath.Join(string(url.Separator), b, object.Key) @@ -488,7 +487,7 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) { } } -func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Content) { +func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *clientContent) { defer close(contentCh) // get bucket and object from URL. b, o := c.url2BucketAndObject() @@ -496,7 +495,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte case b == "" && o == "": buckets, err := c.api.ListBuckets() if err != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(err), } return @@ -505,14 +504,14 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte for _, bucket := range buckets { for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) { if object.Err != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(object.Err), } return } url := *c.targetURL url.Path = filepath.Join(url.Path, bucket.Name, object.Key) - content := new(client.Content) + content := &clientContent{} content.URL = url content.Size = object.Size content.Time = object.Initiated @@ -524,7 +523,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte isRecursive := true for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) { if object.Err != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(object.Err), } return @@ -535,7 +534,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte if c.virtualStyle { url.Path = filepath.Join(string(url.Separator), object.Key) } - content := new(client.Content) + content := &clientContent{} content.URL = url content.Size = object.Size content.Time = object.Initiated @@ -545,7 +544,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte } } -func (c *s3Client) listInRoutine(contentCh chan *client.Content) { +func (c *s3Client) listInRoutine(contentCh chan *clientContent) { defer close(contentCh) // get bucket and object from URL. b, o := c.url2BucketAndObject() @@ -553,7 +552,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) { case b == "" && o == "": buckets, err := c.api.ListBuckets() if err != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(err), } return @@ -561,7 +560,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) { for _, bucket := range buckets { url := *c.targetURL url.Path = filepath.Join(url.Path, bucket.Name) - content := new(client.Content) + content := &clientContent{} content.URL = url content.Size = 0 content.Time = bucket.CreationDate @@ -571,11 +570,11 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) { case b != "" && !strings.HasSuffix(c.targetURL.Path, string(c.targetURL.Separator)) && o == "": e := c.api.BucketExists(b) if e != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(e), } } - content := new(client.Content) + content := &clientContent{} content.URL = *c.targetURL content.Type = os.ModeDir contentCh <- content @@ -583,7 +582,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) { metadata, e := c.api.StatObject(b, o) switch e.(type) { case nil: - content := new(client.Content) + content := &clientContent{} content.URL = *c.targetURL content.Time = metadata.LastModified content.Size = metadata.Size @@ -593,12 +592,12 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) { isRecursive := false for object := range c.api.ListObjects(b, o, isRecursive, nil) { if object.Err != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(object.Err), } return } - content := new(client.Content) + content := &clientContent{} url := *c.targetURL // Join bucket and incoming object key. url.Path = filepath.Join(string(url.Separator), b, object.Key) @@ -623,7 +622,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) { } } -func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) { +func (c *s3Client) listRecursiveInRoutine(contentCh chan *clientContent) { defer close(contentCh) // get bucket and object from URL. b, o := c.url2BucketAndObject() @@ -631,7 +630,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) { case b == "" && o == "": buckets, err := c.api.ListBuckets() if err != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(err), } return @@ -639,7 +638,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) { for _, bucket := range buckets { bucketURL := *c.targetURL bucketURL.Path = filepath.Join(bucketURL.Path, bucket.Name) - contentCh <- &client.Content{ + contentCh <- &clientContent{ URL: bucketURL, Type: os.ModeDir, Time: bucket.CreationDate, @@ -647,12 +646,12 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) { isRecursive := true for object := range c.api.ListObjects(bucket.Name, o, isRecursive, nil) { if object.Err != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(object.Err), } continue } - content := new(client.Content) + content := &clientContent{} objectURL := *c.targetURL objectURL.Path = filepath.Join(objectURL.Path, bucket.Name, object.Key) content.URL = objectURL @@ -666,12 +665,12 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) { isRecursive := true for object := range c.api.ListObjects(b, o, isRecursive, nil) { if object.Err != nil { - contentCh <- &client.Content{ + contentCh <- &clientContent{ Err: probe.NewError(object.Err), } continue } - content := new(client.Content) + content := &clientContent{} url := *c.targetURL // Join bucket and incoming object key. url.Path = filepath.Join(string(url.Separator), b, object.Key) diff --git a/pkg/client/s3/s3_test.go b/client-s3_test.go similarity index 95% rename from pkg/client/s3/s3_test.go rename to client-s3_test.go index 1d3fdbb5..072c8bf4 100644 --- a/pkg/client/s3/s3_test.go +++ b/client-s3_test.go @@ -14,7 +14,7 @@ * limitations under the License. */ -package s3 +package main // bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests import ( @@ -23,11 +23,8 @@ import ( "net/http" "net/http/httptest" "strconv" - "testing" "time" - "github.com/minio/mc/pkg/client" - . "gopkg.in/check.v1" ) @@ -168,26 +165,20 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -func Test(t *testing.T) { TestingT(t) } - -type MySuite struct{} - -var _ = Suite(&MySuite{}) - // Test bucket operations. -func (s *MySuite) TestBucketOperations(c *C) { +func (s *TestSuite) TestBucketOperations(c *C) { bucket := bucketHandler(bucketHandler{ resource: "/bucket/", }) server := httptest.NewServer(bucket) defer server.Close() - conf := new(client.Config) + conf := new(Config) conf.HostURL = server.URL + bucket.resource conf.AccessKey = "WLGDGYAQYIGI833EV05A" conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF" conf.Signature = "S3v4" - s3c, err := New(conf) + s3c, err := s3New(conf) c.Assert(err, IsNil) err = s3c.MakeBucket("us-east-1") @@ -197,7 +188,7 @@ func (s *MySuite) TestBucketOperations(c *C) { c.Assert(err, IsNil) conf.HostURL = server.URL + string(s3c.GetURL().Separator) - s3c, err = New(conf) + s3c, err = s3New(conf) c.Assert(err, IsNil) for content := range s3c.List(false, false) { @@ -206,7 +197,7 @@ func (s *MySuite) TestBucketOperations(c *C) { } conf.HostURL = server.URL + "/bucket" - s3c, err = New(conf) + s3c, err = s3New(conf) c.Assert(err, IsNil) for content := range s3c.List(false, false) { @@ -215,7 +206,7 @@ func (s *MySuite) TestBucketOperations(c *C) { } conf.HostURL = server.URL + "/bucket/" - s3c, err = New(conf) + s3c, err = s3New(conf) c.Assert(err, IsNil) for content := range s3c.List(false, false) { @@ -225,7 +216,7 @@ func (s *MySuite) TestBucketOperations(c *C) { } // Test all object operations. -func (s *MySuite) TestObjectOperations(c *C) { +func (s *TestSuite) TestObjectOperations(c *C) { object := objectHandler(objectHandler{ resource: "/bucket/object", data: []byte("Hello, World"), @@ -233,12 +224,12 @@ func (s *MySuite) TestObjectOperations(c *C) { server := httptest.NewServer(object) defer server.Close() - conf := new(client.Config) + conf := new(Config) conf.HostURL = server.URL + object.resource conf.AccessKey = "WLGDGYAQYIGI833EV05A" conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF" conf.Signature = "S3v4" - s3c, err := New(conf) + s3c, err := s3New(conf) c.Assert(err, IsNil) var reader io.Reader diff --git a/pkg/client/client.go b/client.go similarity index 90% rename from pkg/client/client.go rename to client.go index fd498b29..e72fef96 100644 --- a/pkg/client/client.go +++ b/client.go @@ -14,7 +14,7 @@ * limitations under the License. */ -package client +package main import ( "io" @@ -27,8 +27,8 @@ import ( // Client - client interface type Client interface { // Common operations - Stat() (content *Content, err *probe.Error) - List(recursive, incomplete bool) <-chan *Content + Stat() (content *clientContent, err *probe.Error) + List(recursive, incomplete bool) <-chan *clientContent // Bucket operations MakeBucket(region string) *probe.Error @@ -47,12 +47,12 @@ type Client interface { Remove(incomplete bool) *probe.Error // GetURL returns back internal url - GetURL() URL + GetURL() clientURL } // Content container for content metadata -type Content struct { - URL URL +type clientContent struct { + URL clientURL Time time.Time Size int64 Type os.FileMode diff --git a/common-methods.go b/common-methods.go index d24fc5da..62a539e2 100644 --- a/common-methods.go +++ b/common-methods.go @@ -23,15 +23,12 @@ import ( "runtime" "strings" - "github.com/minio/mc/pkg/client" - "github.com/minio/mc/pkg/client/fs" - "github.com/minio/mc/pkg/client/s3" "github.com/minio/minio/pkg/probe" ) // Check if the target URL represents folder. It may or may not exist yet. func isTargetURLDir(targetURL string) bool { - targetURLParse := client.NewURL(targetURL) + targetURLParse := newURL(targetURL) _, targetContent, err := url2Stat(targetURL) if err != nil { _, aliasedTargetURL, _ := mustExpandAlias(targetURL) @@ -101,12 +98,12 @@ func putTargetStream(urlStr string, reader io.Reader, size int64) (int64, *probe // newClientFromAlias gives a new client interface for matching // alias entry in the mc config file. If no matching host config entry // is found, fs client is returned. -func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Error) { +func newClientFromAlias(alias string, urlStr string) (Client, *probe.Error) { hostCfg := mustGetHostConfig(alias) if hostCfg == nil { // No matching host config. So we treat it like a // filesystem. - fsClient, err := fs.New(urlStr) + fsClient, err := fsNew(urlStr) if err != nil { return nil, err.Trace(alias, urlStr) } @@ -115,7 +112,7 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro // We have a valid alias and hostConfig. We populate the // credentials from the match found in the config file. - s3Config := new(client.Config) + s3Config := new(Config) s3Config.AccessKey = hostCfg.AccessKey s3Config.SecretKey = hostCfg.SecretKey s3Config.Signature = hostCfg.API @@ -125,7 +122,7 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro s3Config.HostURL = urlStr s3Config.Debug = globalDebug - s3Client, err := s3.New(s3Config) + s3Client, err := s3New(s3Config) if err != nil { return nil, err.Trace(alias, urlStr) } @@ -136,7 +133,7 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro var urlRgx = regexp.MustCompile("^https?://") // newClient gives a new client interface -func newClient(aliasedURL string) (client.Client, *probe.Error) { +func newClient(aliasedURL string) (Client, *probe.Error) { alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL) if err != nil { return nil, err.Trace(aliasedURL) diff --git a/config-fix.go b/config-fix.go index 60ca3e2c..b405b238 100644 --- a/config-fix.go +++ b/config-fix.go @@ -20,7 +20,6 @@ import ( "fmt" "strings" - "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" "github.com/minio/minio/pkg/quick" ) @@ -132,7 +131,7 @@ func fixConfigV6ForHosts() { newCfgV6.Aliases[k] = v } - url := new(client.URL) + url := &clientURL{} // Copy hosts. for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts { // Already fixed - Copy and move on. diff --git a/config-utils.go b/config-utils.go index 15aaafbc..ae1e6f21 100644 --- a/config-utils.go +++ b/config-utils.go @@ -1,10 +1,24 @@ +/* + * Minio Client (C) 2015, 2016 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 ( "regexp" "strings" - - "github.com/minio/mc/pkg/client" ) // isValidSecretKey - validate secret key. @@ -30,7 +44,7 @@ func isValidHostURL(hostURL string) bool { if strings.TrimSpace(hostURL) == "" { return false } - url := client.NewURL(hostURL) + url := newURL(hostURL) if url.Scheme != "https" && url.Scheme != "http" { return false } diff --git a/cp-main.go b/cp-main.go index 4cfe2862..d6f2c62f 100644 --- a/cp-main.go +++ b/cp-main.go @@ -29,7 +29,6 @@ import ( "github.com/fatih/color" "github.com/minio/cli" - "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" "github.com/minio/minio/pkg/probe" "github.com/minio/pb" @@ -313,17 +312,17 @@ func doCopySession(session *sessionV6) { switch cpURLs.Error.ToGoError().(type) { // Handle this specifically for filesystem related // errors. - case client.BrokenSymlink: + case BrokenSymlink: continue - case client.TooManyLevelsSymlink: + case TooManyLevelsSymlink: continue - case client.PathNotFound: + case PathNotFound: continue - case client.PathInsufficientPermission: + case PathInsufficientPermission: continue - case client.ObjectAlreadyExists: + case ObjectAlreadyExists: continue - case client.BucketDoesNotExist: + case BucketDoesNotExist: continue } // For critical errors we should exit. Session diff --git a/cp-url-syntax.go b/cp-url-syntax.go index fe69175e..bde54aa8 100644 --- a/cp-url-syntax.go +++ b/cp-url-syntax.go @@ -20,7 +20,6 @@ import ( "fmt" "github.com/minio/cli" - "github.com/minio/mc/pkg/client" ) func checkCopySyntax(ctx *cli.Context) { @@ -40,7 +39,7 @@ func checkCopySyntax(ctx *cli.Context) { /****** Generic Invalid Rules *******/ // Check if bucket name is passed for URL type arguments. - url := client.NewURL(tgtURL) + url := newURL(tgtURL) if url.Host != "" { // This check is for type URL. if !isURLVirtualHostStyle(url.Host) { diff --git a/cp-url.go b/cp-url.go index c178d3e4..2593b766 100644 --- a/cp-url.go +++ b/cp-url.go @@ -20,15 +20,14 @@ import ( "path/filepath" "strings" - "github.com/minio/mc/pkg/client" "github.com/minio/minio/pkg/probe" ) type copyURLs struct { SourceAlias string - SourceContent *client.Content + SourceContent *clientContent TargetAlias string - TargetContent *client.Content + TargetContent *clientContent Error *probe.Error `json:"-"` } @@ -57,7 +56,7 @@ const ( copyURLsTypeD ) -// guessCopyURLType guesses the type of URL. This approach all allows prepareURL +// guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL // functions to accurately report failure causes. func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (copyURLsType, *probe.Error) { if len(sourceURLs) == 1 { // 1 Source, 1 Target @@ -90,11 +89,11 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) ( } // SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f) -// prepareCopyURLsTypeA - prepares target and source URLs for copying. +// prepareCopyURLsTypeA - prepares target and source clientURLs for copying. func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs { - // Extract alias before fiddling with the URL. + // Extract alias before fiddling with the clientURL. sourceAlias, _, _ := mustExpandAlias(sourceURL) - // Find alias and expanded URL. + // Find alias and expanded clientURL. targetAlias, targetURL, _ := mustExpandAlias(targetURL) _, sourceContent, err := url2Stat(sourceURL) @@ -116,21 +115,21 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs { } // prepareCopyContentTypeA - makes CopyURLs content for copying. -func makeCopyContentTypeA(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs { +func makeCopyContentTypeA(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs { return copyURLs{ SourceAlias: sourceAlias, SourceContent: sourceContent, TargetAlias: targetAlias, - TargetContent: &client.Content{URL: *client.NewURL(targetURL)}, + TargetContent: &clientContent{URL: *newURL(targetURL)}, } } // SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A -// prepareCopyURLsTypeB - prepares target and source URLs for copying. +// prepareCopyURLsTypeB - prepares target and source clientURLs for copying. func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs { - // Extract alias before fiddling with the URL. + // Extract alias before fiddling with the clientURL. sourceAlias, _, _ := mustExpandAlias(sourceURL) - // Find alias and expanded URL. + // Find alias and expanded clientURL. targetAlias, targetURL, _ := mustExpandAlias(targetURL) _, sourceContent, err := url2Stat(sourceURL) @@ -152,19 +151,19 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs { } // makeCopyContentTypeB - CopyURLs content for copying. -func makeCopyContentTypeB(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs { +func makeCopyContentTypeB(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs { // All OK.. We can proceed. Type B: source is a file, target is a folder and exists. - targetURLParse := client.NewURL(targetURL) + targetURLParse := newURL(targetURL) targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path))) return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String()) } // SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A -// prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying. +// prepareCopyRecursiveURLTypeC - prepares target and source clientURLs for copying. func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs { - // Extract alias before fiddling with the URL. + // Extract alias before fiddling with the clientURL. sourceAlias, _, _ := mustExpandAlias(sourceURL) - // Find alias and expanded URL. + // Find alias and expanded clientURL. targetAlias, targetURL, _ := mustExpandAlias(targetURL) copyURLsCh := make(chan copyURLs) @@ -197,7 +196,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan } // makeCopyContentTypeC - CopyURLs content for copying. -func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs { +func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs { newSourceURL := sourceContent.URL pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator)) newSourceSuffix := filepath.ToSlash(newSourceURL.Path) @@ -210,7 +209,7 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceConten } // MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B -// prepareCopyURLsTypeE - prepares target and source URLs for copying. +// prepareCopyURLsTypeE - prepares target and source clientURLs for copying. func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs { copyURLsCh := make(chan copyURLs) go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) { @@ -224,7 +223,7 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo return copyURLsCh } -// prepareCopyURLs - prepares target and source URLs for copying. +// prepareCopyURLs - prepares target and source clientURLs for copying. func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs { copyURLsCh := make(chan copyURLs) go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) { diff --git a/diff-main.go b/diff-main.go index 23938b02..13dd0893 100644 --- a/diff-main.go +++ b/diff-main.go @@ -23,7 +23,6 @@ import ( "github.com/fatih/color" "github.com/minio/cli" - "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" "github.com/minio/minio/pkg/probe" ) @@ -144,11 +143,11 @@ func checkDiffSyntax(ctx *cli.Context) { // doDiffMain runs the diff. func doDiffMain(firstURL, secondURL string) { // Source and targets are always directories - sourceSeparator := string(client.NewURL(firstURL).Separator) + sourceSeparator := string(newURL(firstURL).Separator) if !strings.HasSuffix(firstURL, sourceSeparator) { firstURL = firstURL + sourceSeparator } - targetSeparator := string(client.NewURL(secondURL).Separator) + targetSeparator := string(newURL(secondURL).Separator) if !strings.HasSuffix(secondURL, targetSeparator) { secondURL = secondURL + targetSeparator } @@ -173,7 +172,7 @@ func doDiffMain(firstURL, secondURL string) { if sourceContent.Err != nil { switch sourceContent.Err.ToGoError().(type) { // Handle this specifically for filesystem related errors. - case client.BrokenSymlink, client.TooManyLevelsSymlink, client.PathNotFound, client.PathInsufficientPermission: + case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, PathInsufficientPermission: errorIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL)) default: fatalIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL)) diff --git a/difference.go b/difference.go index d46265cb..c96a043f 100644 --- a/difference.go +++ b/difference.go @@ -19,7 +19,6 @@ package main import ( "os" - "github.com/minio/mc/pkg/client" "github.com/minio/minio/pkg/probe" ) @@ -49,7 +48,7 @@ func objectDifferenceFactory(targetAlias, targetURL string) (objectDifference, * current := targetURL reachedEOF := false ok := false - var content *client.Content + var content *clientContent difference := func(suffix string, srcType os.FileMode, srcSize int64) (string, *probe.Error) { if reachedEOF { diff --git a/pkg/client/fs/path-utils.go b/fs-pathutils.go similarity index 98% rename from pkg/client/fs/path-utils.go rename to fs-pathutils.go index 262acac7..411d9c75 100644 --- a/pkg/client/fs/path-utils.go +++ b/fs-pathutils.go @@ -16,7 +16,7 @@ * limitations under the License. */ -package fs +package main func normalizePath(path string) string { return path diff --git a/pkg/client/fs/path-utils_windows.go b/fs-pathutils_window.go similarity index 98% rename from pkg/client/fs/path-utils_windows.go rename to fs-pathutils_window.go index 69f2f105..68aab579 100644 --- a/pkg/client/fs/path-utils_windows.go +++ b/fs-pathutils_window.go @@ -16,7 +16,7 @@ * limitations under the License. */ -package fs +package main import ( "path/filepath" diff --git a/ls-main.go b/ls-main.go index 973f872b..c497efee 100644 --- a/ls-main.go +++ b/ls-main.go @@ -21,7 +21,6 @@ import ( "github.com/fatih/color" "github.com/minio/cli" - "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" ) @@ -127,7 +126,7 @@ func mainList(ctx *cli.Context) { } for _, targetURL := range args { - var clnt client.Client + var clnt Client clnt, err := newClient(targetURL) fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.") diff --git a/ls.go b/ls.go index 8f8c5655..33f607c6 100644 --- a/ls.go +++ b/ls.go @@ -25,7 +25,6 @@ import ( "time" "github.com/dustin/go-humanize" - "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" "github.com/minio/minio/pkg/probe" ) @@ -67,7 +66,7 @@ func (c contentMessage) JSON() string { } // parseContent parse client Content container into printer struct. -func parseContent(c *client.Content) contentMessage { +func parseContent(c *clientContent) contentMessage { content := contentMessage{} content.Time = c.Time.Local() @@ -105,7 +104,7 @@ func parseContent(c *client.Content) contentMessage { } // doList - list all entities inside a folder. -func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error { +func doList(clnt Client, isRecursive, isIncomplete bool) *probe.Error { prefixPath := clnt.GetURL().Path separator := string(clnt.GetURL().Separator) if !strings.HasSuffix(prefixPath, separator) { @@ -115,16 +114,16 @@ func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error { if content.Err != nil { switch content.Err.ToGoError().(type) { // handle this specifically for filesystem related errors. - case client.BrokenSymlink: + case BrokenSymlink: errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.") continue - case client.TooManyLevelsSymlink: + case TooManyLevelsSymlink: errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.") continue - case client.PathNotFound: + case PathNotFound: errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") continue - case client.PathInsufficientPermission: + case PathInsufficientPermission: errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") continue } diff --git a/mirror-main.go b/mirror-main.go index 58eaadc9..94abcdc3 100644 --- a/mirror-main.go +++ b/mirror-main.go @@ -28,7 +28,6 @@ import ( "github.com/fatih/color" "github.com/minio/cli" - "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" "github.com/minio/minio/pkg/probe" "github.com/minio/pb" @@ -297,17 +296,17 @@ func doMirrorSession(session *sessionV6) { switch sURLs.Error.ToGoError().(type) { // Handle this specifically for filesystem related // errors. - case client.BrokenSymlink: + case BrokenSymlink: continue - case client.TooManyLevelsSymlink: + case TooManyLevelsSymlink: continue - case client.PathNotFound: + case PathNotFound: continue - case client.PathInsufficientPermission: + case PathInsufficientPermission: continue - case client.ObjectAlreadyExists: + case ObjectAlreadyExists: continue - case client.BucketDoesNotExist: + case BucketDoesNotExist: continue } // For critical errors we should exit. Session diff --git a/mirror-url.go b/mirror-url.go index 95891e31..b2632d6e 100644 --- a/mirror-url.go +++ b/mirror-url.go @@ -21,15 +21,14 @@ import ( "strings" "github.com/minio/cli" - "github.com/minio/mc/pkg/client" "github.com/minio/minio/pkg/probe" ) type mirrorURLs struct { SourceAlias string - SourceContent *client.Content + SourceContent *clientContent TargetAlias string - TargetContent *client.Content + TargetContent *clientContent Error *probe.Error `json:"-"` } @@ -75,7 +74,7 @@ func checkMirrorSyntax(ctx *cli.Context) { fatalIf(errInvalidArgument().Trace(), "Invalid target arguments to mirror command.") } - url := client.NewURL(tgtURL) + url := newURL(tgtURL) if url.Host != "" { if !isURLVirtualHostStyle(url.Host) { if url.Path == string(url.Separator) { @@ -85,19 +84,19 @@ func checkMirrorSyntax(ctx *cli.Context) { } } _, _, err = url2Stat(tgtURL) - // we die on any error other than client.PathNotFound - destination directory need not exist. - if _, ok := err.ToGoError().(client.PathNotFound); !ok { + // we die on any error other than PathNotFound - destination directory need not exist. + if _, ok := err.ToGoError().(PathNotFound); !ok { fatalIf(err.Trace(tgtURL), fmt.Sprintf("Unable to stat %s", tgtURL)) } } func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirrorURLsCh chan<- mirrorURLs) { // source and targets are always directories - sourceSeparator := string(client.NewURL(sourceURL).Separator) + sourceSeparator := string(newURL(sourceURL).Separator) if !strings.HasSuffix(sourceURL, sourceSeparator) { sourceURL = sourceURL + sourceSeparator } - targetSeparator := string(client.NewURL(targetURL).Separator) + targetSeparator := string(newURL(targetURL).Separator) if !strings.HasSuffix(targetURL, targetSeparator) { targetURL = targetURL + targetSeparator } @@ -151,7 +150,7 @@ func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirror } // either available only in source or size differs and force is set targetPath := urlJoinPath(targetURL, suffix) - targetContent := &client.Content{URL: *client.NewURL(targetPath)} + targetContent := &clientContent{URL: *newURL(targetPath)} mirrorURLsCh <- mirrorURLs{ SourceAlias: sourceAlias, SourceContent: sourceContent, diff --git a/pkg/client/client_test.go b/pkg/client/client_test.go deleted file mode 100644 index 3cfc32ae..00000000 --- a/pkg/client/client_test.go +++ /dev/null @@ -1,69 +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 client - -import ( - "testing" - - . "gopkg.in/check.v1" -) - -func Test(t *testing.T) { TestingT(t) } - -type MySuite struct{} - -var _ = Suite(&MySuite{}) - -func (s *MySuite) TestURLParse(c *C) { - u := NewURL("http://s3.example.com") - c.Assert(u.Scheme, Equals, "http") - c.Assert(u.Host, Equals, "s3.example.com") - c.Assert(u.Path, Equals, "/") - c.Assert(u.SchemeSeparator, Equals, "://") - - u = NewURL("http://s3.example.com/path/new") - c.Assert(u.Scheme, Equals, "http") - c.Assert(u.Host, Equals, "s3.example.com") - c.Assert(u.Path, Equals, "/path/new") - c.Assert(u.SchemeSeparator, Equals, "://") - - u = NewURL(":::://s3.example.com/path/new") - c.Assert(u.Scheme, Equals, "") - c.Assert(u.Host, Equals, "") - c.Assert(u.Path, Equals, ":::://s3.example.com/path/new") - c.Assert(u.SchemeSeparator, Equals, "") - - u = NewURL("localhost:9000") - c.Assert(u.Scheme, Equals, "") - c.Assert(u.Host, Equals, "") - c.Assert(u.Path, Equals, "localhost:9000") - c.Assert(u.SchemeSeparator, Equals, "") -} - -func (s *MySuite) TestPathParse(c *C) { - u := NewURL("path/test") - c.Assert(u.Scheme, Equals, "") - c.Assert(u.Host, Equals, "") - c.Assert(u.Path, Equals, "path/test") - c.Assert(u.SchemeSeparator, Equals, "") - - u = NewURL("/path/test") - c.Assert(u.Scheme, Equals, "") - c.Assert(u.Host, Equals, "") - c.Assert(u.Path, Equals, "/path/test") - c.Assert(u.SchemeSeparator, Equals, "") -} diff --git a/pkg/client/fs/.gitignore b/pkg/client/fs/.gitignore deleted file mode 100644 index daac6aea..00000000 --- a/pkg/client/fs/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*# \ No newline at end of file diff --git a/pkg/client/fs/fs-common.go b/pkg/client/fs/fs-common.go deleted file mode 100644 index 3a67bc4b..00000000 --- a/pkg/client/fs/fs-common.go +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this fs 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 fs - -import ( - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/minio/mc/pkg/client" - "github.com/minio/minio/pkg/probe" -) - -// toClientError error constructs a typed client error for known filesystem errors. -func (f *fsClient) toClientError(e error, fpath string) *probe.Error { - if os.IsPermission(e) { - return probe.NewError(client.PathInsufficientPermission{Path: fpath}) - } - if os.IsNotExist(e) { - return probe.NewError(client.PathNotFound{Path: fpath}) - } - return probe.NewError(e) -} - -// handle windows symlinks - eg: junction files. -func (f *fsClient) handleWindowsSymlinks(fpath string) (os.FileInfo, *probe.Error) { - // On windows there are directory symlinks which are called junction files. - // These files carry special meaning on windows they cannot be, - // accessed with regular operations. - file, e := os.Lstat(fpath) - if e != nil { - err := f.toClientError(e, fpath) - return nil, err.Trace(fpath) - } - return file, nil -} - -// fsStat - wrapper function to get file stat. -func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) { - fpath := f.PathURL.Path - // Golang strips trailing / if you clean(..) or - // EvalSymlinks(..). Adding '.' prevents it from doing so. - if strings.HasSuffix(fpath, string(f.PathURL.Separator)) { - fpath = fpath + "." - } - fpath, e := filepath.EvalSymlinks(fpath) - if e != nil { - if os.IsPermission(e) { - if runtime.GOOS == "windows" { - return f.handleWindowsSymlinks(f.PathURL.Path) - } - return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path}) - } - err := f.toClientError(e, f.PathURL.Path) - return nil, err.Trace(fpath) - } - st, e := os.Stat(fpath) - if e != nil { - if os.IsPermission(e) { - if runtime.GOOS == "windows" { - return f.handleWindowsSymlinks(fpath) - } - return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path}) - } - if os.IsNotExist(e) { - return nil, probe.NewError(client.PathNotFound{Path: f.PathURL.Path}) - } - return nil, probe.NewError(e) - } - return st, nil -} diff --git a/pkg/client/fs/fs-utils.go b/pkg/client/fs/fs-utils.go deleted file mode 100644 index febace27..00000000 --- a/pkg/client/fs/fs-utils.go +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this fs 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 fs - -import ( - "errors" - "os" - "path/filepath" - "sort" -) - -// byDirName implements sort.Interface. -type byDirName []os.FileInfo - -func (f byDirName) Len() int { return len(f) } -func (f byDirName) Less(i, j int) bool { - // For directory add an ending separator fortrue lexical order. - if f[i].Mode().IsDir() { - return f[i].Name()+string(filepath.Separator) < f[j].Name() - } - // For directory add an ending separator for true lexical order. - if f[j].Mode().IsDir() { - return f[i].Name() < f[j].Name()+string(filepath.Separator) - } - return f[i].Name() < f[j].Name() -} -func (f byDirName) Swap(i, j int) { f[i], f[j] = f[j], f[i] } - -// readDir reads the directory named by dirname and returns -// a list of sorted directory entries. -func readDir(dirname string) ([]os.FileInfo, error) { - f, e := os.Open(dirname) - if e != nil { - return nil, e - } - list, e := f.Readdir(-1) - if e != nil { - return nil, e - } - if e = f.Close(); e != nil { - return nil, e - } - sort.Sort(byDirName(list)) - return list, nil -} - -// readDirNames reads the directory named by dirname and returns -// a sorted list of directory entries. -func readDirNames(dirname string) ([]string, error) { - names, e := readDirUnsortedNames(dirname) - if e != nil { - return nil, e - } - sort.Strings(names) - return names, nil -} - -// getRealName - gets the proper filename for sorting purposes -// Readdir() filters out directory names without separators, add -// them back for proper sorting results. -func getRealName(info os.FileInfo) string { - if info.IsDir() { - // Make sure directory has its end separator. - return info.Name() + string(filepath.Separator) - } - return info.Name() -} - -// readDirUnsortedNames reads the directory named by dirname and -// return a unsorted list of directory entries. -func readDirUnsortedNames(dirname string) ([]string, error) { - f, e := os.Open(dirname) - if e != nil { - return nil, e - } - nameInfos, e := f.Readdir(-1) - if e != nil { - return nil, e - } - if e = f.Close(); e != nil { - return nil, e - } - var names []string - for _, nameInfo := range nameInfos { - names = append(names, getRealName(nameInfo)) - } - return names, nil -} - -// walk walks the file tree rooted at root, calling walkFn for each file or -// directory in the tree, including root. -func walk(root string, walkFn walkFunc) error { - info, e := os.Lstat(root) - if e != nil { - return walkFn(root, nil, e) - } - return walkInternal(root, info, walkFn) -} - -// WalkFunc is the type of the function called for each file or directory -// visited by Walk. The path argument contains the argument to Walk as a -// prefix; that is, if Walk is called with "dir", which is a directory -// containing the file "a", the walk function will be called with argument -// "dir/a". The info argument is the os.FileInfo for the named path. -type walkFunc func(path string, info os.FileInfo, e error) error - -// ErrSkipDir is used as a return value from WalkFuncs to indicate that -// the directory named in the call is to be skipped. It is not returned -// as an error by any function. -var errSkipDir = errors.New("skip this directory") - -// ErrSkipFile is used as a return value from WalkFuncs to indicate that -// the file named in the call is to be skipped. It is not returned -// as an error by any function. -var errSkipFile = errors.New("skip this file") - -// walkInternal recursively descends path, calling w. -func walkInternal(path string, info os.FileInfo, walkFn walkFunc) error { - e := walkFn(path, info, nil) - if e != nil { - if info.Mode().IsDir() && e == errSkipDir { - return nil - } - if info.Mode().IsRegular() && e == errSkipFile { - return nil - } - return e - } - if !info.IsDir() { - return nil - } - names, e := readDirNames(path) - if e != nil { - return walkFn(path, info, e) - } - for _, name := range names { - filename := filepath.Join(path, name) - fileInfo, e := os.Lstat(filename) - if e != nil { - if e = walkFn(filename, fileInfo, e); e != nil && e != errSkipDir && e != errSkipFile { - return e - } - } else { - e = walkInternal(filename, fileInfo, walkFn) - if e != nil { - if e == errSkipDir || e == errSkipFile { - return nil - } - return e - } - } - } - return nil -} diff --git a/pkg/client/url.go b/pkg/client/url.go deleted file mode 100644 index 78ff4f83..00000000 --- a/pkg/client/url.go +++ /dev/null @@ -1,162 +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 client - -import ( - "bytes" - "path/filepath" - "regexp" - "runtime" - "strings" -) - -// URL client url structure -type URL struct { - Type URLType - Scheme string - Host string - Path string - SchemeSeparator string - Separator rune -} - -// URLType - enum of different url types -type URLType int - -// enum types -const ( - Object = iota // Minio and S3 compatible cloud storage - Filesystem // POSIX compatible file systems -) - -// Maybe rawurl is of the form scheme:path. (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*) -// If so, return scheme, path; else return "", rawurl. -func getScheme(rawurl string) (scheme, path string) { - urlSplits := strings.Split(rawurl, "://") - if len(urlSplits) == 2 { - scheme, uri := urlSplits[0], "//"+urlSplits[1] - // ignore numbers in scheme - validScheme := regexp.MustCompile("^[a-zA-Z]+$") - if uri != "" { - if validScheme.MatchString(scheme) { - return scheme, uri - } - } - } - return "", rawurl -} - -// Assuming s is of the form [s delimiter s]. -// If so, return s, [delimiter]s or return s, s if cutdelimiter == true -// If no delimiter found return s, "". -func splitSpecial(s string, delimiter string, cutdelimiter bool) (string, string) { - i := strings.Index(s, delimiter) - if i < 0 { - // if delimiter not found return as is. - return s, "" - } - // if delimiter should be removed, remove it. - if cutdelimiter { - return s[0:i], s[i+len(delimiter):] - } - // return split strings with delimiter - return s[0:i], s[i:] -} - -// getHost - extract host from authority string, we do not support ftp style username@ yet. -func getHost(authority string) (host string) { - i := strings.LastIndex(authority, "@") - if i >= 0 { - // TODO support, username@password style userinfo, useful for ftp support. - return - } - return authority -} - -// NewURL returns an abstracted URL for filesystems and object storage. -func NewURL(urlStr string) *URL { - scheme, rest := getScheme(urlStr) - rest, _ = splitSpecial(rest, "?", true) - if strings.HasPrefix(rest, "//") { - // if rest has '//' prefix, skip them - var authority string - authority, rest = splitSpecial(rest[2:], "/", false) - if rest == "" { - rest = "/" - } - host := getHost(authority) - if host != "" && (scheme == "http" || scheme == "https") { - return &URL{ - Scheme: scheme, - Type: Object, - Host: host, - Path: rest, - SchemeSeparator: "://", - Separator: '/', - } - } - } - return &URL{ - Type: Filesystem, - Path: rest, - Separator: filepath.Separator, - } -} - -// JoinURLs join two input urls and returns a url -func JoinURLs(url1, url2 *URL) *URL { - var url1Path, url2Path string - url1Path = filepath.ToSlash(url1.Path) - url2Path = filepath.ToSlash(url2.Path) - if strings.HasSuffix(url1Path, "/") { - url1.Path = url1Path + strings.TrimPrefix(url2Path, "/") - } else { - url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/") - } - return url1 -} - -// String convert URL into its canonical form. -func (u URL) String() string { - var buf bytes.Buffer - // if fileystem no translation needed, return as is. - if u.Type == Filesystem { - return u.Path - } - // if Object convert from any non standard paths to a supported URL path style. - if u.Type == Object { - buf.WriteString(u.Scheme) - buf.WriteByte(':') - buf.WriteString("//") - if h := u.Host; h != "" { - buf.WriteString(h) - } - switch runtime.GOOS { - case "windows": - if u.Path != "" && u.Path[0] != '\\' && u.Host != "" && u.Path[0] != '/' { - buf.WriteByte('/') - } - buf.WriteString(strings.Replace(u.Path, "\\", "/", -1)) - default: - if u.Path != "" && u.Path[0] != '/' && u.Host != "" { - buf.WriteByte('/') - } - buf.WriteString(u.Path) - } - } - return buf.String() -} diff --git a/share-upload-main.go b/share-upload-main.go index 466c5386..a9014f13 100644 --- a/share-upload-main.go +++ b/share-upload-main.go @@ -22,7 +22,6 @@ import ( "time" "github.com/minio/cli" - "github.com/minio/mc/pkg/client" "github.com/minio/minio/pkg/probe" ) @@ -101,7 +100,7 @@ func checkShareUploadSyntax(ctx *cli.Context) { } for _, targetURL := range ctx.Args() { - url := client.NewURL(targetURL) + url := newURL(targetURL) if strings.HasSuffix(targetURL, string(url.Separator)) && !isRecursive { fatalIf(errInvalidArgument().Trace(targetURL), "Use --recursive option to generate curl command for prefixes.") @@ -111,7 +110,7 @@ func checkShareUploadSyntax(ctx *cli.Context) { // makeCurlCmd constructs curl command-line. func makeCurlCmd(key string, isRecursive bool, uploadInfo map[string]string) string { - URL := client.NewURL(key) + URL := newURL(key) postURL := URL.Scheme + URL.SchemeSeparator + URL.Host + string(URL.Separator) if !isBucketVirtualStyle(URL.Host) { postURL = postURL + uploadInfo["bucket"] diff --git a/url.go b/url.go index f6291299..72a2a5a1 100644 --- a/url.go +++ b/url.go @@ -17,14 +17,153 @@ package main import ( + "bytes" "mime" "path/filepath" + "regexp" + "runtime" "strings" - "github.com/minio/mc/pkg/client" "github.com/minio/minio/pkg/probe" ) +// url client url structure +type clientURL struct { + Type clientURLType + Scheme string + Host string + Path string + SchemeSeparator string + Separator rune +} + +// clientURLType - enum of different url types +type clientURLType int + +// enum types +const ( + objectStorage = iota // Minio and S3 compatible cloud storage + fileSystem // POSIX compatible file systems +) + +// Maybe rawurl is of the form scheme:path. (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*) +// If so, return scheme, path; else return "", rawurl. +func getScheme(rawurl string) (scheme, path string) { + urlSplits := strings.Split(rawurl, "://") + if len(urlSplits) == 2 { + scheme, uri := urlSplits[0], "//"+urlSplits[1] + // ignore numbers in scheme + validScheme := regexp.MustCompile("^[a-zA-Z]+$") + if uri != "" { + if validScheme.MatchString(scheme) { + return scheme, uri + } + } + } + return "", rawurl +} + +// Assuming s is of the form [s delimiter s]. +// If so, return s, [delimiter]s or return s, s if cutdelimiter == true +// If no delimiter found return s, "". +func splitSpecial(s string, delimiter string, cutdelimiter bool) (string, string) { + i := strings.Index(s, delimiter) + if i < 0 { + // if delimiter not found return as is. + return s, "" + } + // if delimiter should be removed, remove it. + if cutdelimiter { + return s[0:i], s[i+len(delimiter):] + } + // return split strings with delimiter + return s[0:i], s[i:] +} + +// getHost - extract host from authority string, we do not support ftp style username@ yet. +func getHost(authority string) (host string) { + i := strings.LastIndex(authority, "@") + if i >= 0 { + // TODO support, username@password style userinfo, useful for ftp support. + return + } + return authority +} + +// newURL returns an abstracted URL for filesystems and object storage. +func newURL(urlStr string) *clientURL { + scheme, rest := getScheme(urlStr) + rest, _ = splitSpecial(rest, "?", true) + if strings.HasPrefix(rest, "//") { + // if rest has '//' prefix, skip them + var authority string + authority, rest = splitSpecial(rest[2:], "/", false) + if rest == "" { + rest = "/" + } + host := getHost(authority) + if host != "" && (scheme == "http" || scheme == "https") { + return &clientURL{ + Scheme: scheme, + Type: objectStorage, + Host: host, + Path: rest, + SchemeSeparator: "://", + Separator: '/', + } + } + } + return &clientURL{ + Type: fileSystem, + Path: rest, + Separator: filepath.Separator, + } +} + +// joinURLs join two input urls and returns a url +func joinURLs(url1, url2 *clientURL) *clientURL { + var url1Path, url2Path string + url1Path = filepath.ToSlash(url1.Path) + url2Path = filepath.ToSlash(url2.Path) + if strings.HasSuffix(url1Path, "/") { + url1.Path = url1Path + strings.TrimPrefix(url2Path, "/") + } else { + url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/") + } + return url1 +} + +// String convert URL into its canonical form. +func (u clientURL) String() string { + var buf bytes.Buffer + // if fileSystem no translation needed, return as is. + if u.Type == fileSystem { + return u.Path + } + // if objectStorage convert from any non standard paths to a supported URL path style. + if u.Type == objectStorage { + buf.WriteString(u.Scheme) + buf.WriteByte(':') + buf.WriteString("//") + if h := u.Host; h != "" { + buf.WriteString(h) + } + switch runtime.GOOS { + case "windows": + if u.Path != "" && u.Path[0] != '\\' && u.Host != "" && u.Path[0] != '/' { + buf.WriteByte('/') + } + buf.WriteString(strings.Replace(u.Path, "\\", "/", -1)) + default: + if u.Path != "" && u.Path[0] != '/' && u.Host != "" { + buf.WriteByte('/') + } + buf.WriteString(u.Path) + } + } + return buf.String() +} + func isURLVirtualHostStyle(hostURL string) bool { matchS3, _ := filepath.Match("*.s3*.amazonaws.com", hostURL) matchGoogle, _ := filepath.Match("*.storage.googleapis.com", hostURL) @@ -33,13 +172,13 @@ func isURLVirtualHostStyle(hostURL string) bool { // urlJoinPath Join a path to existing URL. func urlJoinPath(url1, url2 string) string { - u1 := client.NewURL(url1) - u2 := client.NewURL(url2) - return client.JoinURLs(u1, u2).String() + u1 := newURL(url1) + u2 := newURL(url2) + return joinURLs(u1, u2).String() } // url2Stat returns stat info for URL. -func url2Stat(urlStr string) (client client.Client, content *client.Content, err *probe.Error) { +func url2Stat(urlStr string) (client Client, content *clientContent, err *probe.Error) { client, err = newClient(urlStr) if err != nil { return nil, nil, err.Trace(urlStr) @@ -92,7 +231,7 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool { // guessURLContentType - guess content-type of the URL. // on failure just return 'application/octet-stream'. func guessURLContentType(urlStr string) string { - url := client.NewURL(urlStr) + url := newURL(urlStr) contentType := mime.TypeByExtension(filepath.Ext(url.Path)) if contentType == "" { contentType = "application/octet-stream" diff --git a/vendor/github.com/minio/minio-go/CONTRIBUTING.md b/vendor/github.com/minio/minio-go/CONTRIBUTING.md index 3a938e85..8b1ee86c 100644 --- a/vendor/github.com/minio/minio-go/CONTRIBUTING.md +++ b/vendor/github.com/minio/minio-go/CONTRIBUTING.md @@ -14,7 +14,9 @@ - Have test cases for the new code. If you have questions about how to do it, please ask in your pull request. - Run `go fmt` - Squash your commits into a single commit. `git rebase -i`. It's okay to force update your pull request. - - Make sure `go test -short -race ./...` and `go build` completes. + - Make sure `go test -race ./...` and `go build` completes. + NOTE: go test runs functional tests and requires you to have a AWS S3 account. Set them as environment variables + ``ACCESS_KEY`` and ``SECRET_KEY``. To run shorter version of the tests please use ``go test -short -race ./...`` * Read [Effective Go](https://github.com/golang/go/wiki/CodeReviewComments) article from Golang project - `minio-go` project is strictly conformant with Golang style diff --git a/vendor/github.com/minio/minio-go/api.go b/vendor/github.com/minio/minio-go/api.go index d52d641b..5f379a07 100644 --- a/vendor/github.com/minio/minio-go/api.go +++ b/vendor/github.com/minio/minio-go/api.go @@ -78,7 +78,7 @@ const ( // NewV2 - instantiate minio client with Amazon S3 signature version // '2' compatibility. -func NewV2(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) { +func NewV2(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (*Client, error) { clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure) if err != nil { return nil, err @@ -90,7 +90,7 @@ func NewV2(endpoint string, accessKeyID, secretAccessKey string, insecure bool) // NewV4 - instantiate minio client with Amazon S3 signature version // '4' compatibility. -func NewV4(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) { +func NewV4(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (*Client, error) { clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure) if err != nil { return nil, err @@ -102,7 +102,7 @@ func NewV4(endpoint string, accessKeyID, secretAccessKey string, insecure bool) // New - instantiate minio client Client, adds automatic verification // of signature. -func New(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) { +func New(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (*Client, error) { clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure) if err != nil { return nil, err @@ -112,7 +112,7 @@ func New(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (C if isGoogleEndpoint(clnt.endpointURL) { clnt.signature = SignatureV2 } - // If Amazon S3 set to signature v2. + // If Amazon S3 set to signature v2.n if isAmazonEndpoint(clnt.endpointURL) { clnt.signature = SignatureV4 } @@ -138,7 +138,14 @@ func privateNew(endpoint, accessKeyID, secretAccessKey string, insecure bool) (* clnt.endpointURL = endpointURL // Instantiate http client and bucket location cache. - clnt.httpClient = &http.Client{} + clnt.httpClient = &http.Client{ + // Setting a sensible time out of 30secs to wait for response + // headers. Request is pro-actively cancelled after 30secs + // with no response. + Timeout: 30 * time.Second, + Transport: http.DefaultTransport, + } + clnt.bucketLocCache = newBucketLocationCache() // Return. @@ -493,46 +500,3 @@ func (c Client) makeTargetURL(bucketName, objectName, bucketLocation string, que return u, nil } - -// CloudStorageClient - Cloud Storage Client interface. -type CloudStorageClient interface { - // Bucket Read/Write/Stat operations. - MakeBucket(bucketName string, cannedACL BucketACL, location string) error - BucketExists(bucketName string) error - RemoveBucket(bucketName string) error - SetBucketACL(bucketName string, cannedACL BucketACL) error - GetBucketACL(bucketName string) (BucketACL, error) - - ListBuckets() ([]BucketInfo, error) - ListObjects(bucket, prefix string, recursive bool, doneCh <-chan struct{}) <-chan ObjectInfo - ListIncompleteUploads(bucket, prefix string, recursive bool, doneCh <-chan struct{}) <-chan ObjectMultipartInfo - - // Object Read/Write/Stat operations. - GetObject(bucketName, objectName string) (reader *Object, err error) - PutObject(bucketName, objectName string, reader io.Reader, contentType string) (n int64, err error) - StatObject(bucketName, objectName string) (ObjectInfo, error) - RemoveObject(bucketName, objectName string) error - RemoveIncompleteUpload(bucketName, objectName string) error - - // File to Object API. - FPutObject(bucketName, objectName, filePath, contentType string) (n int64, err error) - FGetObject(bucketName, objectName, filePath string) error - - // PutObjectWithProgress for progress. - PutObjectWithProgress(bucketName, objectName string, reader io.Reader, contentType string, progress io.Reader) (n int64, err error) - - // Presigned operations. - PresignedGetObject(bucketName, objectName string, expires time.Duration, reqParams url.Values) (presignedURL string, err error) - PresignedPutObject(bucketName, objectName string, expires time.Duration) (presignedURL string, err error) - PresignedPostPolicy(*PostPolicy) (formData map[string]string, err error) - - // Application info. - SetAppInfo(appName, appVersion string) - - // Set custom transport. - SetCustomTransport(customTransport http.RoundTripper) - - // HTTP tracing methods. - TraceOn(traceOutput io.Writer) - TraceOff() -} diff --git a/vendor/github.com/minio/minio-go/api_functional_v2_test.go b/vendor/github.com/minio/minio-go/api_functional_v2_test.go index a3f3411a..3336c041 100644 --- a/vendor/github.com/minio/minio-go/api_functional_v2_test.go +++ b/vendor/github.com/minio/minio-go/api_functional_v2_test.go @@ -1017,7 +1017,13 @@ func TestFunctionalV2(t *testing.T) { if err != nil { t.Fatal("Error: ", err) } - httpClient := &http.Client{} + httpClient := &http.Client{ + // Setting a sensible time out of 30secs to wait for response + // headers. Request is pro-actively cancelled after 30secs + // with no response. + Timeout: 30 * time.Second, + Transport: http.DefaultTransport, + } resp, err = httpClient.Do(req) if err != nil { t.Fatal("Error: ", err) diff --git a/vendor/github.com/minio/minio-go/api_functional_v4_test.go b/vendor/github.com/minio/minio-go/api_functional_v4_test.go index 583ab79b..6c0a4c62 100644 --- a/vendor/github.com/minio/minio-go/api_functional_v4_test.go +++ b/vendor/github.com/minio/minio-go/api_functional_v4_test.go @@ -1045,7 +1045,13 @@ func TestFunctional(t *testing.T) { if err != nil { t.Fatal("Error: ", err) } - httpClient := &http.Client{} + httpClient := &http.Client{ + // Setting a sensible time out of 30secs to wait for response + // headers. Request is pro-actively cancelled after 30secs + // with no response. + Timeout: 30 * time.Second, + Transport: http.DefaultTransport, + } resp, err = httpClient.Do(req) if err != nil { t.Fatal("Error: ", err) diff --git a/vendor/github.com/minio/minio/pkg/ioutils/filepath.go b/vendor/github.com/minio/minio/pkg/ioutils/filepath.go new file mode 100644 index 00000000..41a54f7c --- /dev/null +++ b/vendor/github.com/minio/minio/pkg/ioutils/filepath.go @@ -0,0 +1,143 @@ +/* + * Minio Cloud Storage, (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 ioutils + +import ( + "errors" + "io" + "os" + "path/filepath" + "sort" +) + +// IsDirEmpty Check if a directory is empty +func IsDirEmpty(dirname string) (status bool, err error) { + f, err := os.Open(dirname) + if err == nil { + defer f.Close() + if _, err = f.Readdirnames(1); err == io.EOF { + status = true + err = nil + } + } + + return +} + +// FTW walks the file tree rooted at root, calling walkFn for each file or +// directory in the tree, including root. +func FTW(root string, walkFn FTWFunc) error { + info, err := os.Lstat(root) + if err != nil { + return walkFn(root, nil, err) + } + return walk(root, info, walkFn) +} + +// byName implements sort.Interface for sorting os.FileInfo list. +type byName []os.FileInfo + +func (f byName) Len() int { return len(f) } +func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] } +func (f byName) Less(i, j int) bool { + n1 := f[i].Name() + if f[i].IsDir() { + n1 = n1 + string(os.PathSeparator) + } + + n2 := f[j].Name() + if f[i].IsDir() { + n2 = n2 + string(os.PathSeparator) + } + + return n1 < n2 +} + +// readDir reads the directory named by dirname and returns +// a sorted list of directory entries. +func readDir(dirname string) (fi []os.FileInfo, err error) { + f, err := os.Open(dirname) + if err == nil { + defer f.Close() + if fi, err = f.Readdir(-1); fi != nil { + sort.Sort(byName(fi)) + } + } + + return +} + +// FTWFunc is the type of the function called for each file or directory +// visited by Walk. The path argument contains the argument to Walk as a +// prefix; that is, if Walk is called with "dir", which is a directory +// containing the file "a", the walk function will be called with argument +// "dir/a". The info argument is the os.FileInfo for the named path. +type FTWFunc func(path string, info os.FileInfo, err error) error + +// ErrSkipDir is used as a return value from WalkFuncs to indicate that +// the directory named in the call is to be skipped. It is not returned +// as an error by any function. +var ErrSkipDir = errors.New("skip this directory") + +// ErrSkipFile is used as a return value from WalkFuncs to indicate that +// the file named in the call is to be skipped. It is not returned +// as an error by any function. +var ErrSkipFile = errors.New("skip this file") + +// ErrDirNotEmpty is used to throw error on directories which have atleast one regular +// file or a symlink left +var ErrDirNotEmpty = errors.New("directory not empty") + +// walk recursively descends path, calling walkFn. +func walk(path string, info os.FileInfo, walkFn FTWFunc) error { + err := walkFn(path, info, nil) + if err != nil { + if info.Mode().IsDir() && err == ErrSkipDir { + return nil + } + if info.Mode().IsRegular() && err == ErrSkipFile { + return nil + } + return err + } + + if !info.IsDir() { + return nil + } + + fis, err := readDir(path) + if err != nil { + return walkFn(path, info, err) + } + for _, fileInfo := range fis { + filename := filepath.Join(path, fileInfo.Name()) + if err != nil { + if err := walkFn(filename, fileInfo, err); err != nil && err != ErrSkipDir && err != ErrSkipFile { + return err + } + } else { + err = walk(filename, fileInfo, walkFn) + if err != nil { + if err == ErrSkipDir || err == ErrSkipFile { + return nil + } + return err + } + } + } + return nil +} diff --git a/vendor/github.com/minio/minio/pkg/ioutils/ioutils_test.go b/vendor/github.com/minio/minio/pkg/ioutils/ioutils_test.go new file mode 100644 index 00000000..d316959f --- /dev/null +++ b/vendor/github.com/minio/minio/pkg/ioutils/ioutils_test.go @@ -0,0 +1,43 @@ +/* + * Minio Cloud Storage, (C) 2016 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 ioutils_test + +import ( + "io/ioutil" + "os" + "testing" + + "github.com/minio/minio/pkg/ioutils" + + . "gopkg.in/check.v1" +) + +func Test(t *testing.T) { TestingT(t) } + +type MySuite struct{} + +var _ = Suite(&MySuite{}) + +func (s *MySuite) TestIoutils(c *C) { + path, err := ioutil.TempDir(os.TempDir(), "minio-ioutils_test") + c.Assert(err, IsNil) + defer os.RemoveAll(path) + + status, err := ioutils.IsDirEmpty(path) + c.Assert(err, IsNil) + c.Assert(status, Equals, true) +} diff --git a/vendor/vendor.json b/vendor/vendor.json index e821a469..4c13c8d3 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -39,14 +39,19 @@ }, { "path": "github.com/minio/minio-go", - "revision": "280f16a52008d3ebba1bd64398b9b082e6738386", - "revisionTime": "2016-02-07T03:45:25-08:00" + "revision": "5576cd0f5a276b64973239ebe172aa8d2380f950", + "revisionTime": "2016-02-15T17:55:49-08:00" }, { "path": "github.com/minio/minio/pkg/atomic", "revision": "f98675660bb2049dea7e39e5113f5af29b8f6815", "revisionTime": "2016-02-11T15:54:02-08:00" }, + { + "path": "github.com/minio/minio/pkg/ioutils", + "revision": "eed0149657017f134fa8dacae9026bb816342a48", + "revisionTime": "2016-02-15T17:42:39-08:00" + }, { "path": "github.com/minio/minio/pkg/probe", "revision": "f98675660bb2049dea7e39e5113f5af29b8f6815",