diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 235040a1..c5b5932e 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -32,7 +32,7 @@ }, { "ImportPath": "github.com/minio/minio-go", - "Rev": "a41bd929a5c2451970eb6fa731156d9481f77b1c" + "Rev": "76a773cadcbf32c9d437a2871b1e449b80be255b" }, { "ImportPath": "github.com/minio/minio/pkg/iodine", diff --git a/Godeps/_workspace/src/github.com/minio/minio-go/api.go b/Godeps/_workspace/src/github.com/minio/minio-go/api.go index 912dba38..c428a040 100644 --- a/Godeps/_workspace/src/github.com/minio/minio-go/api.go +++ b/Godeps/_workspace/src/github.com/minio/minio-go/api.go @@ -137,12 +137,30 @@ type Config struct { // Standard options AccessKeyID string SecretAccessKey string - Region string // Optional field. If empty, region is determined automatically. Endpoint string // Advanced options - AcceptType string // specify this to get server response in non XML style if server supports it - Transport http.RoundTripper // custom transport usually for debugging, by default its nil + // Specify this to get server response in non XML style if server supports it + AcceptType string + // Optional field. If empty, region is determined automatically. + Region string + + // Expert options + // + // Set this to override default transport ``http.DefaultTransport`` + // + // This transport is usually needed for debugging OR to add your own + // custom TLS certificates on the client transport, for custom CA's and + // certs which are not part of standard certificate authority + // + // For example :- + // + // tr := &http.Transport{ + // TLSClientConfig: &tls.Config{RootCAs: pool}, + // DisableCompression: true, + // } + // + Transport http.RoundTripper // internal // use SetUserAgent append to default, useful when minio-go is used with in your application @@ -208,8 +226,8 @@ func (a completedParts) Len() int { return len(a) } func (a completedParts) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a completedParts) Less(i, j int) bool { return a[i].PartNumber < a[j].PartNumber } -// MinimumPartSize minimum part size per object after which PutObject behaves internally as multipart -var MinimumPartSize int64 = 1024 * 1024 * 5 +// minimumPartSize minimum part size per object after which PutObject behaves internally as multipart +var minimumPartSize int64 = 1024 * 1024 * 5 // maxParts - unexported right now var maxParts = int64(10000) @@ -226,7 +244,7 @@ var maxPartSize int64 = 1024 * 1024 * 1024 * 5 // maximumPartSize // minimumPartSize // -// if a the partSize after division with maxParts is greater than MinimumPartSize +// if a the partSize after division with maxParts is greater than minimumPartSize // then choose that to be the new part size, if not return MinimumPartSize // // special case where it happens to be that partSize is indeed bigger than the @@ -234,13 +252,13 @@ var maxPartSize int64 = 1024 * 1024 * 1024 * 5 func getPartSize(objectSize int64) int64 { partSize := (objectSize / (maxParts - 1)) // make sure last part has enough buffer and handle this poperly { - if partSize > MinimumPartSize { + if partSize > minimumPartSize { if partSize > maxPartSize { return maxPartSize } return partSize } - return MinimumPartSize + return minimumPartSize } } @@ -419,9 +437,9 @@ func (a api) PutObject(bucket, object, contentType string, size int64, data io.R return err } switch { - case size < MinimumPartSize: + case size < minimumPartSize: // Single Part use case, use PutObject directly - for part := range multiPart(data, MinimumPartSize, nil) { + for part := range multiPart(data, minimumPartSize, nil) { if part.Err != nil { return part.Err } diff --git a/Godeps/_workspace/src/github.com/minio/minio-go/api_test.go b/Godeps/_workspace/src/github.com/minio/minio-go/api_test.go index 5139994a..cb50c1d4 100644 --- a/Godeps/_workspace/src/github.com/minio/minio-go/api_test.go +++ b/Godeps/_workspace/src/github.com/minio/minio-go/api_test.go @@ -199,14 +199,14 @@ func TestObjectOperations(t *testing.T) { func TestPartSize(t *testing.T) { var maxPartSize int64 = 1024 * 1024 * 1024 * 5 partSize := getPartSize(5000000000000000000) - if partSize > MinimumPartSize { + if partSize > minimumPartSize { if partSize > maxPartSize { - t.Fatal("invalid result, cannot be bigger than MaxPartSize 5GB") + t.Fatal("invalid result, cannot be bigger than maxPartSize 5GB") } } partSize = getPartSize(50000000000) - if partSize > MinimumPartSize { - t.Fatal("invalid result, cannot be bigger than MinimumPartSize 5MB") + if partSize > minimumPartSize { + t.Fatal("invalid result, cannot be bigger than minimumPartSize 5MB") } } @@ -251,9 +251,10 @@ func TestURLEncoding(t *testing.T) { } func TestErrorResponse(t *testing.T) { + a := lowLevelAPI{&Config{}} errorResponse := []byte("AccessDeniedAccess Denied/mybucket/myphoto.jpgF19772218238A85AGuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD") errorReader := bytes.NewReader(errorResponse) - err := responseToError(errorReader) + err := a.responseToError(errorReader) if err == nil { t.Fatal("Error") } @@ -280,7 +281,10 @@ func TestErrorResponse(t *testing.T) { if resp.HostID != "GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD" { t.Fatal("Error") } - if resp.XML() == "" { + if resp.ToXML() == "" { + t.Fatal("Error") + } + if resp.ToJSON() == "" { t.Fatal("Error") } } diff --git a/Godeps/_workspace/src/github.com/minio/minio-go/errors.go b/Godeps/_workspace/src/github.com/minio/minio-go/errors.go index 5725ff18..b1f1cfec 100644 --- a/Godeps/_workspace/src/github.com/minio/minio-go/errors.go +++ b/Godeps/_workspace/src/github.com/minio/minio-go/errors.go @@ -17,6 +17,7 @@ package minio import ( + "encoding/json" "encoding/xml" "io" "strings" @@ -55,7 +56,7 @@ type ErrorResponse struct { // ..., err := s3.GetObject(...) // if err != nil { // resp := s3.ToErrorResponse(err) -// fmt.Println(resp.XML()) +// fmt.Println(resp.ToXML()) // } // ... // ... @@ -69,11 +70,17 @@ func ToErrorResponse(err error) *ErrorResponse { } // XML send raw xml marshalled as string -func (e ErrorResponse) XML() string { +func (e ErrorResponse) ToXML() string { b, _ := xml.Marshal(&e) return string(b) } +// JSON send raw json marshalled as string +func (e ErrorResponse) ToJSON() string { + b, _ := json.Marshal(&e) + return string(b) +} + // Error formats HTTP error string func (e ErrorResponse) Error() string { return e.Message @@ -82,10 +89,9 @@ func (e ErrorResponse) Error() string { /// Internal function not exposed // responseToError returns a new encoded ErrorResponse structure -func responseToError(body io.Reader) error { +func (a lowLevelAPI) responseToError(errBody io.Reader) error { var respError ErrorResponse - decoder := xml.NewDecoder(body) - err := decoder.Decode(&respError) + err := acceptTypeDecoder(errBody, a.config.AcceptType, &respError) if err != nil { return err } diff --git a/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelapi.go b/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelapi.go index d6e7e150..21432df6 100644 --- a/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelapi.go +++ b/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelapi.go @@ -19,6 +19,7 @@ package minio import ( "bytes" "encoding/base64" + "encoding/json" "encoding/xml" "errors" "fmt" @@ -35,6 +36,8 @@ type lowLevelAPI struct { // putBucketRequest wrapper creates a new PutBucket request func (a lowLevelAPI) putBucketRequest(bucket, acl, location string) (*request, error) { + var r *request + var err error op := &operation{ HTTPServer: a.config.Endpoint, HTTPMethod: "PUT", @@ -46,14 +49,20 @@ func (a lowLevelAPI) putBucketRequest(bucket, acl, location string) (*request, e case location != "": createBucketConfig := new(createBucketConfiguration) createBucketConfig.Location = location - createBucketConfigBytes, err := xml.Marshal(createBucketConfig) + var createBucketConfigBytes []byte + switch { + case a.config.AcceptType == "application/xml": + createBucketConfigBytes, err = xml.Marshal(createBucketConfig) + case a.config.AcceptType == "application/json": + createBucketConfigBytes, err = json.Marshal(createBucketConfig) + default: + createBucketConfigBytes, err = xml.Marshal(createBucketConfig) + } if err != nil { return nil, err } createBucketConfigBuffer = bytes.NewReader(createBucketConfigBytes) } - var r *request - var err error switch { case createBucketConfigBuffer == nil: r, err = newRequest(op, a.config, nil) @@ -112,7 +121,7 @@ func (a lowLevelAPI) putBucket(bucket, acl, location string) error { defer resp.Body.Close() if resp != nil { if resp.StatusCode != http.StatusOK { - return responseToError(resp.Body) + return a.responseToError(resp.Body) } } return nil @@ -146,7 +155,7 @@ func (a lowLevelAPI) putBucketACL(bucket, acl string) error { defer resp.Body.Close() if resp != nil { if resp.StatusCode != http.StatusOK { - return responseToError(resp.Body) + return a.responseToError(resp.Body) } } return nil @@ -179,12 +188,11 @@ func (a lowLevelAPI) getBucketACL(bucket string) (accessControlPolicy, error) { defer resp.Body.Close() if resp != nil { if resp.StatusCode != http.StatusOK { - return accessControlPolicy{}, responseToError(resp.Body) + return accessControlPolicy{}, a.responseToError(resp.Body) } } policy := accessControlPolicy{} - decoder := xml.NewDecoder(resp.Body) - err = decoder.Decode(&policy) + err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &policy) if err != nil { return accessControlPolicy{}, err } @@ -227,12 +235,11 @@ func (a lowLevelAPI) getBucketLocation(bucket string) (string, error) { defer resp.Body.Close() if resp != nil { if resp.StatusCode != http.StatusOK { - return "", responseToError(resp.Body) + return "", a.responseToError(resp.Body) } } var locationConstraint string - decoder := xml.NewDecoder(resp.Body) - err = decoder.Decode(&locationConstraint) + err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &locationConstraint) if err != nil { return "", err } @@ -311,12 +318,11 @@ func (a lowLevelAPI) listObjects(bucket, marker, prefix, delimiter string, maxke defer resp.Body.Close() if resp != nil { if resp.StatusCode != http.StatusOK { - return listBucketResult{}, responseToError(resp.Body) + return listBucketResult{}, a.responseToError(resp.Body) } } listBucketResult := listBucketResult{} - decoder := xml.NewDecoder(resp.Body) - err = decoder.Decode(&listBucketResult) + err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listBucketResult) if err != nil { return listBucketResult, err } @@ -467,7 +473,7 @@ func (a lowLevelAPI) putObject(bucket, object, contentType string, md5SumBytes [ defer resp.Body.Close() if resp != nil { if resp.StatusCode != http.StatusOK { - return ObjectStat{}, responseToError(resp.Body) + return ObjectStat{}, a.responseToError(resp.Body) } } var metadata ObjectStat @@ -523,7 +529,7 @@ func (a lowLevelAPI) getPartialObject(bucket, object string, offset, length int6 case http.StatusOK: case http.StatusPartialContent: default: - return nil, ObjectStat{}, responseToError(resp.Body) + return nil, ObjectStat{}, a.responseToError(resp.Body) } } md5sum := strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes @@ -702,12 +708,11 @@ func (a lowLevelAPI) listBuckets() (listAllMyBucketsResult, error) { return listAllMyBucketsResult{}, errors.New(resp.Status) } if resp.StatusCode != http.StatusOK { - return listAllMyBucketsResult{}, responseToError(resp.Body) + return listAllMyBucketsResult{}, a.responseToError(resp.Body) } } listAllMyBucketsResult := listAllMyBucketsResult{} - decoder := xml.NewDecoder(resp.Body) - err = decoder.Decode(&listAllMyBucketsResult) + err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listAllMyBucketsResult) if err != nil { return listAllMyBucketsResult, err } diff --git a/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelcommon.go b/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelcommon.go index d3217846..3f708fe0 100644 --- a/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelcommon.go +++ b/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelcommon.go @@ -21,6 +21,8 @@ import ( "crypto/md5" "crypto/sha256" "encoding/hex" + "encoding/json" + "encoding/xml" "errors" "io" "regexp" @@ -28,6 +30,23 @@ import ( "unicode/utf8" ) +type decoder interface { + Decode(v interface{}) error +} + +func acceptTypeDecoder(body io.Reader, acceptType string, v interface{}) error { + var decoder decoder + switch { + case acceptType == "application/xml": + decoder = xml.NewDecoder(body) + case acceptType == "application/json": + decoder = json.NewDecoder(body) + default: + decoder = xml.NewDecoder(body) + } + return decoder.Decode(v) +} + // urlEncodedName- encode the strings from UTF-8 byte representations to HTML hex escape sequences func urlEncodeName(objectName string) (string, error) { // if object matches reserved string, no need to encode them diff --git a/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelmultipartapi.go b/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelmultipartapi.go index 5b8b5fc1..ad3a23c9 100644 --- a/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelmultipartapi.go +++ b/Godeps/_workspace/src/github.com/minio/minio-go/lowlevelmultipartapi.go @@ -20,6 +20,7 @@ import ( "bytes" "encoding/base64" "encoding/hex" + "encoding/json" "encoding/xml" "fmt" "io" @@ -102,12 +103,11 @@ func (a lowLevelAPI) listMultipartUploads(bucket, keymarker, uploadIDMarker, pre defer resp.Body.Close() if resp != nil { if resp.StatusCode != http.StatusOK { - return listMultipartUploadsResult{}, responseToError(resp.Body) + return listMultipartUploadsResult{}, a.responseToError(resp.Body) } } listMultipartUploadsResult := listMultipartUploadsResult{} - decoder := xml.NewDecoder(resp.Body) - err = decoder.Decode(&listMultipartUploadsResult) + err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listMultipartUploadsResult) if err != nil { return listMultipartUploadsResult, err } @@ -142,12 +142,11 @@ func (a lowLevelAPI) initiateMultipartUpload(bucket, object string) (initiateMul defer resp.Body.Close() if resp != nil { if resp.StatusCode != http.StatusOK { - return initiateMultipartUploadResult{}, responseToError(resp.Body) + return initiateMultipartUploadResult{}, a.responseToError(resp.Body) } } initiateMultipartUploadResult := initiateMultipartUploadResult{} - decoder := xml.NewDecoder(resp.Body) - err = decoder.Decode(&initiateMultipartUploadResult) + err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &initiateMultipartUploadResult) if err != nil { return initiateMultipartUploadResult, err } @@ -165,7 +164,15 @@ func (a lowLevelAPI) completeMultipartUploadRequest(bucket, object, uploadID str HTTPMethod: "POST", HTTPPath: "/" + bucket + "/" + encodedObject + "?uploadId=" + uploadID, } - completeMultipartUploadBytes, err := xml.Marshal(complete) + var completeMultipartUploadBytes []byte + switch { + case a.config.AcceptType == "application/xml": + completeMultipartUploadBytes, err = xml.Marshal(complete) + case a.config.AcceptType == "application/json": + completeMultipartUploadBytes, err = json.Marshal(complete) + default: + completeMultipartUploadBytes, err = xml.Marshal(complete) + } if err != nil { return nil, err } @@ -191,12 +198,11 @@ func (a lowLevelAPI) completeMultipartUpload(bucket, object, uploadID string, c defer resp.Body.Close() if resp != nil { if resp.StatusCode != http.StatusOK { - return completeMultipartUploadResult{}, responseToError(resp.Body) + return completeMultipartUploadResult{}, a.responseToError(resp.Body) } } completeMultipartUploadResult := completeMultipartUploadResult{} - decoder := xml.NewDecoder(resp.Body) - err = decoder.Decode(&completeMultipartUploadResult) + err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &completeMultipartUploadResult) if err != nil { return completeMultipartUploadResult, err } @@ -294,12 +300,11 @@ func (a lowLevelAPI) listObjectParts(bucket, object, uploadID string, partNumber defer resp.Body.Close() if resp != nil { if resp.StatusCode != http.StatusOK { - return listObjectPartsResult{}, responseToError(resp.Body) + return listObjectPartsResult{}, a.responseToError(resp.Body) } } listObjectPartsResult := listObjectPartsResult{} - decoder := xml.NewDecoder(resp.Body) - err = decoder.Decode(&listObjectPartsResult) + err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listObjectPartsResult) if err != nil { return listObjectPartsResult, err } @@ -345,7 +350,7 @@ func (a lowLevelAPI) uploadPart(bucket, object, uploadID string, md5SumBytes []b defer resp.Body.Close() if resp != nil { if resp.StatusCode != http.StatusOK { - return completePart{}, responseToError(resp.Body) + return completePart{}, a.responseToError(resp.Body) } } return cPart, nil diff --git a/cmd-cp.go b/cmd-cp.go index 19b02d68..69eced63 100644 --- a/cmd-cp.go +++ b/cmd-cp.go @@ -70,7 +70,7 @@ EXAMPLES: } // doCopy - Copy a singe file from source to destination -func doCopy(cURLs *cpURLs, bar *barSend) error { +func doCopy(cURLs cpURLs, bar *barSend) error { if !globalQuietFlag { sourceContentParse, _ := client.Parse(cURLs.SourceContent.Name) bar.SetCaption(caption{message: cURLs.SourceContent.Name + ": ", separator: sourceContentParse.Separator}) @@ -117,7 +117,7 @@ func args2URLs(args cli.Args) ([]string, error) { return URLs, nil } -func doCopyInRoutine(cURLs *cpURLs, bar *barSend, cpQueue chan bool, errCh chan error, wg *sync.WaitGroup) { +func doCopyInRoutine(cURLs cpURLs, bar *barSend, cpQueue chan bool, errCh chan error, wg *sync.WaitGroup) { defer wg.Done() if err := doCopy(cURLs, bar); err != nil { errCh <- err diff --git a/cp-url.go b/cp-url.go index dc3ac81a..00521570 100644 --- a/cp-url.go +++ b/cp-url.go @@ -17,7 +17,6 @@ package main import ( - "errors" "fmt" "path/filepath" "strings" @@ -92,118 +91,141 @@ func isTargetURLDir(targetURL string) bool { // guessCopyURLType guesses the type of URL. This approach all allows prepareURL // functions to accurately report failure causes. func guessCopyURLType(sourceURLs []string, targetURL string) cpURLsType { - if targetURL == "" { // Target is empty + if strings.TrimSpace(targetURL) == "" || targetURL == "" { // Target is empty return cpURLsTypeInvalid } - - if len(sourceURLs) < 1 { // Source list is empty + if sourceURLs == nil { // Source list is empty return cpURLsTypeInvalid } - if len(sourceURLs) == 1 { // 1 Source, 1 Target - if isURLRecursive(sourceURLs[0]) { // Type C + switch { + // Type C + case isURLRecursive(sourceURLs[0]): return cpURLsTypeC - } // else Type A or Type B - if isTargetURLDir(targetURL) { // Type B + // Type B + case isTargetURLDir(targetURL): return cpURLsTypeB - } // else Type A - return cpURLsTypeA + // Type A + default: + return cpURLsTypeA + } } // else Type D return cpURLsTypeD } // prepareCopyURLsTypeA - prepares target and source URLs for copying. -func prepareCopyURLsTypeA(sourceURL string, targetURL string) *cpURLs { - sourceClient, err := source2Client(sourceURL) - if err != nil { - return &cpURLs{Error: iodine.New(err, nil)} - } - - // Source exists? - sourceContent, err := sourceClient.Stat() - if err != nil { - // Source does not exist or insufficient privileges. - return &cpURLs{Error: iodine.New(err, nil)} - } - if !sourceContent.Type.IsRegular() { - // Source is not a regular file - return &cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)} - } - - targetClient, err := target2Client(targetURL) - if err != nil { - return &cpURLs{Error: iodine.New(err, nil)} - } - // Target exists? - targetContent, err := targetClient.Stat() - if err == nil { // Target exists. - if !targetContent.Type.IsRegular() { // Target is not a regular file - return &cpURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)} +func prepareCopyURLsTypeA(sourceURL string, targetURL string) <-chan cpURLs { + cpURLsCh := make(chan cpURLs, 10000) + go func(sourceURL, targetURL string, cpURLsCh chan cpURLs) { + defer close(cpURLsCh) + sourceClient, err := source2Client(sourceURL) + if err != nil { + cpURLsCh <- cpURLs{Error: iodine.New(err, nil)} + return } - } - - // All OK.. We can proceed. Type A - sourceContent.Name = sourceURL - return &cpURLs{SourceContent: sourceContent, TargetContent: &client.Content{Name: targetURL}} + // Source exists? + sourceContent, err := sourceClient.Stat() + if err != nil { + // Source does not exist or insufficient privileges. + cpURLsCh <- cpURLs{Error: iodine.New(err, nil)} + return + } + if !sourceContent.Type.IsRegular() { + // Source is not a regular file + cpURLsCh <- cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)} + return + } + targetClient, err := target2Client(targetURL) + if err != nil { + cpURLsCh <- cpURLs{Error: iodine.New(err, nil)} + return + } + // Target exists? + targetContent, err := targetClient.Stat() + if err == nil { // Target exists. + if !targetContent.Type.IsRegular() { // Target is not a regular file + cpURLsCh <- cpURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)} + return + } + } + // All OK.. We can proceed. Type A + sourceContent.Name = sourceURL + cpURLsCh <- cpURLs{SourceContent: sourceContent, TargetContent: &client.Content{Name: targetURL}} + }(sourceURL, targetURL, cpURLsCh) + return cpURLsCh } // SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A // prepareCopyURLsTypeB - prepares target and source URLs for copying. -func prepareCopyURLsTypeB(sourceURL string, targetURL string) *cpURLs { - sourceClient, err := source2Client(sourceURL) - if err != nil { - return &cpURLs{Error: iodine.New(err, nil)} - } - - sourceContent, err := sourceClient.Stat() - if err != nil { - // Source does not exist or insufficient privileges. - return &cpURLs{Error: iodine.New(err, nil)} - } - - if !sourceContent.Type.IsRegular() { - // Source is not a regular file. - return &cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)} - } - - targetClient, err := target2Client(targetURL) - if err != nil { - return &cpURLs{Error: iodine.New(err, nil)} - } - - // Target exist? - targetContent, err := targetClient.Stat() - if err == nil { - if !targetContent.Type.IsDir() { - // Target exists, but is not a directory. - return &cpURLs{Error: iodine.New(fmt.Errorf("Target [%s] is not a directory.", targetURL), nil)} +func prepareCopyURLsTypeB(sourceURL string, targetURL string) <-chan cpURLs { + cpURLsCh := make(chan cpURLs, 10000) + go func(sourceURL, targetURL string, cpURLsCh chan cpURLs) { + defer close(cpURLsCh) + sourceClient, err := source2Client(sourceURL) + if err != nil { + cpURLsCh <- cpURLs{Error: iodine.New(err, nil)} + return } - } // Else name is available to create. - // All OK.. We can proceed. Type B: source is a file, target is a directory and exists. - sourceURLParse, err := client.Parse(sourceURL) - if err != nil { - return &cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)} - } + sourceContent, err := sourceClient.Stat() + if err != nil { + // Source does not exist or insufficient privileges. + cpURLsCh <- cpURLs{Error: iodine.New(err, nil)} + return + } - targetURLParse, err := client.Parse(targetURL) - if err != nil { - return &cpURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)} - } + if !sourceContent.Type.IsRegular() { + // Source is not a regular file. + cpURLsCh <- cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)} + return + } - targetURLParse.Path = filepath.Join(targetURLParse.Path, filepath.Base(sourceURLParse.Path)) - return prepareCopyURLsTypeA(sourceURL, targetURLParse.String()) + targetClient, err := target2Client(targetURL) + if err != nil { + cpURLsCh <- cpURLs{Error: iodine.New(err, nil)} + return + } + + // Target exist? + targetContent, err := targetClient.Stat() + if err == nil { + if !targetContent.Type.IsDir() { + // Target exists, but is not a directory. + cpURLsCh <- cpURLs{Error: iodine.New(fmt.Errorf("Target [%s] is not a directory.", targetURL), nil)} + return + } + } // Else name is available to create. + + // All OK.. We can proceed. Type B: source is a file, target is a directory and exists. + sourceURLParse, err := client.Parse(sourceURL) + if err != nil { + cpURLsCh <- cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)} + return + } + + targetURLParse, err := client.Parse(targetURL) + if err != nil { + cpURLsCh <- cpURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)} + return + } + + targetURLParse.Path = filepath.Join(targetURLParse.Path, filepath.Base(sourceURLParse.Path)) + for cURLs := range prepareCopyURLsTypeA(sourceURL, targetURLParse.String()) { + cpURLsCh <- cURLs + } + }(sourceURL, targetURL, cpURLsCh) + return cpURLsCh } // SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A // prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying. -func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan *cpURLs { - cpURLsCh := make(chan *cpURLs, 10000) - go func(sourceURL, targetURL string, cpURLsCh chan *cpURLs) { +func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan cpURLs { + cpURLsCh := make(chan cpURLs, 10000) + go func(sourceURL, targetURL string, cpURLsCh chan cpURLs) { defer close(cpURLsCh) if !isURLRecursive(sourceURL) { // Source is not of recursive type. - cpURLsCh <- &cpURLs{Error: iodine.New(fmt.Errorf("Source [%s] is not recursive.", sourceURL), nil)} + cpURLsCh <- cpURLs{Error: iodine.New(fmt.Errorf("Source [%s] is not recursive.", sourceURL), nil)} return } @@ -211,7 +233,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan *cpURLs { sourceURL = stripRecursiveURL(sourceURL) sourceClient, err := source2Client(sourceURL) if err != nil { - cpURLsCh <- &cpURLs{Error: iodine.New(err, nil)} + cpURLsCh <- cpURLs{Error: iodine.New(err, nil)} return } @@ -219,19 +241,19 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan *cpURLs { sourceContent, err := sourceClient.Stat() if err != nil { // Source does not exist or insufficient privileges. - cpURLsCh <- &cpURLs{Error: iodine.New(err, nil)} + cpURLsCh <- cpURLs{Error: iodine.New(err, nil)} return } if !sourceContent.Type.IsDir() { // Source is not a dir. - cpURLsCh <- &cpURLs{Error: iodine.New(fmt.Errorf("Source [%s] is not a directory.", sourceURL), nil)} + cpURLsCh <- cpURLs{Error: iodine.New(fmt.Errorf("Source [%s] is not a directory.", sourceURL), nil)} return } targetClient, err := target2Client(targetURL) if err != nil { - cpURLsCh <- &cpURLs{Error: iodine.New(err, nil)} + cpURLsCh <- cpURLs{Error: iodine.New(err, nil)} return } @@ -239,20 +261,20 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan *cpURLs { targetContent, err := targetClient.Stat() if err != nil { // Target does not exist. - cpURLsCh <- &cpURLs{Error: iodine.New(fmt.Errorf("Target directory [%s] does not exist.", targetURL), nil)} + cpURLsCh <- cpURLs{Error: iodine.New(fmt.Errorf("Target directory [%s] does not exist.", targetURL), nil)} return } if !targetContent.Type.IsDir() { // Target exists, but is not a directory. - cpURLsCh <- &cpURLs{Error: iodine.New(fmt.Errorf("Target [%s] is not a directory.", targetURL), nil)} + cpURLsCh <- cpURLs{Error: iodine.New(fmt.Errorf("Target [%s] is not a directory.", targetURL), nil)} return } for sourceContent := range sourceClient.List(true) { if sourceContent.Err != nil { // Listing failed. - cpURLsCh <- &cpURLs{Error: iodine.New(sourceContent.Err, nil)} + cpURLsCh <- cpURLs{Error: iodine.New(sourceContent.Err, nil)} continue } @@ -264,13 +286,13 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan *cpURLs { // All OK.. We can proceed. Type B: source is a file, target is a directory and exists. sourceURLParse, err := client.Parse(sourceURL) if err != nil { - cpURLsCh <- &cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)} + cpURLsCh <- cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)} continue } targetURLParse, err := client.Parse(targetURL) if err != nil { - cpURLsCh <- &cpURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)} + cpURLsCh <- cpURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)} continue } @@ -280,92 +302,92 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan *cpURLs { sourceContentURL := sourceURLDelimited + sourceContentName sourceContentParse, err := client.Parse(sourceContentURL) if err != nil { - cpURLsCh <- &cpURLs{Error: iodine.New(errInvalidSource{URL: sourceContentName}, nil)} + cpURLsCh <- cpURLs{Error: iodine.New(errInvalidSource{URL: sourceContentName}, nil)} continue } // Construct target path from recursive path of source without its prefix dir. newTargetURLParse := *targetURLParse newTargetURLParse.Path = filepath.Join(newTargetURLParse.Path, sourceContentName) - cpURLsCh <- prepareCopyURLsTypeA(sourceContentParse.String(), newTargetURLParse.String()) + for cURLs := range prepareCopyURLsTypeA(sourceContentParse.String(), newTargetURLParse.String()) { + cpURLsCh <- cURLs + } + } }(sourceURL, targetURL, cpURLsCh) - return cpURLsCh } // MULTI-SOURCE - Type D: copy([]f, d) -> []B // prepareCopyURLsTypeD - prepares target and source URLs for copying. -func prepareCopyURLsTypeD(sourceURLs []string, targetURL string) <-chan *cpURLs { - cpURLsCh := make(chan *cpURLs, 10000) - go func(sourceURLs []string, targetURL string, cpURLsCh chan *cpURLs) { +func prepareCopyURLsTypeD(sourceURLs []string, targetURL string) <-chan cpURLs { + cpURLsCh := make(chan cpURLs, 10000) + go func(sourceURLs []string, targetURL string, cpURLsCh chan cpURLs) { defer close(cpURLsCh) - targetClient, err := target2Client(targetURL) if err != nil { - cpURLsCh <- &cpURLs{Error: iodine.New(err, nil)} + cpURLsCh <- cpURLs{Error: iodine.New(err, nil)} return } - // Target exist? targetContent, err := targetClient.Stat() if err != nil { // Target does not exist. - cpURLsCh <- &cpURLs{Error: iodine.New(fmt.Errorf("Target directory [%s] does not exist.", targetURL), nil)} + cpURLsCh <- cpURLs{Error: iodine.New(fmt.Errorf("Target directory [%s] does not exist.", targetURL), nil)} return } if !targetContent.Type.IsDir() { // Target exists, but is not a directory. - cpURLsCh <- &cpURLs{Error: iodine.New(fmt.Errorf("Target [%s] is not a directory.", targetURL), nil)} + cpURLsCh <- cpURLs{Error: iodine.New(fmt.Errorf("Target [%s] is not a directory.", targetURL), nil)} return } - - if len(sourceURLs) < 1 { + if sourceURLs == nil { // Source list is empty. - cpURLsCh <- &cpURLs{Error: iodine.New(errors.New("Source list is empty"), nil)} + cpURLsCh <- cpURLs{Error: iodine.New(fmt.Errorf("Source list is empty"), nil)} return } - for _, sourceURL := range sourceURLs { // Target is directory. Possibilities are only Type B and C // Is it a recursive URL "..."? - if isURLRecursive(sourceURL) { // Type C - ch := prepareCopyURLsTypeC(sourceURL, targetURL) - for cpURLs := range ch { - cpURLsCh <- cpURLs + switch isURLRecursive(sourceURL) { + case true: + for cURLs := range prepareCopyURLsTypeC(sourceURL, targetURL) { + cpURLsCh <- cURLs + } + case false: + for cURLs := range prepareCopyURLsTypeB(sourceURL, targetURL) { + cpURLsCh <- cURLs } - } else { // Type B - cpURLsCh <- prepareCopyURLsTypeB(sourceURL, targetURL) } } - }(sourceURLs, targetURL, cpURLsCh) - return cpURLsCh } // prepareCopyURLs - prepares target and source URLs for copying. -func prepareCopyURLs(sourceURLs []string, targetURL string) <-chan *cpURLs { - cpURLsCh := make(chan *cpURLs, 10000) - go func(sourceURLs []string, targetURL string, cpURLsCh chan *cpURLs) { +func prepareCopyURLs(sourceURLs []string, targetURL string) <-chan cpURLs { + cpURLsCh := make(chan cpURLs, 10000) + go func(sourceURLs []string, targetURL string, cpURLsCh chan cpURLs) { defer close(cpURLsCh) switch guessCopyURLType(sourceURLs, targetURL) { case cpURLsTypeA: - cpURLs := prepareCopyURLsTypeA(sourceURLs[0], targetURL) - cpURLsCh <- cpURLs + for cURLs := range prepareCopyURLsTypeA(sourceURLs[0], targetURL) { + cpURLsCh <- cURLs + } case cpURLsTypeB: - cpURLs := prepareCopyURLsTypeB(sourceURLs[0], targetURL) - cpURLsCh <- cpURLs + for cURLs := range prepareCopyURLsTypeB(sourceURLs[0], targetURL) { + cpURLsCh <- cURLs + } case cpURLsTypeC: - for cpURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL) { - cpURLsCh <- cpURLs + for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL) { + cpURLsCh <- cURLs } case cpURLsTypeD: - for cpURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL) { - cpURLsCh <- cpURLs + for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL) { + cpURLsCh <- cURLs } default: - cpURLsCh <- &cpURLs{Error: iodine.New(errInvalidArgument{}, nil)} + cpURLsCh <- cpURLs{Error: iodine.New(errInvalidArgument{}, nil)} } }(sourceURLs, targetURL, cpURLsCh) diff --git a/sync-url.go b/sync-url.go index 4c07c547..ee72a0c4 100644 --- a/sync-url.go +++ b/sync-url.go @@ -61,11 +61,9 @@ func guessSyncURLType(sourceURL string, targetURLs []string) syncURLsType { if targetURLs == nil { // Target is empty return syncURLsType(cpURLsTypeInvalid) } - if sourceURL == "" { // Source list is empty return syncURLsType(cpURLsTypeInvalid) } - if isURLRecursive(sourceURL) { // Type C return syncURLsType(cpURLsTypeC) } // else Type A or Type B @@ -83,13 +81,15 @@ func prepareSyncURLsTypeA(sourceURL string, targetURLs []string) <-chan syncURLs defer close(syncURLsCh) var sURLs syncURLs for _, targetURL := range targetURLs { - cpURLs := prepareCopyURLsTypeA(sourceURL, targetURL) - if cpURLs.Error != nil { - syncURLsCh <- syncURLs{Error: iodine.New(cpURLs.Error, nil)} - continue + var cURLs cpURLs + for cURLs = range prepareCopyURLsTypeA(sourceURL, targetURL) { + if cURLs.Error != nil { + syncURLsCh <- syncURLs{Error: iodine.New(cURLs.Error, nil)} + continue + } } - sURLs.SourceContent = cpURLs.SourceContent - sURLs.TargetContents = append(sURLs.TargetContents, cpURLs.TargetContent) + sURLs.SourceContent = cURLs.SourceContent + sURLs.TargetContents = append(sURLs.TargetContents, cURLs.TargetContent) } syncURLsCh <- sURLs }() @@ -102,13 +102,15 @@ func prepareSyncURLsTypeB(sourceURL string, targetURLs []string) <-chan syncURLs defer close(syncURLsCh) var sURLs syncURLs for _, targetURL := range targetURLs { - cpURLs := prepareCopyURLsTypeB(sourceURL, targetURL) - if cpURLs.Error != nil { - syncURLsCh <- syncURLs{Error: iodine.New(cpURLs.Error, nil)} - continue + var cURLs cpURLs + for cURLs = range prepareCopyURLsTypeB(sourceURL, targetURL) { + if cURLs.Error != nil { + syncURLsCh <- syncURLs{Error: iodine.New(cURLs.Error, nil)} + continue + } } - sURLs.SourceContent = cpURLs.SourceContent - sURLs.TargetContents = append(sURLs.TargetContents, cpURLs.TargetContent) + sURLs.SourceContent = cURLs.SourceContent + sURLs.TargetContents = append(sURLs.TargetContents, cURLs.TargetContent) } syncURLsCh <- sURLs }()