diff --git a/README.md b/README.md
index e4fa9068..16f59ab9 100644
--- a/README.md
+++ b/README.md
@@ -26,6 +26,7 @@ diff list differences in object name, size, and date between two buckets
rm remove objects
event manage object notifications
watch listen for object notification events
+undo undo PUT/DELETE operations
policy manage anonymous access to buckets and objects
tag manage tags for bucket(s) and object(s)
lock manage default bucket object lock configuration
diff --git a/cmd/ls.go b/cmd/ls.go
index 935103ca..53f1eee1 100644
--- a/cmd/ls.go
+++ b/cmd/ls.go
@@ -82,20 +82,25 @@ func (c contentMessage) JSON() string {
return string(jsonMessageBytes)
}
-// get content key
-func getKey(c *ClientContent) string {
+// Use OS separator and adds a trailing separator if it is a dir
+func getOSDependantKey(path string, isDir bool) string {
sep := "/"
// for windows make sure to print in 'windows' specific style.
if runtime.GOOS == "windows" {
- c.URL.Path = strings.Replace(c.URL.Path, "/", "\\", -1)
+ path = strings.Replace(path, "/", "\\", -1)
sep = "\\"
}
- if c.Type.IsDir() && !strings.HasSuffix(c.URL.Path, sep) {
- return fmt.Sprintf("%s%s", c.URL.Path, sep)
+ if isDir && !strings.HasSuffix(path, sep) {
+ return fmt.Sprintf("%s%s", path, sep)
}
- return c.URL.Path
+ return path
+}
+
+// get content key
+func getKey(c *ClientContent) string {
+ return getOSDependantKey(c.URL.Path, c.Type.IsDir())
}
// Generate printable listing from a list of sorted client
@@ -149,8 +154,7 @@ func generateContentMessages(clntURL ClientURL, ctnts []*ClientContent, printAll
return
}
-// Pretty print the list of versions belonging to one object
-func printObjectVersions(clntURL ClientURL, ctntVersions []*ClientContent, printAllVersions bool) {
+func sortObjectVersions(ctntVersions []*ClientContent) {
// Sort versions
sort.Slice(ctntVersions, func(i, j int) bool {
if ctntVersions[i].IsLatest {
@@ -161,7 +165,11 @@ func printObjectVersions(clntURL ClientURL, ctntVersions []*ClientContent, print
}
return ctntVersions[i].Time.After(ctntVersions[j].Time)
})
+}
+// Pretty print the list of versions belonging to one object
+func printObjectVersions(clntURL ClientURL, ctntVersions []*ClientContent, printAllVersions bool) {
+ sortObjectVersions(ctntVersions)
msgs := generateContentMessages(clntURL, ctntVersions, printAllVersions)
for _, msg := range msgs {
printMsg(msg)
diff --git a/cmd/main.go b/cmd/main.go
index 44c99477..d5b03ce4 100644
--- a/cmd/main.go
+++ b/cmd/main.go
@@ -344,6 +344,7 @@ var appCmds = []cli.Command{
encryptCmd,
eventCmd,
watchCmd,
+ undoCmd,
policyCmd,
tagCmd,
replicateCmd,
diff --git a/cmd/undo-main.go b/cmd/undo-main.go
new file mode 100644
index 00000000..ec29118c
--- /dev/null
+++ b/cmd/undo-main.go
@@ -0,0 +1,275 @@
+/*
+ * MinIO Client, (C) 2020 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 (
+ "context"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "strings"
+
+ "github.com/fatih/color"
+ "github.com/minio/cli"
+ json "github.com/minio/mc/pkg/colorjson"
+ "github.com/minio/mc/pkg/probe"
+ "github.com/minio/minio/pkg/console"
+)
+
+var (
+ undoFlags = []cli.Flag{
+ cli.BoolFlag{
+ Name: "recursive, r",
+ Usage: "undo last S3 put/delete operations",
+ },
+ cli.BoolFlag{
+ Name: "force",
+ Usage: "force recursive operation",
+ },
+ cli.IntFlag{
+ Name: "last",
+ Usage: "undo N last changes",
+ Value: 1,
+ },
+ cli.BoolFlag{
+ Name: "dry-run",
+ Usage: "fake an undo operation",
+ },
+ }
+)
+
+var undoCmd = cli.Command{
+ Name: "undo",
+ Usage: "undo PUT/DELETE operations",
+ Action: mainUndo,
+ Before: setGlobalsFromContext,
+ Flags: append(undoFlags, globalFlags...),
+ CustomHelpTemplate: `NAME:
+ {{.HelpName}} - {{.Usage}}
+
+USAGE:
+ {{.HelpName}} [FLAGS] SOURCE [SOURCE...]
+{{if .VisibleFlags}}
+FLAGS:
+ {{range .VisibleFlags}}{{.}}
+ {{end}}{{end}}
+
+EXAMPLES:
+ 1. Undo the last 3 uploads and/or removals of a particular object
+ {{.Prompt}} {{.HelpName}} s3/backups/file.zip --last 3
+
+ 2. Undo the last upload/removal change of all objects under a prefix
+ {{.Prompt}} {{.HelpName}} --recursive --force s3/backups/prefix/
+`,
+}
+
+// undoMessage container for undo message structure.
+type undoMessage struct {
+ Status string `json:"status"`
+ URL string `json:"url,omitempty"`
+ Key string `json:"key,omitempty"`
+ VersionID string `json:"versionId,omitempty"`
+ IsDeleteMarker bool `json:"isDeleteMarker,omitempty"`
+}
+
+// String colorized string message.
+func (c undoMessage) String() string {
+ var msg string
+ fmt.Print(color.GreenString("\u2713 "))
+ yellow := color.New(color.FgYellow).SprintFunc()
+ if c.IsDeleteMarker {
+ msg += "Last " + color.RedString("delete") + " of `" + yellow(c.Key) + "` is reverted"
+ } else {
+ msg += "Last " + color.BlueString("upload") + " of `" + yellow(c.Key) + "` (vid=" + c.VersionID + ") is reverted"
+ }
+ msg += "."
+ return msg
+}
+
+// JSON jsonified content message.
+func (c undoMessage) JSON() string {
+ c.Status = "success"
+ jsonMessageBytes, e := json.MarshalIndent(c, "", " ")
+ fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
+
+ return string(jsonMessageBytes)
+}
+
+// parseUndoSyntax performs command-line input validation for cat command.
+func parseUndoSyntax(ctx *cli.Context) (targetAliasedURL string, last int, recursive, dryRun bool) {
+ targetAliasedURL = ctx.Args().Get(0)
+ if targetAliasedURL == "" {
+ fatalIf(errInvalidArgument().Trace(), "The argument should not be empty")
+ }
+
+ last = ctx.Int("last")
+ if last < 1 {
+ fatalIf(errInvalidArgument().Trace(), "--last value should be a positive integer")
+ }
+
+ recursive = ctx.Bool("recursive")
+ force := ctx.Bool("force")
+ if recursive && !force {
+ fatalIf(errInvalidArgument().Trace(), "This is a dangerous operation, you need to provide --force flag as well")
+ }
+
+ dryRun = ctx.Bool("dry-run")
+ return
+}
+
+func undoLastNOperations(ctx context.Context, clnt Client, objectVersions []*ClientContent, last int, dryRun bool) (exitErr error) {
+ if last == 0 {
+ return
+ }
+
+ sortObjectVersions(objectVersions)
+
+ if len(objectVersions) > last {
+ objectVersions = objectVersions[:last]
+ }
+
+ contentCh := make(chan *ClientContent)
+ errorCh := clnt.Remove(ctx, false, false, false, contentCh)
+
+ prefixPath := clnt.GetURL().Path
+ prefixPath = filepath.ToSlash(prefixPath)
+ if !strings.HasSuffix(prefixPath, "/") {
+ prefixPath = prefixPath[:strings.LastIndex(prefixPath, "/")+1]
+ }
+ prefixPath = strings.TrimPrefix(prefixPath, "./")
+
+ go func() {
+ for _, objectVersion := range objectVersions {
+ if !dryRun {
+ contentCh <- objectVersion
+ }
+
+ // Convert any os specific delimiters to "/".
+ contentURL := filepath.ToSlash(objectVersion.URL.Path)
+ // Trim prefix path from the content path.
+ keyName := strings.TrimPrefix(contentURL, prefixPath)
+
+ printMsg(undoMessage{
+ Status: "success",
+ Key: getOSDependantKey(keyName, objectVersion.Type.IsDir()),
+ URL: objectVersion.URL.String(),
+ VersionID: objectVersion.VersionID,
+ IsDeleteMarker: objectVersion.IsDeleteMarker,
+ })
+
+ }
+ close(contentCh)
+ }()
+
+ for err := range errorCh {
+ if err != nil {
+ errorIf(err.Trace(), "Unable to undo")
+ exitErr = exitStatus(globalErrorExitStatus) // Set the exit status.
+ }
+ }
+
+ return
+}
+
+func undoURL(ctx context.Context, aliasedURL string, last int, recursive, dryRun bool) (exitErr error) {
+ clnt, err := newClient(aliasedURL)
+ fatalIf(err.Trace(aliasedURL), "Unable to initialize target `"+aliasedURL+"`.")
+
+ alias, _, _ := mustExpandAlias(aliasedURL)
+
+ var (
+ lastObjectPath string
+ perObjectVersions []*ClientContent
+ atLeastOneUndoApplied bool
+ )
+
+ for content := range clnt.List(ctx, ListOptions{
+ isRecursive: recursive,
+ withOlderVersions: true,
+ withDeleteMarkers: true,
+ showDir: DirNone,
+ }) {
+ if content.Err != nil {
+ fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
+ }
+
+ if content.StorageClass == s3StorageClassGlacier {
+ continue
+ }
+
+ if !recursive {
+ if alias+getKey(content) != getStandardizedURL(aliasedURL) {
+ break
+ }
+ }
+
+ if lastObjectPath != content.URL.Path {
+ // Print any object in the current list before reinitializing it
+ exitErr = undoLastNOperations(ctx, clnt, perObjectVersions, last, dryRun)
+ lastObjectPath = content.URL.Path
+ perObjectVersions = []*ClientContent{}
+ }
+
+ perObjectVersions = append(perObjectVersions, content)
+ atLeastOneUndoApplied = true
+ }
+
+ // Undo the remaining versions found if any
+ exitErr = undoLastNOperations(ctx, clnt, perObjectVersions, last, dryRun)
+
+ if !atLeastOneUndoApplied {
+ errorIf(errDummy().Trace(clnt.GetURL().String()), "Unable to find any object version to undo.")
+ exitErr = exitStatus(globalErrorExitStatus) // Set the exit status.
+ }
+
+ return
+}
+
+func checkIfBucketIsVersioned(ctx context.Context, aliasedURL string) (versioned bool) {
+ client, err := newClient(aliasedURL)
+ fatalIf(err, "Unable to parse `%s`", aliasedURL)
+
+ versioningConfig, err := client.GetVersion(ctx)
+ if err != nil {
+ if errors.As(err.ToGoError(), &APINotImplemented{}) {
+ return false
+ }
+ fatalIf(err.Trace(), "Unable to get bucket versioning info")
+ }
+
+ if versioningConfig.Status == "Enabled" {
+ return true
+ }
+ return false
+}
+
+// mainUndo is the main entry point for undo command.
+func mainUndo(cliCtx *cli.Context) error {
+ ctx, cancelCat := context.WithCancel(globalContext)
+ defer cancelCat()
+
+ console.SetColor("Success", color.New(color.FgGreen, color.Bold))
+
+ // check 'undo' cli arguments.
+ targetAliasedURL, last, recursive, dryRun := parseUndoSyntax(cliCtx)
+
+ if !checkIfBucketIsVersioned(ctx, targetAliasedURL) {
+ fatalIf(errDummy().Trace(), "Undo command works only with S3 versioned-enabled buckets.")
+ }
+
+ return undoURL(ctx, targetAliasedURL, last, recursive, dryRun)
+}
diff --git a/docs/minio-client-complete-guide.md b/docs/minio-client-complete-guide.md
index 88870bfb..af6ffeaa 100644
--- a/docs/minio-client-complete-guide.md
+++ b/docs/minio-client-complete-guide.md
@@ -29,6 +29,7 @@ ilm manage bucket lifecycle
encrypt manage bucket encryption config
event manage object notifications
watch listen for object notification events
+undo undo PUT/DELETE operations
policy manage anonymous access to buckets and objects
tag manage tags for bucket(s) and object(s)
replicate configure server side bucket replication
@@ -304,10 +305,10 @@ mc version RELEASE.2020-04-25T00-43-23Z
|:----------------------------------------------------------------------------------------|:--------------------------------------------------------------------|:-----------------------------------------------------------|----------------------------------------------------|
| [**ls** - list buckets and objects](#ls) | [**tree** - list buckets and objects in a tree format](#tree) | [**mb** - make a bucket](#mb) | [**cat** - display object contents](#cat) |
| [**cp** - copy objects](#cp) | [**rb** - remove a bucket](#rb) | [**pipe** - stream STDIN to an object](#pipe) | [**version** - manage bucket version](#version) |
-| [**share** - generate URL for temporary access to an object](#share) | [**rm** - remove objects](#rm) | [**find** - find files and objects](#find) | |
-| [**diff** - list differences in object name, size, and date between two buckets](#diff) | [**mirror** - synchronize object(s) to a remote site](#mirror) | [**ilm** - manage bucket lifecycle policies](#ilm) | [**replicate** - manage bucket server side replication](#replicate) |
-| [**alias** - manage aliases](#alias) | [**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) | [**encrypt** - manage bucket encryption](#encrypt) |
+| [**share** - generate URL for temporary access to an object](#share) | [**rm** - remove objects](#rm) | [**find** - find files and objects](#find) | [**undo** - undo PUT/DELETE operations](#undo) |
+| [**diff** - list differences in object name, size, and date between two buckets](#diff) | [**mirror** - synchronize object(s) to a remote site](#mirror) | [**ilm** - manage bucket lifecycle policies](#ilm) | [**replicate** - manage bucket server side replication](#replicate) |
+| [**alias** - manage aliases](#alias) | [**policy** - set public policy on bucket or prefix](#policy) | [**event** - manage events on your buckets](#event) | [**encrypt** - manage bucket encryption](#encrypt) |
+| [**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) | [**lock** - manage default bucket object lock configuration](#lock) | [**retention** - set retention for object(s)](#retention) | |
| [**mv** - move objects](#mv) | [**sql** - run sql queries on objects](#sql) | [**legalhold** - set legal hold for object(s)](#legalhold) | |
@@ -1561,6 +1562,33 @@ mc version suspend myminio/mybucket
myminio/mybucket versioning is suspended
```
+
+### Command `undo`
+`undo` reverts latest PUT/DELETE operations
+
+```
+NAME:
+ mc undo - undo PUT/DELETE operations
+
+USAGE:
+ mc undo [FLAGS] SOURCE
+
+FLAGS:
+ --recursive, -r undo last S3 put/delete operations
+ --force force recursive operation
+ --last value undo N last changes (default: 1)
+ --dry-run fake an undo operation
+ --help, -h show help
+```
+
+*Example: Undo the last 3 uploads and/or removals of a particular object*
+```
+mc undo s3/backups/file.zip --last 3
+✓ Last delete of `CREDITS` is reverted.
+✓ Last upload of `CREDITS` (vid=mj2juHIoyvU94s8kIim5H.Z9L0QO50wO) is reverted.
+✓ Last upload of `CREDITS` (vid=przFKd1iWC7ts_8FNoIvLae8NH_BAi_X) is reverted.
+```
+
### Command `encrypt`
`encrypt` manages bucket encryption config