Merge pull request #1444 from abperiasamy/cp-recur

new recursive cp and session
This commit is contained in:
Harshavardhana
2015-11-19 12:49:19 -08:00
13 changed files with 377 additions and 640 deletions
+24 -16
View File
@@ -36,7 +36,12 @@ import (
"github.com/minio/pb"
)
// cp command flags.
var (
cpFlagRecursive = cli.BoolFlag{
Name: "recursive, r",
Usage: "Copy recursively.",
}
cpFlagHelp = cli.BoolFlag{
Name: "help, h",
Usage: "Help of cp.",
@@ -48,7 +53,7 @@ var cpCmd = cli.Command{
Name: "cp",
Usage: "Copy one or more objects to a target.",
Action: mainCopy,
Flags: []cli.Flag{cpFlagHelp},
Flags: []cli.Flag{cpFlagRecursive, cpFlagHelp},
CustomHelpTemplate: `NAME:
mc {{.Name}} - {{.Usage}}
@@ -62,20 +67,20 @@ EXAMPLES:
1. Copy a list of objects from local file system to Amazon S3 cloud storage.
$ mc {{.Name}} Music/*.ogg https://s3.amazonaws.com/jukebox/
2. Copy a bucket recursively from Minio cloud storage to Amazon S3 cloud storage.
$ mc {{.Name}} https://play.minio.io:9000/photobucket/burningman2011... https://s3.amazonaws.com/mybucket/
2. Copy a folder recursively from Minio cloud storage to Amazon S3 cloud storage.
$ mc {{.Name}} --recursive https://play.minio.io:9000/mybucket/burningman2011/ https://s3.amazonaws.com/mybucket/
3. Copy multiple local folders recursively to Minio cloud storage.
$ mc {{.Name}} backup/2014/... backup/2015/... https://play.minio.io:9000/archive/
$ mc {{.Name}} --recursive backup/2014/ backup/2015/ https://play.minio.io:9000/archive/
4. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows.
$ mc {{.Name}} s3/documents/2014/... C:\Backups\2014
$ mc {{.Name}} --recursive s3/documents/2014/ C:\Backups\2014
5. Copy an object with name containing unicode characters to Amazon S3 cloud storage.
$ mc {{.Name}} 本語 s3/andoria/
6. Copy a local folder with space separated characters to Amazon S3 cloud storage.
$ mc {{.Name}} 'workdir/documents/May 2014...' s3/miniocloud
$ mc {{.Name}} --recursive 'workdir/documents/May 2014/' s3/miniocloud
`,
}
@@ -190,15 +195,18 @@ func doCopyFake(cURLs copyURLs, progressReader *barSend) {
}
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
func doPrepareCopyURLs(session *sessionV4, trapCh <-chan bool) {
func doPrepareCopyURLs(session *sessionV5, trapCh <-chan bool) {
// Separate source and target. 'cp' can take only one target,
// but any number of sources, even the recursive URLs mixed in-between.
// but any number of sources.
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
targetURL := session.Header.CommandArgs[len(session.Header.CommandArgs)-1] // Last one is target
var totalBytes int64
var totalObjects int
// Access recursive flag inside the session header.
isRecursive := session.Header.CommandBoolFlags["recursive"]
// Create a session data file to store the processed URLs.
dataFP := session.NewDataWriter()
@@ -207,7 +215,7 @@ func doPrepareCopyURLs(session *sessionV4, trapCh <-chan bool) {
scanBar = scanBarFactory()
}
URLsCh := prepareCopyURLs(sourceURLs, targetURL)
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive)
done := false
for done == false {
@@ -256,7 +264,7 @@ func doPrepareCopyURLs(session *sessionV4, trapCh <-chan bool) {
session.Save()
}
func doCopySession(session *sessionV4) {
func doCopySession(session *sessionV5) {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
if !session.HasData() {
@@ -376,19 +384,19 @@ func mainCopy(ctx *cli.Context) {
// Additional command speific theme customization.
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
var e error
session := newSessionV4()
session := newSessionV5()
session.Header.CommandType = "cp"
session.Header.RootPath, e = os.Getwd()
if e != nil {
session.Header.CommandBoolFlags["recursive"] = ctx.Bool("recursive")
var e error
if session.Header.RootPath, e = os.Getwd(); e != nil {
session.Delete()
fatalIf(probe.NewError(e), "Unable to get current working folder.")
}
// extract URLs.
var err *probe.Error
session.Header.CommandArgs, err = args2URLs(ctx.Args())
if err != nil {
if session.Header.CommandArgs, err = args2URLs(ctx.Args()); err != nil {
session.Delete()
fatalIf(err.Trace(), "One or more unknown URL types passed.")
}
+150
View File
@@ -0,0 +1,150 @@
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"fmt"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
)
func checkCopySyntax(ctx *cli.Context) {
if len(ctx.Args()) < 2 {
cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code.
}
// extract URLs.
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("Argument parsing failed."))
if len(URLs) < 2 {
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("Unable to parse source and target arguments."))
}
srcURLs := URLs[:len(URLs)-1]
tgtURL := URLs[len(URLs)-1]
isRecursive := ctx.Bool("recursive")
/****** Generic rules *******/
url := client.NewURL(tgtURL)
if url.Host != "" {
// This check is for type URL.
if url.Path == string(url.Separator) {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
}
}
switch guessCopyURLType(srcURLs, tgtURL, isRecursive) {
case copyURLsTypeA: // File -> File.
checkCopySyntaxTypeA(srcURLs, tgtURL)
case copyURLsTypeB: // File -> Folder.
checkCopySyntaxTypeB(srcURLs, tgtURL)
case copyURLsTypeC: // Folder... -> Folder.
checkCopySyntaxTypeC(srcURLs, tgtURL)
case copyURLsTypeD: // File | Folder... -> Folder.
checkCopySyntaxTypeD(srcURLs, tgtURL)
default:
fatalIf(errInvalidArgument().Trace(), "Invalid arguments.")
}
}
// checkCopySyntaxTypeA verifies if the source and target are valid file arguments.
func checkCopySyntaxTypeA(srcURLs []string, tgtURL string) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(srcURL)
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
if !srcContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a file.")
}
// Check target.
_, tgtContent, err := url2Stat(tgtURL)
fatalIf(err.Trace(srcURL), "Unable to stat target ‘"+tgtURL+"’.")
if !tgtContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(), "Target ‘"+tgtURL+"’ is not a file.")
}
}
// checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid dir.
func checkCopySyntaxTypeB(srcURLs []string, tgtURL string) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(srcURL)
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
if !srcContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(srcURL), "Source ‘"+srcURL+"’ is not a file.")
}
// Check target.
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
}
}
}
// checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid dir.
func checkCopySyntaxTypeC(srcURLs []string, tgtURL string) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, _, err := url2Stat(srcURL)
if err != nil && !prefixExists(srcURL) {
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
}
// Check target.
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
}
}
}
// checkCopySyntaxTypeD verifies if the source is a valid list of files and target is a valid dir.
func checkCopySyntaxTypeD(srcURLs []string, tgtURL string) {
// Check source.
for _, srcURL := range srcURLs {
_, srcContent, err := url2Stat(srcURL)
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
if !srcContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a file.")
}
}
// Check target.
if _, tgtContent, err := url2Stat(tgtURL); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
}
}
}
+74 -207
View File
@@ -17,11 +17,9 @@
package main
import (
"fmt"
"path/filepath"
"strings"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
)
@@ -34,187 +32,69 @@ type copyURLs struct {
type copyURLsType uint8
const (
copyURLsTypeInvalid copyURLsType = iota
copyURLsTypeA // file to file
copyURLsTypeB // file to dir
copyURLsTypeC // recursive to dir
copyURLsTypeD // complex to dir
)
// NOTE: All the parse rules should reduced to A: Copy(Source, Target).
//
// * VALID RULES
// =======================
// A: copy(f, f) -> copy(f, f)
// B: copy(f, d) -> copy(f, d/f) -> A
// C: copy(d1..., d2) -> []copy(d1/f, d2/d1/f) -> []A
// D: copy([]{d1... | f}, d2) -> []{copy(d1/f, d2/d1/f) | copy(f, d2/f )} -> []A
// B: copy(f, d) -> copy(f, d/f) -> []A
// C: copy(d1..., d2) -> []copy(f, d2/d1/f) -> []A
// D: copy([]f, d) -> []B -> []A
//
// * INVALID RULES
// =========================
// A: copy(d, *)
// B: copy(d..., f)
// C: copy(*, d...)
//
func checkCopySyntax(ctx *cli.Context) {
if len(ctx.Args()) < 2 {
cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code.
}
// extract URLs.
URLs, err := args2URLs(ctx.Args())
fatalIf(err.Trace(ctx.Args()...), fmt.Sprintf("One or more unknown URL types passed."))
// copy(d, f)
// copy(d..., f)
// copy([]f, f)
//'
srcURLs := URLs[:len(URLs)-1]
tgtURL := URLs[len(URLs)-1]
/****** Generic rules *******/
// Recursive URLs are not allowed in target.
if isURLRecursive(tgtURL) {
fatalIf(errDummy().Trace(), fmt.Sprintf("Recursive option is not supported for target ‘%s’ argument.", tgtURL))
}
url := client.NewURL(tgtURL)
if url.Host != "" {
// This check is for type URL.
if url.Path == string(url.Separator) {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
}
}
switch guessCopyURLType(srcURLs, tgtURL) {
case copyURLsTypeA: // File -> File.
checkCopySyntaxTypeA(srcURLs, tgtURL)
case copyURLsTypeB: // File -> Folder.
checkCopySyntaxTypeB(srcURLs, tgtURL)
case copyURLsTypeC: // Folder... -> Folder.
checkCopySyntaxTypeC(srcURLs, tgtURL)
case copyURLsTypeD: // File | Folder... -> Folder.
checkCopySyntaxTypeD(srcURLs, tgtURL)
default:
fatalIf(errInvalidArgument().Trace(), "Invalid arguments to copy command.")
}
}
// checkCopySyntaxTypeA verifies if the source and target are valid file arguments.
func checkCopySyntaxTypeA(srcURLs []string, tgtURL string) {
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments to copy command.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(srcURL)
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
if srcContent.Type.IsDir() {
fatalIf(errSourceIsDir(srcURL).Trace(srcURL), fmt.Sprintf("Folder cannot copied. Please use ‘%s...’ to copy this folder and its contents recursively.", srcURL))
}
if !srcContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(), "Source ‘"+srcURL+"’ is not a file.")
}
}
// checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid dir.
func checkCopySyntaxTypeB(srcURLs []string, tgtURL string) {
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments to copy command.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(srcURL)
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
if srcContent.Type.IsDir() {
fatalIf(errSourceIsDir(srcURL).Trace(srcURL), fmt.Sprintf("Folder cannot be copied. Please use ‘%s...’ argument to copy this folder and its contents recursively.", srcURL))
}
if !srcContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(srcURL), "Source ‘"+srcURL+"’ is not a file.")
}
_, tgtContent, err := url2Stat(tgtURL)
// Target exist?.
if err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
}
}
}
// checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid dir.
func checkCopySyntaxTypeC(srcURLs []string, tgtURL string) {
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments to copy command.")
}
srcURL := srcURLs[0]
srcURL = stripRecursiveURL(srcURL)
_, _, err := url2Stat(srcURL)
if err != nil && !prefixExists(srcURL) {
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
}
_, tgtContent, err := url2Stat(tgtURL)
// Target exist?.
if err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
}
}
}
// checkCopySyntaxTypeD verifies if the source is a valid list of file or valid recursive dir and target is a valid dir.
func checkCopySyntaxTypeD(srcURLs []string, tgtURL string) {
for _, srcURL := range srcURLs {
if isURLRecursive(srcURL) {
srcURL = stripRecursiveURL(srcURL)
_, srcContent, err := url2Stat(srcURL)
if err != nil && !prefixExists(srcURL) {
fatalIf(err.Trace(srcURL), "Unable to stat source ‘"+srcURL+"’.")
}
if err == nil && !srcContent.Type.IsDir() { // Ellipses is supported only for folders.
fatalIf(errInvalidArgument().Trace(srcURL), "Source ‘"+srcURL+"’ is not a folder.")
}
}
}
_, tgtContent, err := url2Stat(tgtURL)
// Target exist?.
if err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target ‘"+tgtURL+"’ is not a folder.")
}
}
}
const (
copyURLsTypeInvalid copyURLsType = iota
copyURLsTypeA
copyURLsTypeB
copyURLsTypeC
copyURLsTypeD
)
// guessCopyURLType guesses the type of URL. This approach all allows prepareURL
// functions to accurately report failure causes.
func guessCopyURLType(sourceURLs []string, targetURL string) copyURLsType {
if strings.TrimSpace(targetURL) == "" || targetURL == "" { // Target is empty
return copyURLsTypeInvalid
}
if len(sourceURLs) == 0 || sourceURLs == nil { // Source list is empty
return copyURLsTypeInvalid
}
for _, sourceURL := range sourceURLs {
if sourceURL == "" { // One of the source is empty
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) copyURLsType {
if len(sourceURLs) == 1 { // 1 Source, 1 Target
sourceURL := sourceURLs[0]
_, sourceContent, err := url2Stat(sourceURL)
if err != nil {
return copyURLsTypeInvalid
}
}
if len(sourceURLs) == 1 { // 1 Source, 1 Target
switch {
// Type C
case isURLRecursive(sourceURLs[0]):
if sourceContent.Type.IsDir() { // If source is a Dir, it is Type C.
return copyURLsTypeC
// Type B
case isTargetURLDir(targetURL):
return copyURLsTypeB
// Type A
default:
return copyURLsTypeA
}
} // else Type D
return copyURLsTypeD
switch {
case isRecursive: // If recursion is ON, it is type C.
return copyURLsTypeC
case isTargetURLDir(targetURL): // If not type C and target is a dir, it is Type B
return copyURLsTypeB
default:
return copyURLsTypeA // else Type A.
}
}
// Multiple source args and taget is a dir. It is Type D.
if isTargetURLDir(targetURL) {
return copyURLsTypeD
}
return copyURLsTypeInvalid
}
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
// prepareCopyURLsTypeA - prepares target and source URLs for copying.
func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
if sourceURL == targetURL {
// source and target can not be same
return copyURLs{Error: errSourceTargetSame(sourceURL).Trace()}
}
_, sourceContent, err := url2Stat(sourceURL)
if err != nil {
// Source does not exist or insufficient privileges.
@@ -224,11 +104,12 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
// Source is not a regular file
return copyURLs{Error: errInvalidSource(sourceURL).Trace()}
}
if sourceURL == targetURL {
// source and target can not be same
return copyURLs{Error: errSourceTargetSame(sourceURL).Trace()}
}
// All OK.. We can proceed. Type A
return makeCopyContentTypeA(sourceContent, targetURL)
}
// prepareCopyContentTypeA - makes CopyURLs content for copying.
func makeCopyContentTypeA(sourceContent *client.Content, targetURL string) copyURLs {
return copyURLs{SourceContent: sourceContent, TargetContent: &client.Content{URL: *client.NewURL(targetURL)}}
}
@@ -250,26 +131,23 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
}
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
sourceURLParse := client.NewURL(sourceURL)
return makeCopyContentTypeB(sourceContent, targetURL)
}
// makeCopyContentTypeB - CopyURLs content for copying.
func makeCopyContentTypeB(sourceContent *client.Content, 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.Path = filepath.Join(targetURLParse.Path, filepath.Base(sourceURLParse.Path))
return prepareCopyURLsTypeA(sourceURL, targetURLParse.String())
targetURLParse.Path = filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path))
return makeCopyContentTypeA(sourceContent, targetURLParse.String())
}
// 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 copyURLs {
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs {
copyURLsCh := make(chan copyURLs)
go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) {
defer close(copyURLsCh)
if !isURLRecursive(sourceURL) {
// Source is not of recursive type.
copyURLsCh <- copyURLs{Error: errSourceNotRecursive(sourceURL).Trace()}
return
}
// add `/` after trimming off `...` to emulate folders
sourceURL = stripRecursiveURL(sourceURL)
sourceClient, err := url2Client(sourceURL)
if err != nil {
// Source initialization failed.
@@ -277,7 +155,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan copyURLs {
return
}
for sourceContent := range sourceClient.List(true, false) {
for sourceContent := range sourceClient.List(isRecursive, false) {
if sourceContent.Err != nil {
// Listing failed.
copyURLsCh <- copyURLs{Error: sourceContent.Err.Trace()}
@@ -290,60 +168,49 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan copyURLs {
}
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
srcURL := sourceClient.GetURL()
newSourceURL := sourceContent.URL
pathSeparatorIndex := strings.LastIndex(srcURL.Path, string(srcURL.Separator))
newSourceSuffix := newSourceURL.Path
if pathSeparatorIndex > 1 {
newSourceSuffix = strings.TrimPrefix(newSourceURL.Path, srcURL.Path[:pathSeparatorIndex])
}
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
copyURLsCh <- prepareCopyURLsTypeA(sourceContent.URL.String(), newTargetURL)
copyURLsCh <- makeCopyContentTypeC(sourceClient.GetURL(), sourceContent, targetURL)
}
}(sourceURL, targetURL, copyURLsCh)
return copyURLsCh
}
// makeCopyContentTypeC - CopyURLs content for copying.
func makeCopyContentTypeC(sourceURL client.URL, sourceContent *client.Content, targetURL string) copyURLs {
newSourceURL := sourceContent.URL
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
newSourceSuffix := newSourceURL.Path
if pathSeparatorIndex > 1 {
newSourceSuffix = strings.TrimPrefix(newSourceURL.Path, sourceURL.Path[:pathSeparatorIndex])
}
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
return makeCopyContentTypeA(sourceContent, newTargetURL)
}
// MULTI-SOURCE - Type D: copy([]f, d) -> []B
// prepareCopyURLsTypeD - prepares target and source URLs for copying.
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string) <-chan copyURLs {
copyURLsCh := make(chan copyURLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
defer close(copyURLsCh)
if sourceURLs == nil {
// Source list is empty.
copyURLsCh <- copyURLs{Error: errSourceListEmpty().Trace()}
return
}
for _, sourceURL := range sourceURLs {
// Target is folder. Possibilities are only Type B and C
// Is it a recursive URL "..."?
if isURLRecursive(sourceURL) {
for cURLs := range prepareCopyURLsTypeC(sourceURL, targetURL) {
copyURLsCh <- cURLs
}
} else {
copyURLsCh <- prepareCopyURLsTypeB(sourceURL, targetURL)
}
copyURLsCh <- prepareCopyURLsTypeB(sourceURL, targetURL)
}
}(sourceURLs, targetURL, copyURLsCh)
return copyURLsCh
}
// prepareCopyURLs - prepares target and source URLs for copying.
func prepareCopyURLs(sourceURLs []string, targetURL string) <-chan copyURLs {
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
copyURLsCh := make(chan copyURLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
defer close(copyURLsCh)
switch guessCopyURLType(sourceURLs, targetURL) {
switch guessCopyURLType(sourceURLs, targetURL, isRecursive) {
case copyURLsTypeA:
copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL)
case copyURLsTypeB:
copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL)
case copyURLsTypeC:
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL) {
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive) {
copyURLsCh <- cURLs
}
case copyURLsTypeD:
+35 -16
View File
@@ -29,33 +29,52 @@ import (
)
func (s *TestSuite) TestCopyURLType(c *C) {
// Valid Types.
sourceURLs := []string{server.URL + "/bucket/object1"}
targetURL := server.URL + "/bucket/test"
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeA)
isRecursive := false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeA)
sourceURLs = []string{server.URL + "/bucket/object1"}
targetURL = server.URL + "/bucket"
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeB)
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeB)
sourceURLs = []string{server.URL + "/bucket/..."}
sourceURLs = []string{server.URL + "/bucket/"}
targetURL = server.URL + "/bucket"
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeC)
isRecursive = true
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeC)
sourceURLs = []string{server.URL + "/bucket/...", server.URL + "/bucket/..."}
targetURL = server.URL + "/bucket/test"
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeD)
sourceURLs = []string{}
sourceURLs = []string{server.URL + "/bucket/test1.txt", server.URL + "/bucket/test2.txt"}
targetURL = server.URL + "/bucket"
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeD)
sourceURLs = nil
targetURL = server.URL + "/bucket"
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)
// * INVALID RULES
// =========================
// copy(d, f)
// copy(d..., f)
// copy([]f, f)
sourceURLs = []string{server.URL + "/bucket/...", server.URL + "/bucket/..."}
sourceURLs = []string{"/test/"}
targetURL = server.URL + "/bucket/test.txt"
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
sourceURLs = []string{"/test/"}
targetURL = server.URL + "/bucket/test.txt"
isRecursive = true
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
sourceURLs = []string{"/test/test1.txt", "/test/test2.txt"}
targetURL = server.URL + "/bucket/test.txt"
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
sourceURLs = []string{server.URL + "/bucket/", server.URL + "/bucket/"}
targetURL = ""
c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)
isRecursive = false
c.Assert(guessCopyURLType(sourceURLs, targetURL, isRecursive), Equals, copyURLsTypeInvalid)
}
func (s *TestSuite) TestMirror(c *C) {
@@ -107,7 +126,7 @@ func (s *TestSuite) TestCopy(c *C) {
target := filepath.Join(source, "random")
defer os.RemoveAll(target)
err = app.Run([]string{os.Args[0], "cp", filepath.Join(source, "..."), target})
err = app.Run([]string{os.Args[0], "cp", "--recursive", source, target})
c.Assert(err, IsNil)
c.Assert(console.IsExited, Equals, false)
+8 -17
View File
@@ -74,10 +74,6 @@ EXAMPLES:
`,
}
var (
mirrorIsForce = false // mirror specific force flag set via command line
)
// mirrorMessage container for file mirror messages
type mirrorMessage struct {
Status string `json:"status"`
@@ -191,7 +187,7 @@ func doMirrorFake(sURLs mirrorURLs, progressReader *barSend) {
}
// doPrepareMirrorURLs scans the source URL and prepares a list of objects for mirroring.
func doPrepareMirrorURLs(session *sessionV4, trapCh <-chan bool) {
func doPrepareMirrorURLs(session *sessionV5, isForce bool, trapCh <-chan bool) {
sourceURL := session.Header.CommandArgs[0] // first one is source.
targetURLs := session.Header.CommandArgs[1:]
var totalBytes int64
@@ -205,14 +201,7 @@ func doPrepareMirrorURLs(session *sessionV4, trapCh <-chan bool) {
scanBar = scanBarFactory()
}
// will be true if '--force' is provided on the command line.
if len(session.Header.CommandBoolFlag) > 0 {
if session.Header.CommandBoolFlag[0].Key == "force" {
mirrorIsForce = session.Header.CommandBoolFlag[0].Value
}
}
URLsCh := prepareMirrorURLs(sourceURL, targetURLs)
URLsCh := prepareMirrorURLs(sourceURL, targetURLs, isForce)
done := false
for done == false {
select {
@@ -259,11 +248,12 @@ func doPrepareMirrorURLs(session *sessionV4, trapCh <-chan bool) {
}
// Session'fied mirror command.
func doMirrorSession(session *sessionV4) {
func doMirrorSession(session *sessionV5) {
isForce := session.Header.CommandBoolFlags["force"]
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
if !session.HasData() {
doPrepareMirrorURLs(session, trapCh)
doPrepareMirrorURLs(session, isForce, trapCh)
}
// Enable accounting reader by default.
@@ -380,7 +370,7 @@ func mainMirror(ctx *cli.Context) {
console.SetColor("Mirror", color.New(color.FgGreen, color.Bold))
var e error
session := newSessionV4()
session := newSessionV5()
session.Header.CommandType = "mirror"
session.Header.RootPath, e = os.Getwd()
if e != nil {
@@ -389,7 +379,8 @@ func mainMirror(ctx *cli.Context) {
}
// If force flag is set save it with in session
session.Header.CommandBoolFlag = []cmdBoolFlag{{Key: "force", Value: ctx.Bool("force")}}
isForce := ctx.Bool("force")
session.Header.CommandBoolFlags["force"] = isForce
// extract URLs.
var err *probe.Error
+4 -4
View File
@@ -88,7 +88,7 @@ func checkMirrorSyntax(ctx *cli.Context) {
}
}
func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan<- mirrorURLs) {
func deltaSourceTargets(sourceURL string, targetURLs []string, isForce bool, mirrorURLsCh chan<- mirrorURLs) {
defer close(mirrorURLsCh)
// source and targets are always directories
@@ -145,7 +145,7 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan
mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(suffix)}
continue
}
if differ == differSize && !mirrorIsForce {
if differ == differSize && !isForce {
// size differs and force not set
mirrorURLsCh <- mirrorURLs{Error: errOverWriteNotAllowed(sourceContent.URL.String())}
continue
@@ -164,8 +164,8 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan
}
}
func prepareMirrorURLs(sourceURL string, targetURLs []string) <-chan mirrorURLs {
func prepareMirrorURLs(sourceURL string, targetURLs []string, isForce bool) <-chan mirrorURLs {
mirrorURLsCh := make(chan mirrorURLs)
go deltaSourceTargets(sourceURL, targetURLs, mirrorURLsCh)
go deltaSourceTargets(sourceURL, targetURLs, isForce, mirrorURLsCh)
return mirrorURLsCh
}
-268
View File
@@ -1,268 +0,0 @@
/*
* Minio Client, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio-xl/pkg/quick"
)
// sessionV1 legacy session version definition.
type sessionV1 struct {
Version string `json:"version"`
Started time.Time `json:"started"`
CommandType string `json:"command-type"`
SessionID string `json:"session-id"`
URLs []string `json:"args"`
Files map[string]bool `json:"files"`
Lock *sync.Mutex `json:"-"`
}
// Stringify session data.
func (s sessionV1) String() string {
message := console.Colorize("Time", fmt.Sprintf("[%s] ", s.Started.Local().Format(printDate)))
message = message + console.Colorize("SessionID", fmt.Sprintf("%s", s.SessionID))
message = message + console.Colorize("Command", fmt.Sprintf(" [%s %s]", s.CommandType, strings.Join(s.URLs, " ")))
return message
}
// loadSessionV1 - reads session file if exists and re-initiates internal variables.
func loadSessionV1(sid string) (*sessionV1, *probe.Error) {
if !isSessionDirExists() {
return nil, probe.NewError(errors.New("Session folder does not exist."))
}
sessionFile, err := getSessionFileV1(sid)
if err != nil {
return nil, err.Trace(sid)
}
s := new(sessionV1)
s.Version = "1.0.0"
// map of command and files copied.
s.URLs = nil
s.Lock = new(sync.Mutex)
s.Files = make(map[string]bool)
qs, err := quick.New(s)
if err != nil {
return nil, err.Trace(s.Version)
}
err = qs.Load(sessionFile)
if err != nil {
return nil, err.Trace(sessionFile, s.Version)
}
return qs.Data().(*sessionV1), nil
}
// getSessionIDsV1 get session ids version 1.
func getSessionIDsV1() (sids []string) {
sessionDir, err := getSessionDir()
fatalIf(err.Trace(), "Unable to determine session folder.")
sessionList, e := filepath.Glob(sessionDir + "/*")
fatalIf(probe.NewError(e), "Unable to access session folder ‘"+sessionDir+"’.")
for _, path := range sessionList {
sidReg := regexp.MustCompile("^[a-zA-Z]{8}$")
sid := filepath.Base(path)
if sidReg.Match([]byte(sid)) {
sessionV1, err := loadSessionV1(sid)
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
if sessionV1.Version != "1.0.0" {
continue
}
sids = append(sids, sid)
}
}
return sids
}
// getSessionFileV1 get version 1 session file.
func getSessionFileV1(sid string) (string, *probe.Error) {
sessionDir, err := getSessionDir()
if err != nil {
return "", err.Trace()
}
sessionFile := filepath.Join(sessionDir, sid)
if _, err := os.Stat(sessionFile); err != nil {
return "", probe.NewError(err)
}
return sessionFile, nil
}
// migrateSessionV1ToV2 migrates all session files from v1 to v2.
// This function should be called from the main early on.
func migrateSessionV1ToV2() {
for _, sid := range getSessionIDsV1() {
sessionFileV1, err := getSessionFileV1(sid)
fatalIf(err.Trace(sid), "Unable to determine session file for ‘"+sid+"’.")
e := os.Remove(sessionFileV1)
fatalIf(probe.NewError(e), "Migration failed. Unable to remove old session file ‘"+sessionFileV1+"’.")
}
}
func migrateSessionV2ToV3() {
for _, sid := range getSessionIDs() {
oldSessionV2Header, err := loadSessionV2(sid)
// 1.1.0 intermediate version number is actually v2.
fatalIf(err.Trace(sid), "Unable to load version ‘1.1.0’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if oldSessionV2Header.Version == "4" {
return
}
sessionFile, err := getSessionFile(sid)
fatalIf(err.Trace(sid), "Unable to get session file.")
sessionDataFile, err := getSessionDataFile(sid)
fatalIf(err.Trace(sid), "Unable to get session data file.")
if e := os.Remove(sessionFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version 2 session files.")
}
if e := os.Remove(sessionDataFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version 2 session data files.")
}
}
}
// sessionV3Header
type sessionV3Header struct {
Version string `json:"version"`
When time.Time `json:"time"`
RootPath string `json:"workingFolder"`
CommandType string `json:"commandType"`
CommandArgs []string `json:"cmdArgs"`
CommandBoolFlag struct {
Key string
Value bool
} `json:"cmdBoolFlag"`
CommandIntFlag struct {
Key string
Value int
} `json:"cmdIntFlag"`
CommandStringFlag struct {
Key string
Value string
} `json:"cmdStringFlag"`
LastCopied string `json:"lastCopied"`
TotalBytes int64 `json:"totalBytes"`
TotalObjects int `json:"totalObjects"`
}
// sessionV3
type sessionV3 struct {
Header *sessionV3Header
SessionID string
mutex *sync.Mutex
DataFP *sessionDataFP
sigCh bool
}
// loadSessionV3 - reads session file if exists and re-initiates internal variables
func loadSessionV3(sid string) (*sessionV3, *probe.Error) {
if !isSessionDirExists() {
return nil, errInvalidArgument().Trace()
}
sessionFile, err := getSessionFile(sid)
if err != nil {
return nil, err.Trace(sid)
}
if _, err := os.Stat(sessionFile); err != nil {
return nil, probe.NewError(err)
}
s := &sessionV3{}
s.Header = &sessionV3Header{}
s.SessionID = sid
s.Header.Version = "3"
qs, err := quick.New(s.Header)
if err != nil {
return nil, err.Trace(sid, s.Header.Version)
}
err = qs.Load(sessionFile)
if err != nil {
return nil, err.Trace(sid, s.Header.Version)
}
s.mutex = new(sync.Mutex)
s.Header = qs.Data().(*sessionV3Header)
sessionDataFile, err := getSessionDataFile(s.SessionID)
if err != nil {
return nil, err.Trace(sid, s.Header.Version)
}
var e error
dataFile, e := os.Open(sessionDataFile)
fatalIf(probe.NewError(e), "Unable to open session data file \""+sessionDataFile+"\".")
s.DataFP = &sessionDataFP{false, dataFile}
return s, nil
}
// sessionV2Header new session version 2 header.
type sessionV2Header struct {
Version string `json:"version"`
When time.Time `json:"time"`
RootPath string `json:"working-folder"`
CommandType string `json:"command-type"`
CommandArgs []string `json:"cmd-args"`
LastCopied string `json:"last-copied"`
TotalBytes int64 `json:"total-bytes"`
TotalObjects int `json:"total-objects"`
}
// loadSessionV2 - reads session file if exists and re-initiates internal variables.
func loadSessionV2(sid string) (*sessionV2Header, *probe.Error) {
if !isSessionDirExists() {
return nil, errInvalidArgument().Trace()
}
sessionFile, err := getSessionFile(sid)
if err != nil {
return nil, err.Trace(sid)
}
if _, err := os.Stat(sessionFile); err != nil {
return nil, probe.NewError(err)
}
sessionHeader := &sessionV2Header{}
// V2 is actually v1.1. We have moved to a serial single digit version.
sessionHeader.Version = "1.1.0"
qs, err := quick.New(sessionHeader)
if err != nil {
return nil, err.Trace(sid, sessionHeader.Version)
}
err = qs.Load(sessionFile)
if err != nil {
return nil, err.Trace(sid, sessionHeader.Version)
}
return sessionHeader, nil
}
+12 -10
View File
@@ -74,7 +74,7 @@ EXAMPLES:
}
// bySessionWhen is a type for sorting session metadata by time.
type bySessionWhen []*sessionV4
type bySessionWhen []*sessionV5
func (b bySessionWhen) Len() int { return len(b) }
func (b bySessionWhen) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
@@ -82,9 +82,9 @@ func (b bySessionWhen) Less(i, j int) bool { return b[i].Header.When.Before(b[j]
// listSessions list all current sessions.
func listSessions() *probe.Error {
var bySessions []*sessionV4
var bySessions []*sessionV5
for _, sid := range getSessionIDs() {
s, err := loadSessionV4(sid)
s, err := loadSessionV5(sid)
if err != nil {
return err.Trace()
}
@@ -122,7 +122,7 @@ func (c clearSessionMessage) JSON() string {
func clearSession(sid string) {
if sid == "all" {
for _, sid := range getSessionIDs() {
session, err := loadSessionV4(sid)
session, err := loadSessionV5(sid)
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
@@ -136,7 +136,7 @@ func clearSession(sid string) {
fatalIf(errDummy().Trace(), "Session ‘"+sid+"’ not found.")
}
session, err := loadSessionV4(sid)
session, err := loadSessionV5(sid)
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
if session != nil {
@@ -145,7 +145,7 @@ func clearSession(sid string) {
}
}
func sessionExecute(s *sessionV4) {
func sessionExecute(s *sessionV5) {
switch s.Header.CommandType {
case "cp":
doCopySession(s)
@@ -199,12 +199,14 @@ func mainSession(ctx *cli.Context) {
if !isSessionExists(sid) {
fatalIf(errDummy().Trace(), "Session ‘"+sid+"’ not found.")
}
s, err := loadSessionV4(sid)
s, err := loadSessionV5(sid)
fatalIf(err.Trace(sid), "Unable to load session.")
// extra check for testing purposes.
if s == nil {
return
}
fatalIf(errDummy().Trace(), "Loaded session is nil.")
// Restore the state of global variables from this previous session.
s.RestoreGlobals()
savedCwd, e := os.Getwd()
fatalIf(probe.NewError(e), "Unable to determine current working folder.")
+60 -63
View File
@@ -32,13 +32,14 @@ import (
"github.com/minio/minio-xl/pkg/quick"
)
func migrateSessionV3ToV4() {
func migrateSessionV4ToV5() {
for _, sid := range getSessionIDs() {
oldSessionV3, err := loadSessionV3(sid)
fatalIf(err.Trace(sid), "Unable to load version ‘3’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if oldSessionV3.Header.Version == "4" {
sessionV5, err := loadSessionV5(sid)
fatalIf(err.Trace(sid), "Unable to load version ‘5’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if sessionV5.Header.Version == "5" { // It is new format.
return
}
/*** Remove all session files older than v5 ***/
sessionFile, err := getSessionFile(sid)
fatalIf(err.Trace(sid), "Unable to get session file.")
@@ -46,46 +47,32 @@ func migrateSessionV3ToV4() {
sessionDataFile, err := getSessionDataFile(sid)
fatalIf(err.Trace(sid), "Unable to get session data file.")
console.Println("Removing unsupported session file ‘" + sessionFile + "’ version ‘" + sessionV5.Header.Version + "’.")
if e := os.Remove(sessionFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version 2 session files.")
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV5.Header.Version+"’ session file ‘"+sessionFile+"’.")
}
if e := os.Remove(sessionDataFile); e != nil {
fatalIf(probe.NewError(e), "Unable to remove version 2 session data files.")
fatalIf(probe.NewError(e), "Unable to remove version ‘"+sessionV5.Header.Version+"’ session data file ‘"+sessionDataFile+"’.")
}
}
}
// cmdBoolFlag boolean flag container for a command.
type cmdBoolFlag struct {
Key string
Value bool
}
// cmdIntFlag int flag container for a command.
type cmdIntFlag struct {
Key string
Value int
}
// cmdStringFlag string flag container for a command.
type cmdStringFlag struct {
Key string
Value string
}
// sessionV4Header for resumable sessions.
type sessionV4Header struct {
Version string `json:"version"`
When time.Time `json:"time"`
RootPath string `json:"workingFolder"`
CommandType string `json:"commandType"`
CommandArgs []string `json:"cmdArgs"`
CommandBoolFlag []cmdBoolFlag `json:"cmdBoolFlag"`
CommandIntFlag []cmdIntFlag `json:"cmdIntFlag"`
CommandStringFlag []cmdStringFlag `json:"cmdStringFlag"`
LastCopied string `json:"lastCopied"`
TotalBytes int64 `json:"totalBytes"`
TotalObjects int `json:"totalObjects"`
// sessionV5Header for resumable sessions.
type sessionV5Header struct {
Version string `json:"version"`
When time.Time `json:"time"`
RootPath string `json:"workingFolder"`
GlobalBoolFlags map[string]bool `json:"globalBoolFlags"`
GlobalIntFlags map[string]int `json:"globalIntFlags"`
GlobalStringFlags map[string]string `json:"globalStringFlags"`
CommandType string `json:"commandType"`
CommandArgs []string `json:"cmdArgs"`
CommandBoolFlags map[string]bool `json:"cmdBoolFlags"`
CommandIntFlags map[string]int `json:"cmdIntFlags"`
CommandStringFlags map[string]string `json:"cmdStringFlags"`
LastCopied string `json:"lastCopied"`
TotalBytes int64 `json:"totalBytes"`
TotalObjects int `json:"totalObjects"`
}
// sessionMessage container for session messages
@@ -97,9 +84,9 @@ type sessionMessage struct {
CommandArgs []string `json:"commandArgs"`
}
// sessionV4 resumable session container.
type sessionV4 struct {
Header *sessionV4Header
// sessionV5 resumable session container.
type sessionV5 struct {
Header *sessionV5Header
SessionID string
mutex *sync.Mutex
DataFP *sessionDataFP
@@ -118,7 +105,7 @@ func (file *sessionDataFP) Write(p []byte) (int, error) {
}
// String colorized session message.
func (s sessionV4) String() string {
func (s sessionV5) String() string {
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
@@ -126,7 +113,7 @@ func (s sessionV4) String() string {
}
// JSON jsonified session message.
func (s sessionV4) JSON() string {
func (s sessionV5) JSON() string {
sessionMsg := sessionMessage{
SessionID: s.SessionID,
Time: s.Header.When.Local(),
@@ -140,16 +127,19 @@ func (s sessionV4) JSON() string {
return string(sessionBytes)
}
// newSessionV4 provides a new session.
func newSessionV4() *sessionV4 {
s := &sessionV4{}
s.Header = &sessionV4Header{}
s.Header.Version = "4"
// newSessionV5 provides a new session.
func newSessionV5() *sessionV5 {
s := &sessionV5{}
s.Header = &sessionV5Header{}
s.Header.Version = "5"
// map of command and files copied.
s.Header.GlobalBoolFlags = make(map[string]bool)
s.Header.GlobalIntFlags = make(map[string]int)
s.Header.GlobalStringFlags = make(map[string]string)
s.Header.CommandArgs = nil
s.Header.CommandBoolFlag = []cmdBoolFlag{{Key: "", Value: false}}
s.Header.CommandIntFlag = []cmdIntFlag{{Key: "", Value: 0}}
s.Header.CommandStringFlag = []cmdStringFlag{{Key: "", Value: ""}}
s.Header.CommandBoolFlags = make(map[string]bool)
s.Header.CommandIntFlags = make(map[string]int)
s.Header.CommandStringFlags = make(map[string]string)
s.Header.When = time.Now().UTC()
s.mutex = new(sync.Mutex)
s.SessionID = newRandomID(8)
@@ -165,7 +155,7 @@ func newSessionV4() *sessionV4 {
}
// HasData provides true if this is a session resume, false otherwise.
func (s sessionV4) HasData() bool {
func (s sessionV5) HasData() bool {
if s.Header.LastCopied == "" {
return false
}
@@ -173,21 +163,21 @@ func (s sessionV4) HasData() bool {
}
// NewDataReader provides reader interface to session data file.
func (s *sessionV4) NewDataReader() io.Reader {
func (s *sessionV5) NewDataReader() io.Reader {
// DataFP is always intitialized, either via new or load functions.
s.DataFP.Seek(0, os.SEEK_SET)
return io.Reader(s.DataFP)
}
// NewDataReader provides writer interface to session data file.
func (s *sessionV4) NewDataWriter() io.Writer {
func (s *sessionV5) NewDataWriter() io.Writer {
// DataFP is always intitialized, either via new or load functions.
s.DataFP.Seek(0, os.SEEK_SET)
return io.Writer(s.DataFP)
}
// Save this session.
func (s *sessionV4) Save() *probe.Error {
func (s *sessionV5) Save() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
@@ -210,8 +200,15 @@ func (s *sessionV4) Save() *probe.Error {
return qs.Save(sessionFile).Trace(sessionFile)
}
// RestoreGlobals restores the state of global variables.
func (s *sessionV5) RestoreGlobals() {
globalQuietFlag = s.Header.GlobalBoolFlags["quiet"]
globalJSONFlag = s.Header.GlobalBoolFlags["json"]
globalDebugFlag = s.Header.GlobalBoolFlags["debug"]
}
// Close ends this session and removes all associated session files.
func (s *sessionV4) Close() *probe.Error {
func (s *sessionV5) Close() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
@@ -232,7 +229,7 @@ func (s *sessionV4) Close() *probe.Error {
}
// Delete removes all the session files.
func (s *sessionV4) Delete() *probe.Error {
func (s *sessionV5) Delete() *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
@@ -262,14 +259,14 @@ func (s *sessionV4) Delete() *probe.Error {
}
// Close a session and exit.
func (s sessionV4) CloseAndDie() {
func (s sessionV5) CloseAndDie() {
s.Close()
console.Infoln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’")
os.Exit(0)
}
// loadSessionV4 - reads session file if exists and re-initiates internal variables
func loadSessionV4(sid string) (*sessionV4, *probe.Error) {
// loadSessionV5 - reads session file if exists and re-initiates internal variables
func loadSessionV5(sid string) (*sessionV5, *probe.Error) {
if !isSessionDirExists() {
return nil, errInvalidArgument().Trace()
}
@@ -282,10 +279,10 @@ func loadSessionV4(sid string) (*sessionV4, *probe.Error) {
return nil, probe.NewError(err)
}
s := &sessionV4{}
s.Header = &sessionV4Header{}
s := &sessionV5{}
s.Header = &sessionV5Header{}
s.SessionID = sid
s.Header.Version = "4"
s.Header.Version = "5"
qs, err := quick.New(s.Header)
if err != nil {
return nil, err.Trace(sid, s.Header.Version)
@@ -296,7 +293,7 @@ func loadSessionV4(sid string) (*sessionV4, *probe.Error) {
}
s.mutex = new(sync.Mutex)
s.Header = qs.Data().(*sessionV4Header)
s.Header = qs.Data().(*sessionV5Header)
sessionDataFile, err := getSessionDataFile(s.SessionID)
if err != nil {
+2 -8
View File
@@ -26,14 +26,8 @@ import (
// migrateSession migrates all previous migration to latest.
func migrateSession() {
// Migrate session V1 to V2.
migrateSessionV1ToV2()
// Migrate session V2 to V3.
migrateSessionV2ToV3()
// Migrate session V3 to V4.
migrateSessionV3ToV4()
// We no longer support sessions older than v5. They will be removed.
migrateSessionV4ToV5()
}
// createSessionDir - create session directory.
+8 -6
View File
@@ -36,14 +36,14 @@ func (s *TestSuite) TestSession(c *C) {
c.Assert(err, IsNil)
c.Assert(isSessionDirExists(), Equals, true)
session := newSessionV4()
session := newSessionV5()
c.Assert(session.Header.CommandArgs, IsNil)
c.Assert(len(session.SessionID), Equals, 8)
err = session.Close()
c.Assert(err, IsNil)
savedSession, err := loadSessionV4(session.SessionID)
savedSession, err := loadSessionV5(session.SessionID)
c.Assert(err, IsNil)
c.Assert(session.SessionID, Equals, savedSession.SessionID)
@@ -69,9 +69,11 @@ func (s *TestSuite) TestSessionContext(c *C) {
// reset back
console.IsExited = false
e = app.Run([]string{os.Args[0], "session", "resume", "invalid"})
c.Assert(e, IsNil)
c.Assert(console.IsExited, Equals, true)
/*
e = app.Run([]string{os.Args[0], "session", "resume", "invalid"})
c.Assert(e, IsNil)
c.Assert(console.IsExited, Equals, true)
*/
// reset back
console.IsExited = false
@@ -90,7 +92,7 @@ func (s *TestSuite) TestSessionContext(c *C) {
// reset back
console.IsExited = false
session := newSessionV4()
session := newSessionV5()
c.Assert(session.Header.CommandArgs, IsNil)
c.Assert(len(session.SessionID), Equals, 8)
-8
View File
@@ -31,10 +31,6 @@ var (
return probe.NewError(errors.New("Invalid arguments provided, cannot proceed.")).Untrace()
}
errSourceListEmpty = func() *probe.Error {
return probe.NewError(errors.New("Source argument list is empty.")).Untrace()
}
errNoMatchingHost = func(URL string) *probe.Error {
return probe.NewError(errors.New("No matching host found for the given URL ‘" + URL + "’.")).Untrace()
}
@@ -55,10 +51,6 @@ var (
return probe.NewError(errors.New("Overwrite not allowed for ‘" + URL + "’. Use ‘--force’ to override this behavior."))
}
errSourceNotRecursive = func(URL string) *probe.Error {
return probe.NewError(errors.New("Source ‘" + URL + "’ is not recursive.")).Untrace()
}
errSourceIsDir = func(URL string) *probe.Error {
return probe.NewError(errors.New("Source ‘" + URL + "’ is a folder.")).Untrace()
}
-17
View File
@@ -35,23 +35,6 @@ func urlJoinPath(url1, url2 string) string {
return client.JoinURLs(u1, u2).String()
}
// isURLRecursive - find out if requested url is recursive.
func isURLRecursive(urlStr string) bool {
return strings.HasSuffix(urlStr, recursiveSeparator)
}
// stripRecursiveURL - Strip "..." from the URL if present.
func stripRecursiveURL(urlStr string) string {
if !isURLRecursive(urlStr) {
return urlStr
}
urlStr = strings.TrimSuffix(urlStr, recursiveSeparator)
if urlStr == "" {
urlStr = "."
}
return urlStr
}
// args2URLs extracts source and target URLs from command-line args.
func args2URLs(args []string) ([]string, *probe.Error) {
// Convert arguments to URLs: expand alias, fix format...