diff --git a/README.md b/README.md
index 08102fc8..88ffe359 100644
--- a/README.md
+++ b/README.md
@@ -6,6 +6,7 @@ Minio Client (mc) provides a modern alternative to UNIX commands like ls, cat, c
```
ls list buckets and objects
mb make a bucket
+rb remove a bucket
cat display object contents
head display first 'n' lines of an object
pipe stream STDIN to an object
diff --git a/cmd/client-fs.go b/cmd/client-fs.go
index 9b25ff36..5825b4fa 100644
--- a/cmd/client-fs.go
+++ b/cmd/client-fs.go
@@ -412,7 +412,7 @@ func (f *fsClient) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
}
// Remove - remove entry read from clientContent channel.
-func (f *fsClient) Remove(isIncomplete bool, contentCh <-chan *clientContent) <-chan *probe.Error {
+func (f *fsClient) Remove(isIncomplete, isRemoveBucket bool, contentCh <-chan *clientContent) <-chan *probe.Error {
errorCh := make(chan *probe.Error)
// Goroutine reads from contentCh and removes the entry in content.
diff --git a/cmd/client-s3.go b/cmd/client-s3.go
index 28eb8ee2..f1be59a7 100644
--- a/cmd/client-s3.go
+++ b/cmd/client-s3.go
@@ -36,7 +36,7 @@ import (
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/mc/pkg/probe"
- "github.com/minio/minio-go"
+ minio "github.com/minio/minio-go"
"github.com/minio/minio-go/pkg/credentials"
"github.com/minio/minio-go/pkg/encrypt"
"github.com/minio/minio-go/pkg/policy"
@@ -779,7 +779,7 @@ func (c *s3Client) removeIncompleteObjects(bucket string, objectsCh <-chan strin
}
// Remove - remove object or bucket(s).
-func (c *s3Client) Remove(isIncomplete bool, contentCh <-chan *clientContent) <-chan *probe.Error {
+func (c *s3Client) Remove(isIncomplete, isRemoveBucket bool, contentCh <-chan *clientContent) <-chan *probe.Error {
errorCh := make(chan *probe.Error)
prevBucket := ""
@@ -787,8 +787,6 @@ func (c *s3Client) Remove(isIncomplete bool, contentCh <-chan *clientContent) <-
var objectsCh chan string
var statusCh <-chan minio.RemoveObjectError
- isRemoveBucket := false
-
go func() {
defer close(errorCh)
for content := range contentCh {
@@ -819,7 +817,6 @@ func (c *s3Client) Remove(isIncomplete bool, contentCh <-chan *clientContent) <-
}
}
// Re-init objectsCh for next bucket
- isRemoveBucket = false
objectsCh = make(chan string)
if isIncomplete {
statusCh = c.removeIncompleteObjects(bucket, objectsCh)
@@ -844,7 +841,6 @@ func (c *s3Client) Remove(isIncomplete bool, contentCh <-chan *clientContent) <-
}
} else {
// end of bucket - close the objectsCh
- isRemoveBucket = true
if objectsCh != nil {
close(objectsCh)
}
diff --git a/cmd/client.go b/cmd/client.go
index a5fbefdf..0f05aa9f 100644
--- a/cmd/client.go
+++ b/cmd/client.go
@@ -74,7 +74,7 @@ type Client interface {
Watch(params watchParams) (*watchObject, *probe.Error)
// Delete operations
- Remove(isIncomplete bool, contentCh <-chan *clientContent) (errorCh <-chan *probe.Error)
+ Remove(isIncomplete, isRemoveBucket bool, contentCh <-chan *clientContent) (errorCh <-chan *probe.Error)
// GetURL returns back internal url
GetURL() clientURL
diff --git a/cmd/main.go b/cmd/main.go
index 6b23cb3c..f2040c4e 100644
--- a/cmd/main.go
+++ b/cmd/main.go
@@ -288,6 +288,7 @@ func checkUpdate(ctx *cli.Context) {
var appCmds = []cli.Command{
lsCmd,
mbCmd,
+ rbCmd,
catCmd,
headCmd,
pipeCmd,
diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go
index 52076e4a..a9ed3a3a 100644
--- a/cmd/mirror-main.go
+++ b/cmd/mirror-main.go
@@ -232,8 +232,8 @@ func (mj *mirrorJob) doRemove(sURLs URLs) URLs {
contentCh := make(chan *clientContent, 1)
contentCh <- &clientContent{URL: *newClientURL(sURLs.TargetContent.URL.Path)}
close(contentCh)
-
- errorCh := clnt.Remove(false, contentCh)
+ isRemoveBucket := false
+ errorCh := clnt.Remove(false, isRemoveBucket, contentCh)
for pErr := range errorCh {
if pErr != nil {
switch pErr.ToGoError().(type) {
diff --git a/cmd/rb-main.go b/cmd/rb-main.go
new file mode 100644
index 00000000..3ed93f47
--- /dev/null
+++ b/cmd/rb-main.go
@@ -0,0 +1,210 @@
+/*
+ * Minio Client (C) 2019 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 cmd
+
+import (
+ "encoding/json"
+ "path/filepath"
+
+ "github.com/fatih/color"
+ "github.com/minio/cli"
+ "github.com/minio/mc/pkg/console"
+ "github.com/minio/mc/pkg/probe"
+)
+
+var (
+ rbFlags = []cli.Flag{
+ cli.BoolFlag{
+ Name: "force",
+ Usage: "allow a recursive remove operation",
+ },
+ }
+)
+
+// remove a bucket.
+var rbCmd = cli.Command{
+ Name: "rb",
+ Usage: "remove a bucket",
+ Action: mainRemoveBucket,
+ Before: setGlobalsFromContext,
+ Flags: append(rbFlags, globalFlags...),
+ CustomHelpTemplate: `NAME:
+ {{.HelpName}} - {{.Usage}}
+
+USAGE:
+ {{.HelpName}} [FLAGS] TARGET [TARGET...]
+{{if .VisibleFlags}}
+FLAGS:
+ {{range .VisibleFlags}}{{.}}
+ {{end}}{{end}}
+EXAMPLES:
+ 1. Remove an empty bucket on Amazon S3 cloud storage
+ $ {{.HelpName}} s3/mybucket
+
+ 2. Remove a directory hierarchy.
+ $ {{.HelpName}} /tmp/this/new/dir1
+
+ 3. Remove bucket 'jazz-songs' and all its contents
+ $ {{.HelpName}} --force s3/jazz-songs
+
+ 4. Remove all buckets and objects recursively from S3 host
+ $ {{.HelpName}} --force s3
+`,
+}
+
+// removeBucketMessage is container for delete bucket success and failure messages.
+type removeBucketMessage struct {
+ Status string `json:"status"`
+ Bucket string `json:"bucket"`
+}
+
+// String colorized delete bucket message.
+func (s removeBucketMessage) String() string {
+ return console.Colorize("RemoveBucket", "Bucket removed successfully `"+s.Bucket+"`.")
+}
+
+// JSON jsonified remove bucket message.
+func (s removeBucketMessage) JSON() string {
+ removeBucketJSONBytes, e := json.Marshal(s)
+ fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
+
+ return string(removeBucketJSONBytes)
+}
+
+// Validate command line arguments.
+func checkRbSyntax(ctx *cli.Context) {
+ if !ctx.Args().Present() {
+ exitCode := 1
+ cli.ShowCommandHelpAndExit(ctx, "rb", exitCode)
+ }
+}
+
+// deletes a bucket and all its contents
+func deleteBucket(url string) error {
+ targetAlias, targetURL, _ := mustExpandAlias(url)
+ clnt, pErr := newClientFromAlias(targetAlias, targetURL)
+ if pErr != nil {
+ errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.")
+ return exitStatus(globalErrorExitStatus) // End of journey.
+ }
+ var isIncomplete bool
+ isRemoveBucket := true
+ contentCh := make(chan *clientContent)
+ errorCh := clnt.Remove(isIncomplete, isRemoveBucket, contentCh)
+
+ for content := range clnt.List(true, false, DirLast) {
+ if content.Err != nil {
+ errorIf(content.Err.Trace(url), "Failed to remove `"+url+"`.")
+ switch content.Err.ToGoError().(type) {
+ case PathInsufficientPermission:
+ // Ignore Permission error.
+ continue
+ }
+ close(contentCh)
+ return exitStatus(globalErrorExitStatus)
+ }
+ urlString := content.URL.Path
+
+ sent := false
+ for !sent {
+ select {
+ case contentCh <- content:
+ sent = true
+ case pErr := <-errorCh:
+ errorIf(pErr.Trace(urlString), "Failed to remove `"+urlString+"`.")
+ switch pErr.ToGoError().(type) {
+ case PathInsufficientPermission:
+ // Ignore Permission error.
+ continue
+ }
+ close(contentCh)
+ return exitStatus(globalErrorExitStatus)
+ }
+ }
+ }
+
+ close(contentCh)
+ for pErr := range errorCh {
+ errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.")
+ switch pErr.ToGoError().(type) {
+ case PathInsufficientPermission:
+ // Ignore Permission error.
+ continue
+ }
+ return exitStatus(globalErrorExitStatus)
+ }
+ return nil
+}
+
+// isNamespaceRemoval returns true if alias
+// is not qualified by bucket
+func isNamespaceRemoval(url string) bool {
+ // clean path for aliases like s3/.
+ //Note: UNC path using / works properly in go 1.9.2 even though it breaks the UNC specification.
+ url = filepath.ToSlash(filepath.Clean(url))
+ // namespace removal applies only for non FS. So filter out if passed url represents a directory
+ if !isAliasURLDir(url, nil) {
+ _, path := url2Alias(url)
+ return (path == "")
+ }
+ return false
+}
+
+// mainRemoveBucket is entry point for rb command.
+func mainRemoveBucket(ctx *cli.Context) error {
+ // check 'rb' cli arguments.
+ checkRbSyntax(ctx)
+ // Set command flags from context.
+ isForce := ctx.Bool("force")
+ // Additional command speific theme customization.
+ console.SetColor("RemoveBucket", color.New(color.FgGreen, color.Bold))
+
+ var cErr error
+ for _, targetURL := range ctx.Args() {
+ // Instantiate client for URL.
+ clnt, err := newClient(targetURL)
+ if err != nil {
+ errorIf(err.Trace(targetURL), "Invalid target `"+targetURL+"`.")
+ cErr = exitStatus(globalErrorExitStatus)
+ continue
+ }
+ isEmpty := true
+ for range clnt.List(true, false, DirNone) {
+ isEmpty = false
+ break
+ }
+ // For all recursive operations make sure to check for 'force' flag.
+ if !isForce {
+ if isNamespaceRemoval(targetURL) {
+ fatalIf(errDummy().Trace(),
+ "This operation results in **site-wide** removal of buckets. If you are really sure, retry this command with ‘--force’ flags.")
+ }
+ if !isEmpty {
+ fatalIf(errDummy().Trace(), "`"+targetURL+"` is not empty. Retry this command with ‘--force’ flag if you want to remove `"+targetURL+"` and all its contents")
+ }
+ }
+ e := deleteBucket(targetURL)
+ if e == nil {
+ // Successfully removed a bucket.
+ printMsg(removeBucketMessage{Status: "success", Bucket: targetURL})
+ } else {
+ errorIf(probe.NewError(e), `"+targetURL+"`+"could not be removed.")
+ }
+
+ }
+ return cErr
+}
diff --git a/cmd/rm-main.go b/cmd/rm-main.go
index b4416a07..274c9696 100644
--- a/cmd/rm-main.go
+++ b/cmd/rm-main.go
@@ -47,7 +47,7 @@ var (
},
cli.BoolFlag{
Name: "dangerous",
- Usage: "allow site-wide removal of buckets and objects",
+ Usage: "allow site-wide removal of objects",
},
cli.BoolFlag{
Name: "incomplete, I",
@@ -107,10 +107,10 @@ EXAMPLES:
5. Remove all objects read from STDIN.
$ {{.HelpName}} --force --stdin
- 6. Remove all buckets and objects recursively from S3 host
+ 6. Remove all objects recursively from S3 host
$ {{.HelpName}} --recursive --dangerous s3
- 7. Remove all buckets and objects older than '90' days recursively from host
+ 7. Remove all objects older than '90' days recursively from host
$ {{.HelpName}} --recursive --dangerous --older-than=90 s3
8. Drop all incomplete uploads on 'jazz-songs' bucket.
@@ -168,14 +168,14 @@ func checkRmSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
if (isRecursive || isStdin) && !isForce {
if isNamespaceRemoval {
fatalIf(errDummy().Trace(),
- "This operation results in site-wide removal of buckets and objects. If you are really sure, retry this command with ‘--dangerous’ and ‘--force’ flags.")
+ "This operation results in site-wide removal of objects. If you are really sure, retry this command with ‘--dangerous’ and ‘--force’ flags.")
}
fatalIf(errDummy().Trace(),
"Removal requires --force flag. This operation is *IRREVERSIBLE*. Please review carefully before performing this *DANGEROUS* operation.")
}
if (isRecursive || isStdin) && isNamespaceRemoval && !isDangerous {
fatalIf(errDummy().Trace(),
- "This operation results in site-wide removal of buckets and objects. If you are really sure, retry this command with ‘--dangerous’ and ‘--force’ flags.")
+ "This operation results in site-wide removal of objects. If you are really sure, retry this command with ‘--dangerous’ and ‘--force’ flags.")
}
}
@@ -214,8 +214,8 @@ func removeSingle(url string, isIncomplete bool, isFake bool, olderThan int, new
contentCh := make(chan *clientContent, 1)
contentCh <- &clientContent{URL: *newClientURL(targetURL)}
close(contentCh)
-
- errorCh := clnt.Remove(isIncomplete, contentCh)
+ isRemoveBucket := false
+ errorCh := clnt.Remove(isIncomplete, isRemoveBucket, contentCh)
for pErr := range errorCh {
if pErr != nil {
errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.")
@@ -239,12 +239,12 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, olderThan int,
return exitStatus(globalErrorExitStatus) // End of journey.
}
contentCh := make(chan *clientContent)
- errorCh := clnt.Remove(isIncomplete, contentCh)
+ isRemoveBucket := false
+
+ errorCh := clnt.Remove(isIncomplete, isRemoveBucket, contentCh)
- isEmpty := true
isRecursive := true
- for content := range clnt.List(isRecursive, isIncomplete, DirLast) {
- isEmpty = false
+ for content := range clnt.List(isRecursive, isIncomplete, DirNone) {
if content.Err != nil {
errorIf(content.Err.Trace(url), "Failed to remove `"+url+"` recursively.")
switch content.Err.ToGoError().(type) {
@@ -306,10 +306,6 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, olderThan int,
return exitStatus(globalErrorExitStatus)
}
- // As clnt.List() returns empty, we just send dummy value to behave like non-recursive.
- if isEmpty {
- printMsg(rmMessage{Key: url})
- }
return nil
}
diff --git a/docs/minio-client-complete-guide.md b/docs/minio-client-complete-guide.md
index 46e376e6..8ef32e29 100644
--- a/docs/minio-client-complete-guide.md
+++ b/docs/minio-client-complete-guide.md
@@ -5,6 +5,7 @@ Minio Client (mc) provides a modern alternative to UNIX commands like ls, cat, c
```sh
ls list buckets and objects
mb make a bucket
+rb remove a bucket
cat display object contents
head display first 'n' lines of an object
pipe stream STDIN to an object
@@ -250,12 +251,13 @@ Skip SSL certificate verification.
| | | |
|:---|:---|:---|
|[**ls** - List buckets and objects](#ls) |[**mb** - Make a bucket](#mb) | [**cat** - Concatenate an object](#cat) |
-|[**cp** - Copy objects](#cp) | [**rm** - Remove objects](#rm) | [**pipe** - Pipe to an object](#pipe) |
-| [**share** - Share access](#share) |[**mirror** - Mirror buckets](#mirror) | [**find** - Find files and objects](#find) |
-| [**diff** - Diff buckets](#diff) |[**policy** - Set public policy on bucket or prefix](#policy) |[**session** - Manage saved sessions](#session) |
-| [**config** - Manage config file](#config) | [**watch** - Watch for events](#watch) | [**event** - Manage events on your buckets](#event) |
-| [**update** - Manage software updates](#update) | [**version** - Show version](#version) | [**stat** - Stat contents of objects and folders](#stat) |
-| [**head** - Display first 'n' lines of an object](#head) | [**sql** - Run sql queries on objects](#sql) | |
+|[**cp** - Copy objects](#cp) |[**rb** - Remove a bucket](#rb) | [**pipe** - Pipe to an object](#pipe) |
+| [**share** - Share access](#share) | [**rm** - Remove objects](#rm) | [**find** - Find files and objects](#find) |
+| [**diff** - Diff buckets](#diff) |[**mirror** - Mirror buckets](#mirror)|[**session** - Manage saved sessions](#session) |
+| [**config** - Manage config file](#config) | [**policy** - Set public policy on bucket or prefix](#policy) | [**event** - Manage events on your buckets](#event) |
+| [**update** - Manage software updates](#update) | [**watch** - Watch for events](#watch) | [**stat** - Stat contents of objects and folders](#stat) |
+| [**head** - Display first 'n' lines of an object](#head) | [**version** - Show version](#version) | |
+| | [**sql** - Run sql queries on objects](#sql) | |
### Command `ls` - List Objects
@@ -314,6 +316,30 @@ mc mb s3/mybucket --region=us-west-1
Bucket created successfully ‘s3/mybucket’.
```
+
+### Command `rb` - Remove a Bucket
+`rb` command removes a bucket and all its contents on an object storage. On a filesystem, it behaves like `rmdir` command.
+
+Note that when a bucket is removed all policies associated with the bucket will also be removed. If you would like to just
+empty the objects in a bucket use `rm` command
+
+```sh
+USAGE:
+ mc rb [FLAGS] TARGET [TARGET...]
+
+FLAGS:
+ --help, -h show help
+
+```
+
+*Example: Remove a bucket named "mybucket" on https://play.minio.io:9000.*
+
+
+```sh
+mc rb play/mybucket --recursive --force
+Bucket removed successfully ‘play/mybucket’.
+```
+
### Command `cat` - Concatenate Objects
`cat` command concatenates contents of a file or object to another. You may also use it to simply display the contents to stdout
@@ -490,8 +516,8 @@ encryptedobject: 14 B / 14 B ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
Notice that two different aliases myminio1 and myminio2 are used for the same endpoint to provide the old secretkey and the newly rotated key.
-### Command `rm` - Remove Buckets and Objects
-Use `rm` command to remove file or bucket
+### Command `rm` - Remove Objects
+Use `rm` command to remove file or object
```sh
USAGE:
@@ -500,7 +526,7 @@ USAGE:
FLAGS:
--recursive, -r remove recursively
--force allow a recursive remove operation
- --dangerous allow site-wide removal of buckets and objects
+ --dangerous allow site-wide removal of objects
--incomplete, -I remove incomplete uploads
--fake perform a fake remove operation
--stdin read object names from STDIN
@@ -526,13 +552,12 @@ mc rm --encrypt-key "play/mybucket=32byteslongsecretkeymustbegiven1" play/mybuck
Removing `play/mybucket/myobject.txt`.
```
-*Example: Recursively remove a bucket and all its contents. Since this is a dangerous operation, you must explicitly pass `--force` option.*
+*Example: Recursively remove a bucket's contents. Since this is a dangerous operation, you must explicitly pass `--force` option.*
```sh
mc rm --recursive --force play/mybucket
Removing `play/mybucket/newfile.txt`.
Removing `play/mybucket/otherobject.txt`.
-Removing `play/mybucket`.
```
*Example: Remove all uploaded incomplete files for an object.*