Merge pull request #1044 from harshavardhana/checksyntax-cmd

Add checkCommandSyntax for all commands
This commit is contained in:
Harshavardhana
2015-08-24 19:33:28 -07:00
11 changed files with 313 additions and 140 deletions
+55 -3
View File
@@ -17,8 +17,13 @@
package main
import (
"encoding/json"
"strings"
"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"
)
@@ -57,20 +62,67 @@ EXAMPLES:
`,
}
func mainAccess(ctx *cli.Context) {
// AccessMessage is container for access command on bucket success and failure messages
type AccessMessage struct {
Status string `json:"status"`
Bucket string `json:"bucket"`
Acl string `json:"acl"`
Error *probe.Error `json:"error,omitempty"`
}
func (s AccessMessage) String() string {
if !globalJSONFlag {
if s.Status == "success" {
return console.Colorize("Access", "Set access permission ‘"+s.Acl+"’ updated successfully for ‘"+s.Bucket+"’")
}
}
accessJSONBytes, err := json.Marshal(s)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
return string(accessJSONBytes)
}
func checkAccessSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code
}
config := mustGetMcConfig()
if len(ctx.Args()) < 2 {
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code
}
acl := bucketACL(ctx.Args().First())
if !acl.isValidBucketACL() {
fatalIf(errDummy().Trace(),
"Unrecognized permission ‘"+acl.String()+"’. Allowed values are [private, public, readonly].")
}
for _, arg := range ctx.Args().Tail() {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
}
}
func mainAccess(ctx *cli.Context) {
checkAccessSyntax(ctx)
console.SetCustomTheme(map[string]*color.Color{
"Access": color.New(color.FgGreen, color.Bold),
})
acl := bucketACL(ctx.Args().First())
config := mustGetMcConfig()
for _, arg := range ctx.Args().Tail() {
targetURL, err := getCanonicalizedURL(arg, config.Aliases)
fatalIf(err.Trace(arg), "Unable to parse argument ‘"+arg+"’.")
fatalIf(doUpdateAccessCmd(targetURL, acl).Trace(targetURL), "Unable to set access permission ‘"+acl.String()+"’ for ‘"+targetURL+"’.")
fatalIf(doUpdateAccessCmd(targetURL, acl).Trace(targetURL, acl.String()), "Unable to set access permission ‘"+acl.String()+"’ for ‘"+targetURL+"’.")
console.Println(AccessMessage{
Status: "success",
Bucket: targetURL,
Acl: acl.String(),
Error: nil,
})
}
}
+29 -14
View File
@@ -19,6 +19,7 @@ package main
import (
"io"
"os"
"strings"
"syscall"
"github.com/minio/cli"
@@ -56,28 +57,42 @@ EXAMPLES:
4. Concatenate a non english file name from Amazon S3 cloud storage.
$ mc {{.Name}} s3:andoria/本語 > /tmp/本語
5. Behave like operating system tool ‘cat’, used for shell aliases.
$ echo "Hello, World!" | mc --mimic cat
Hello, World!
`,
}
func mainCat(ctx *cli.Context) {
stdinMode := false
if globalMimicFlag {
if !ctx.Args().Present() {
stdinMode = true
}
} else if !ctx.Args().Present() || ctx.Args().First() == "help" {
func checkCatSyntax(ctx *cli.Context) {
if (!ctx.Args().Present() && !globalMimicFlag) || ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "cat", 1) // last argument is exit code
}
if stdinMode {
fatalIf(catOut(os.Stdin).Trace(), "Unable to read from stdin.")
} else {
// Convert arguments to URLs: expand alias, fix format...
for _, arg := range ctx.Args() {
fatalIf(catURL(arg).Trace(arg), "Unable to read from ‘"+arg+"’.")
for _, arg := range ctx.Args() {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
}
}
func mainCat(ctx *cli.Context) {
checkCatSyntax(ctx)
stdinMode := false
if globalMimicFlag && !ctx.Args().Present() {
stdinMode = true
}
// handle std input data
if stdinMode {
fatalIf(catOut(os.Stdin).Trace(), "Unable to read from stdin.")
return
}
// Convert arguments to URLs: expand alias, fix format...
for _, arg := range ctx.Args() {
fatalIf(catURL(arg).Trace(arg), "Unable to read from ‘"+arg+"’.")
}
}
func catURL(sourceURL string) *probe.Error {
+43 -24
View File
@@ -46,14 +46,15 @@ var configCmd = cli.Command{
mc {{.Name}} - {{.Usage}}
USAGE:
mc {{.Name}}{{if .Flags}} [ARGS...]{{end}} alias NAME HOSTURL
mc {{.Name}} add alias ALIASNAME URL
mc {{.Name}} list alias
EXAMPLES:
1. Add alias URLs.
$ mc {{.Name}} alias zek https://s3.amazonaws.com/
1. Add aliases for a URL
$ mc {{.Name}} add alias zek https://s3.amazonaws.com/
2. List all aliased URLs.
$ mc {{.Name}} alias list
$ mc {{.Name}} list alias
`,
}
@@ -67,7 +68,7 @@ type AliasMessage struct {
// String string printer for Content metadata
func (a AliasMessage) String() string {
if !globalJSONFlag {
message := console.Colorize("Alias", fmt.Sprintf("[%s] <-", a.Alias))
message := console.Colorize("Alias", fmt.Sprintf("[%s] <- ", a.Alias))
message += console.Colorize("URL", fmt.Sprintf("%s", a.URL))
return message
}
@@ -77,8 +78,7 @@ func (a AliasMessage) String() string {
return string(jsonMessageBytes)
}
// mainConfig is the handle for "mc config" sub-command. writes configuration data in json format to config file.
func mainConfig(ctx *cli.Context) {
func checkConfigSyntax(ctx *cli.Context) {
// show help if nothing is set
if !ctx.Args().Present() || ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
@@ -86,6 +86,32 @@ func mainConfig(ctx *cli.Context) {
if strings.TrimSpace(ctx.Args().First()) == "" {
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
if len(ctx.Args().Tail()) > 3 {
fatalIf(errDummy().Trace(), "Incorrect number of arguments to config command")
}
switch strings.TrimSpace(ctx.Args().First()) {
case "add":
if strings.TrimSpace(ctx.Args().Tail().First()) != "alias" {
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().Tail().First()) == "alias" {
if len(ctx.Args().Tail().Tail()) != 2 {
fatalIf(errInvalidArgument().Trace(), "Incorrect number of arguments for add alias command.")
}
}
case "list":
if strings.TrimSpace(ctx.Args().Tail().First()) != "alias" {
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
default:
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
}
// mainConfig is the handle for "mc config" sub-command. writes configuration data in json format to config file.
func mainConfig(ctx *cli.Context) {
checkConfigSyntax(ctx)
// set new custom coloring
console.SetCustomTheme(map[string]*color.Color{
"Alias": color.New(color.FgCyan, color.Bold),
@@ -94,35 +120,28 @@ func mainConfig(ctx *cli.Context) {
arg := ctx.Args().First()
tailArgs := ctx.Args().Tail()
if len(tailArgs) > 2 {
fatalIf(errDummy().Trace(), "Incorrect number of arguments to config command. Please read ‘mc config help’")
}
switch arg {
case "alias":
if tailArgs.First() == "list" {
switch strings.TrimSpace(arg) {
case "add":
if strings.TrimSpace(tailArgs.First()) == "alias" {
addAlias(tailArgs.Get(1), tailArgs.Get(2))
}
case "list":
if strings.TrimSpace(tailArgs.First()) == "alias" {
conf := newConfigV2()
config, err := quick.New(conf)
fatalIf(err.Trace(conf.Version), "Failed to initialize ‘quick’ configuration data structure.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to load config path")
configPath := mustGetMcConfigPath()
err = config.Load(configPath)
fatalIf(err.Trace(configPath), "Unable to load config path")
// convert interface{} back to its original struct
newConf := config.Data().(*configV2)
for k, v := range newConf.Aliases {
console.Println(AliasMessage{k, v})
}
return
}
if len(tailArgs) < 2 {
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
alias := tailArgs[0]
url := tailArgs[1]
addAlias(alias, url)
default:
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
}
+4 -2
View File
@@ -24,14 +24,16 @@ import (
)
func (s *CmdTestSuite) TestConfigContext(c *C) {
err := app.Run([]string{os.Args[0], "config", "alias", "test", "htt://test.io"})
console.IsExited = false
err := app.Run([]string{os.Args[0], "config", "add", "alias", "test", "htt://test.io"})
c.Assert(err, IsNil)
c.Assert(console.IsExited, Equals, true)
// reset back
console.IsExited = false
err = app.Run([]string{os.Args[0], "config", "alias", "new", "http://test.io"})
err = app.Run([]string{os.Args[0], "config", "add", "alias", "new", "http://test.io"})
c.Assert(err, IsNil)
c.Assert(console.IsExited, Equals, false)
+11 -14
View File
@@ -25,19 +25,22 @@ import (
"github.com/minio/minio/pkg/probe"
)
// ErrorMessage container for error messages
type ErrorMessage struct {
Message string `json:"message"`
Cause error `json:"cause"`
Type string `json:"type"`
CallTrace []probe.TracePoint `json:"trace,omitempty"`
SysInfo map[string]string `json:"sysinfo"`
}
// fatalIf wrapper function which takes error and selectively prints stack frames if available on debug
func fatalIf(err *probe.Error, msg string) {
if err == nil {
return
}
if globalJSONFlag {
errorMessage := struct {
Message string `json:"message"`
Cause error `json:"cause"`
Type string `json:"type"`
CallTrace []probe.TracePoint `json:"trace,omitempty"`
SysInfo map[string]string `json:"sysinfo"`
}{
errorMessage := ErrorMessage{
Message: msg,
Type: "fatal",
Cause: err.ToGoError(),
@@ -65,13 +68,7 @@ func errorIf(err *probe.Error, msg string) {
return
}
if globalJSONFlag {
errorMessage := struct {
Message string `json:"message"`
Cause error `json:"cause"`
Type string `json:"type"`
CallTrace []probe.TracePoint `json:"trace,omitempty"`
SysInfo map[string]string `json:"sysinfo"`
}{
errorMessage := ErrorMessage{
Message: msg,
Type: "error",
Cause: err.ToGoError(),
+36 -15
View File
@@ -17,6 +17,8 @@
package main
import (
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
@@ -42,45 +44,64 @@ FLAGS:
{{end}}{{ end }}
EXAMPLES:
1. List objects recursively on Minio cloud storage.
$ mc {{.Name}} https://play.minio.io:9000/backup/...
[2015-03-28 12:47:50 PDT] 34MiB 2006-Jan-1/backup.tar.gz
[2015-03-31 14:46:33 PDT] 55MiB 2006-Mar-1/backup.tar.gz
2. List buckets on Amazon S3 cloud storage.
1. List buckets on Amazon S3 cloud storage.
$ mc {{.Name}} https://s3.amazonaws.com/
[2015-01-20 15:42:00 PST] 0B rom/
[2015-01-15 00:05:40 PST] 0B zek/
3. List buckets from Amazon S3 cloud storage and recursively list objects from Minio cloud storage.
2. List buckets from Amazon S3 cloud storage and recursively list objects from Minio cloud storage.
$ mc {{.Name}} https://s3.amazonaws.com/ https://play.minio.io:9000/backup/...
2015-01-15 00:05:40 PST 0B zek/
2015-03-31 14:46:33 PDT 55MiB 2006-Mar-1/backup.tar.gz
4. List files recursively on local filesystem on Windows.
3. List files recursively on local filesystem on Windows.
$ mc {{.Name}} C:\Users\Worf\...
[2015-03-28 12:47:50 PDT] 11.00MiB Martok\Klingon Council Ministers.pdf
[2015-03-31 14:46:33 PDT] 15.00MiB Gowron\Khitomer Conference Details.pdf
5. List files with non english characters on Amazon S3 cloud storage.
4. List files with non english characters on Amazon S3 cloud storage.
$ mc ls s3:andoria/本...
[2015-05-19 17:21:49 PDT] 41B 本語.pdf
[2015-05-19 17:24:19 PDT] 41B 本語.txt
[2015-05-19 17:28:22 PDT] 41B 本語.md
5. Behave like operating system tool ‘ls’, used for shell aliases.
$ mc --mimic ls
...
[2015-05-19 17:28:22 PDT] 41B 本語.md
`,
}
func checkListSyntax(ctx *cli.Context) {
args := ctx.Args()
if !ctx.Args().Present() {
if globalMimicFlag {
args = []string{"."}
} else {
cli.ShowCommandHelpAndExit(ctx, "ls", 1) // last argument is exit code
}
}
if ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "ls", 1) // last argument is exit code
}
for _, arg := range args {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
}
}
// mainList - is a handler for mc ls command
func mainList(ctx *cli.Context) {
checkListSyntax(ctx)
args := ctx.Args()
if globalMimicFlag {
if !ctx.Args().Present() {
args = []string{"."}
}
} else if !ctx.Args().Present() || ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "ls", 1) // last argument is exit code
// Operating system tool behavior
if globalMimicFlag && !ctx.Args().Present() {
args = []string{"."}
}
console.SetCustomTheme(map[string]*color.Color{
"File": color.New(color.FgWhite),
"Dir": color.New(color.FgCyan, color.Bold),
+48 -6
View File
@@ -17,6 +17,10 @@
package main
import (
"encoding/json"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/probe"
@@ -52,17 +56,55 @@ EXAMPLES:
`,
}
// mainMakeBucket is the handler for mc mb command
func mainMakeBucket(ctx *cli.Context) {
// MakeBucketMessage is container for make bucket success and failure messages
type MakeBucketMessage struct {
Status string `json:"status"`
Bucket string `json:"bucket"`
Error *probe.Error `json:"error,omitempty"`
}
func (s MakeBucketMessage) String() string {
if !globalJSONFlag {
if s.Status == "success" {
return console.Colorize("MakeBucket", "Bucket created successfully ‘"+s.Bucket+"’")
}
}
makeBucketJSONBytes, err := json.Marshal(s)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
return string(makeBucketJSONBytes)
}
func checkMakeBucketSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "mb", 1) // last argument is exit code
}
for _, arg := range ctx.Args() {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
}
}
// mainMakeBucket is the handler for mc mb command
func mainMakeBucket(ctx *cli.Context) {
checkMakeBucketSyntax(ctx)
console.SetCustomTheme(map[string]*color.Color{
"MakeBucket": color.New(color.FgGreen, color.Bold),
})
config := mustGetMcConfig()
for _, arg := range ctx.Args() {
targetURL, err := getCanonicalizedURL(arg, config.Aliases)
fatalIf(err.Trace(arg), "Unable to parse argument ‘"+arg+"’.")
fatalIf(err.Trace(arg), "Unable to parse bucket ‘"+arg+"’.")
fatalIf(doMakeBucketCmd(targetURL).Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.")
console.Infoln("Bucket created successfully: " + targetURL)
console.Println(MakeBucketMessage{
Status: "success",
Bucket: targetURL,
Error: nil,
})
}
}
@@ -70,11 +112,11 @@ func mainMakeBucket(ctx *cli.Context) {
func doMakeBucketCmd(targetURL string) *probe.Error {
clnt, err := target2Client(targetURL)
if err != nil {
return err.Trace()
return err.Trace(targetURL)
}
err = clnt.MakeBucket()
if err != nil {
return err.Trace()
return err.Trace(targetURL)
}
return nil
}
+16 -14
View File
@@ -30,29 +30,29 @@ func (s *CmdTestSuite) TestMbAndAccessCmd(c *C) {
root, err := ioutil.TempDir(os.TempDir(), "cmd-")
c.Assert(err, IsNil)
defer os.RemoveAll(root)
{
err := doMakeBucketCmd(filepath.Join(root, "bucket"))
c.Assert(err, IsNil)
err = doUpdateAccessCmd(filepath.Join(root, "bucket"), "public-read-write")
c.Assert(err, IsNil)
perr := doMakeBucketCmd(filepath.Join(root, "bucket"))
c.Assert(perr, IsNil)
err = doUpdateAccessCmd(filepath.Join(root, "bucket"), "invalid")
c.Assert(err, Not(IsNil))
perr = doUpdateAccessCmd(filepath.Join(root, "bucket"), "public-read-write")
c.Assert(perr, IsNil)
err = doMakeBucketCmd(server.URL + "/bucket")
c.Assert(err, IsNil)
perr = doUpdateAccessCmd(filepath.Join(root, "bucket"), "invalid")
c.Assert(perr, Not(IsNil))
err = doUpdateAccessCmd(server.URL+"/bucket", "public-read-write")
c.Assert(err, IsNil)
perr = doMakeBucketCmd(server.URL + "/bucket")
c.Assert(perr, IsNil)
err = doUpdateAccessCmd(server.URL+"/bucket", "invalid")
c.Assert(err, Not(IsNil))
}
perr = doUpdateAccessCmd(server.URL+"/bucket", "public-read-write")
c.Assert(perr, IsNil)
perr = doUpdateAccessCmd(server.URL+"/bucket", "invalid")
c.Assert(perr, Not(IsNil))
}
func (s *CmdTestSuite) TestMBContext(c *C) {
console.IsExited = false
err := app.Run([]string{os.Args[0], "mb", server.URL + "/bucket"})
c.Assert(err, IsNil)
c.Assert(console.IsExited, Equals, false)
@@ -69,6 +69,8 @@ func (s *CmdTestSuite) TestMBContext(c *C) {
}
func (s *CmdTestSuite) TestAccessContext(c *C) {
console.IsExited = false
err := app.Run([]string{os.Args[0], "access", "private", server.URL + "/bucket"})
c.Assert(err, IsNil)
c.Assert(console.IsExited, Equals, false)
+25 -19
View File
@@ -113,16 +113,38 @@ func sessionExecute(s *sessionV2) {
}
}
func mainSession(ctx *cli.Context) {
func checkSessionSyntax(ctx *cli.Context) {
if len(ctx.Args()) < 1 || ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().First()) == "" {
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
}
switch strings.TrimSpace(ctx.Args().First()) {
case "list":
case "resume":
if strings.TrimSpace(ctx.Args().Tail().First()) == "" {
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
case "clear":
if len(ctx.Args()) == 2 {
if strings.TrimSpace(ctx.Args().Tail().First()) == "" {
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
}
default:
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
}
func mainSession(ctx *cli.Context) {
checkSessionSyntax(ctx)
if !isSessionDirExists() {
fatalIf(createSessionDir().Trace(), "Unable to create session directory.")
}
console.SetCustomTheme(map[string]*color.Color{
"Command": color.New(color.FgWhite, color.Bold),
"SessionID": color.New(color.FgYellow, color.Bold),
@@ -134,15 +156,7 @@ func mainSession(ctx *cli.Context) {
case "list":
fatalIf(listSessions().Trace(), "Unable to list sessions.")
case "resume":
if len(ctx.Args().Tail()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().Tail().First()) == "" {
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
}
sid := strings.TrimSpace(ctx.Args().Tail().First())
if !isSession(sid) {
fatalIf(errDummy().Trace(), "Session ‘"+sid+"’ not found.")
}
@@ -170,20 +184,12 @@ func mainSession(ctx *cli.Context) {
err = s.Delete()
fatalIf(err.Trace(), "Unable to clear session files properly.")
// change dir back
// chdir back to saved path
e = os.Chdir(savedCwd)
fatalIf(probe.NewError(e), "Unable to change directory to saved path ‘"+savedCwd+"’.")
// purge a requested pending session, if "*" purge everything
// purge a requested pending session, if "all" purge everything
case "clear":
if len(ctx.Args().Tail()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().Tail().First()) == "" {
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
}
clearSession(strings.TrimSpace(ctx.Args().Tail().First()))
default:
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
}
}
+46 -28
View File
@@ -63,33 +63,6 @@ EXAMPLES:
`,
}
// mainShare - is a handler for mc share command
func mainShare(ctx *cli.Context) {
if !ctx.Args().Present() || ctx.Args().First() == "help" || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
}
console.SetCustomTheme(map[string]*color.Color{
"Share": color.New(color.FgGreen, color.Bold),
})
args := ctx.Args()
config := mustGetMcConfig()
/// get first and last arguments
url := args.First() // url to be shared
// default expiration is 7days
expires := time.Duration(604800) * time.Second
if len(args) == 2 {
var err error
expires, err = time.ParseDuration(args.Last())
fatalIf(probe.NewError(err), "Unable to parse time argument.")
}
targetURL, err := getCanonicalizedURL(url, config.Aliases)
fatalIf(err.Trace(url), "Unable to parse argument ‘"+url+"’.")
// if recursive strip off the "..."
err = doShareCmd(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires)
fatalIf(err.Trace(targetURL), "Unable generate URL for sharing.")
}
// ShareMessage container for share messages
type ShareMessage struct {
Expires time.Duration `json:"expire-seconds"`
@@ -110,6 +83,47 @@ func (s ShareMessage) String() string {
return string(shareMessageBytes)
}
func checkShareSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || ctx.Args().First() == "help" || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
}
if len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().First()) == "" {
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
}
// mainShare - is a handler for mc share command
func mainShare(ctx *cli.Context) {
checkShareSyntax(ctx)
console.SetCustomTheme(map[string]*color.Color{
"Share": color.New(color.FgGreen, color.Bold),
})
args := ctx.Args()
config := mustGetMcConfig()
/// get first and last arguments
url := args.First() // url to be shared
// default expiration is 7days
expires := time.Duration(604800) * time.Second
if len(args) == 2 {
var err error
expires, err = time.ParseDuration(args.Last())
fatalIf(probe.NewError(err), "Unable to parse time argument.")
}
targetURL, err := getCanonicalizedURL(url, config.Aliases)
fatalIf(err.Trace(url), "Unable to parse argument ‘"+url+"’.")
// if recursive strip off the "..."
err = doShareCmd(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires)
fatalIf(err.Trace(targetURL), "Unable to generate URL for sharing.")
}
func getNewTargetURL(targetParser *client.URL, name string) string {
match, _ := filepath.Match("*.s3*.amazonaws.com", targetParser.Host)
if match {
@@ -144,11 +158,15 @@ func doShareCmd(targetURL string, recursive bool, expires time.Duration) *probe.
if err != nil {
return err.Trace()
}
console.Println(ShareMessage{Expires: expires / time.Second, PresignedURL: presignedURL}.String())
console.Println(ShareMessage{
Expires: time.Duration(int64(expires.Seconds())) * time.Second,
PresignedURL: presignedURL,
}.String())
}
return nil
}
// this code is necessary since, share only operates on cloud storage URLs not filesystem
func path2Bucket(u *client.URL) (bucketName string) {
pathSplits := strings.SplitN(u.Path, "?", 2)
splits := strings.SplitN(pathSplits[0], string(u.Separator), 3)
-1
View File
@@ -102,5 +102,4 @@ func mainUpdate(ctx *cli.Context) {
return
}
console.Infoln("You are already running the most recent version of ‘mc’.")
return
}