Add tree listing (#2804)

This commit is contained in:
Praveen raj Mani
2019-07-17 22:23:02 -07:00
committed by Harshavardhana
parent 6200a34522
commit bdcb9dcb2f
4 changed files with 337 additions and 10 deletions
+1
View File
@@ -156,6 +156,7 @@ var completeCmds = map[string]complete.Predictor{
"/stat": complete.PredictOr(s3Completer, fsCompleter),
"/watch": complete.PredictOr(s3Completer, fsCompleter),
"/policy": complete.PredictOr(s3Completer, fsCompleter),
"/tree": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
"/mb": aliasCompleter,
"/sql": s3Completer,
+1
View File
@@ -330,6 +330,7 @@ var appCmds = []cli.Command{
configCmd,
updateCmd,
versionCmd,
treeCmd,
}
func registerApp(name string) *cli.App {
+295
View File
@@ -0,0 +1,295 @@
/*
* 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 (
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
const (
treeEntry = "├─ "
treeLastEntry = "└─ "
treeNext = "│"
treeLevel = " "
)
// Structured message depending on the type of console.
type treeMessage struct {
Entry string
IsDir bool
BranchString string
}
// Colorized message for console printing.
func (t treeMessage) String() string {
entryType := "File"
if t.IsDir {
entryType = "Dir"
}
return fmt.Sprintf("%s%s", t.BranchString, console.Colorize(entryType, t.Entry))
}
// JSON'ified message for scripting.
// Does No-op. JSON requests are redirected to `ls -r --json`
func (t treeMessage) JSON() string {
fatalIf(probe.NewError(errors.New("JSON() should never be called here")), "Unable to list in tree format. Please report this issue at https://github.com/minio/mc/issues")
return ""
}
var treeFlags = []cli.Flag{
cli.BoolFlag{
Name: "files, f",
Usage: "includes files in tree",
},
cli.IntFlag{
Name: "depth, d",
Usage: "sets the depth threshold",
},
}
// trees files and folders.
var treeCmd = cli.Command{
Name: "tree",
Usage: "list buckets and objects in a tree format",
Action: mainTree,
Before: setGlobalsFromContext,
Flags: append(treeFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET [TARGET ...]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List all buckets on Amazon S3 cloud storage in a tree format..
$ {{.HelpName}} s3
2. List all buckets in "mybucket" on Amazon S3 cloud storage in a tree format.
$ {{.HelpName}} s3/mybucket/
3. List all buckets in "mybucket" on Amazon S3 cloud storage hosted on Microsoft Windows in a tree format.
$ {{.HelpName}} s3\mybucket\
4. List all buckets and objects in "mybucket" on Amazon S3 cloud storage in a tree format.
$ {{.HelpName}} -f myminio/mybucket/
5. Set the depth of the tree for listing.
$ {{.HelpName}} -d 2 myminio/mybucket/
6. List all the directories irrespective to the depth.
$ {{.HelpName}} myminio/mybucket/
`,
}
// checkTreeSyntax - validate all the passed arguments
func checkTreeSyntax(ctx *cli.Context) {
args := ctx.Args()
var depth = -1
if ctx.IsSet("depth") {
depth = ctx.Int("depth")
if depth == -1 {
depth = 0
}
}
if depth != -1 && depth <= 0 {
fatalIf(errInvalidArgument().Trace(args...), "depth should have a value greater than 0")
}
if (args.Present()) && len(args) == 0 {
return
}
for _, url := range args {
if !isURLPrefixExists(url, false) {
fatalIf(probe.NewError(errors.New("See 'mc tree -h' for help")),
"'"+url+"' is not a valid 'alias[/bucket-name ...]'")
}
}
}
// doTree - list all entities inside a folder in a tree format.
func doTree(url string, level int, leaf bool, branchString string, depth int, includeFiles bool) error {
targetAlias, targetURL, _ := mustExpandAlias(url)
if !strings.HasSuffix(targetURL, "/") {
targetURL += "/"
}
clnt, err := newClientFromAlias(targetAlias, targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
prefixPath := clnt.GetURL().Path
separator := string(clnt.GetURL().Separator)
if !strings.HasSuffix(prefixPath, separator) {
prefixPath = filepath.Dir(prefixPath) + "/"
}
bucketNameShowed := false
var prev *clientContent
show := func(end bool) error {
currbranchString := branchString
if level == 1 && !bucketNameShowed {
bucketNameShowed = true
printMsg(treeMessage{
Entry: url,
IsDir: true,
BranchString: branchString,
})
}
isLevelClosed := strings.HasSuffix(currbranchString, treeLastEntry)
if isLevelClosed {
currbranchString = strings.TrimSuffix(currbranchString, treeLastEntry)
} else {
currbranchString = strings.TrimSuffix(currbranchString, treeEntry)
}
if level != 1 {
if isLevelClosed {
currbranchString += " " + treeLevel
} else {
currbranchString += treeNext + treeLevel
}
}
if end {
currbranchString += treeLastEntry
} else {
currbranchString += treeEntry
}
// Convert any os specific delimiters to "/".
contentURL := filepath.ToSlash(prev.URL.Path)
prefixPath = filepath.ToSlash(prefixPath)
// Trim prefix of current working dir
prefixPath = strings.TrimPrefix(prefixPath, "."+separator)
if prev.Type.IsDir() {
printMsg(treeMessage{
Entry: strings.TrimSuffix(strings.TrimPrefix(contentURL, prefixPath), "/"),
IsDir: true,
BranchString: currbranchString,
})
} else {
printMsg(treeMessage{
Entry: strings.TrimPrefix(contentURL, prefixPath),
IsDir: false,
BranchString: currbranchString,
})
}
if prev.Type.IsDir() {
url := ""
if targetAlias != "" {
url = targetAlias + "/" + contentURL
} else {
url = contentURL
}
if depth == -1 || level <= depth {
if err := doTree(url, level+1, end, currbranchString, depth, includeFiles); err != nil {
return err
}
}
}
return nil
}
for content := range clnt.List(false, false, DirNone) {
if !includeFiles && !content.Type.IsDir() {
continue
}
if content.Err != nil {
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to tree.")
continue
}
if prev != nil {
if err := show(false); err != nil {
return err
}
}
prev = content
}
if prev != nil {
if err := show(true); err != nil {
return err
}
}
return nil
}
// mainTree - is a handler for mc tree command
func mainTree(ctx *cli.Context) error {
// check 'tree' cli arguments.
checkTreeSyntax(ctx)
console.SetColor("File", color.New(color.Bold))
console.SetColor("Dir", color.New(color.FgCyan, color.Bold))
args := ctx.Args()
// mimic operating system tool behavior.
if !ctx.Args().Present() {
args = []string{"."}
}
includeFiles := ctx.Bool("files")
depth := -1
if ctx.IsSet("depth") {
depth = ctx.Int("depth")
}
var cErr error
for _, targetURL := range args {
if !globalJSON {
if e := doTree(targetURL, 1, false, "", depth, includeFiles); e != nil {
cErr = e
}
} else {
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
if !strings.HasSuffix(targetURL, "/") {
targetURL += "/"
}
clnt, err := newClientFromAlias(targetAlias, targetURL)
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
if e := doList(clnt, true, false); e != nil {
cErr = e
}
}
}
return cErr
}
+40 -10
View File
@@ -4,6 +4,7 @@ MinIO Client (mc) provides a modern alternative to UNIX commands like ls, cat, c
```
ls list buckets and objects
tree list buckets and objects in a tree format
mb make a bucket
rb remove a bucket
cat display object contents
@@ -183,6 +184,7 @@ alias cat='mc cat'
alias mkdir='mc mb'
alias pipe='mc pipe'
alias find='mc find'
alias tree='mc tree'
```
## 6. Global Options
@@ -251,7 +253,7 @@ Skip SSL certificate verification.
| | | |
|:---|:---|:---|
|[**ls** - List buckets and objects](#ls) |[**mb** - Make a bucket](#mb) | [**cat** - Concatenate an object](#cat) |
|[**ls** - List buckets and objects](#ls) |[**tree** - List buckets and objects in a tree format](#tree) |[**mb** - Make a bucket](#mb) | [**cat** - Concatenate an object](#cat) |
|[**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) |
@@ -285,6 +287,34 @@ mc ls play
[2016-04-08 20:58:18 IST] 0B mybucket/
```
<a name="tree"></a>
### Command `tree` - List buckets and directories in a tree format
`tree` command lists buckets and directories in a tree format. Use `--files` flag to include files/objects in listing.
```sh
USAGE:
mc tree [FLAGS] TARGET [TARGET ...]
FLAGS:
--help, -h show help
--files, -f include files in tree
--depth, -d set the maximum depth of the tree
```
_Example: List all buckets on play/test-bucket in a tree format._
```sh
mc tree play/test-bucket
play/test-bucket/
├─ dir_a
├─ dir_b
│ └─ dir_bb
└─ dir_x
└─ dir_xx
```
<a name="mb"></a>
### Command `mb` - Make a Bucket
`mb` command creates a new bucket on an object storage. On a filesystem, it behaves like `mkdir -p` command. Bucket is equivalent of a drive or mount point in filesystems and should not be treated as folders. MinIO does not place any limits on the number of buckets created per user.
@@ -396,9 +426,9 @@ ENVIRONMENT VARIABLES:
MC_ENCRYPT_KEY: list of comma delimited prefix=secret values
INPUT SERIALIZATION
--csv-input or --json-input can be used to specify input data format. Format is
--csv-input or --json-input can be used to specify input data format. Format is
specified by a string with pattern "key=value,..." for valid key(s).
DATA FORMAT:
csv: Use --csv-input flag
Valid keys:
@@ -409,12 +439,12 @@ INPUT SERIALIZATION
FileHeader (fh)
Comments (cc)
QuotedRecordDelimiter (qrd)
json: Use --json-input flag
Valid keys:
Type
Type
parquet: If object name ends in .parquet, this is automatically interpreted.
OUTPUT SERIALIZATION
--csv-output or --json-output can be used to specify output data format. Format is
specified by a string with pattern "key=value,..." for valid key(s).
@@ -426,11 +456,11 @@ OUTPUT SERIALIZATION
QuoteChar (qc)
QuoteEscChar (qec)
QuoteFields (qf)
json: Use --json-output flag
Valid keys:
RecordDelimiter (rd)
RecordDelimiter (rd)
COMPRESSION TYPE
--compression specifies if the queried object is compressed.
Valid values: NONE | GZIP | BZIP2
@@ -810,7 +840,7 @@ FLAGS:
--debug Enable debug output.
--insecure Disable SSL certificate verification.
--help, -h Show help.
LEGEND:
< - object is only in source.
> - object is only in destination.