|
| 1 | +package v3ctl |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "github.com/nuclio/errors" |
| 7 | + "github.com/spf13/cobra" |
| 8 | + v3io "github.com/v3io/v3io-go/pkg/dataplane" |
| 9 | +) |
| 10 | + |
| 11 | +type lsCommandeer struct { |
| 12 | + rootCommandeer *RootCommandeer |
| 13 | + cmd *cobra.Command |
| 14 | + withAttributes bool |
| 15 | +} |
| 16 | + |
| 17 | +func newLsCommandeer(rootCommandeer *RootCommandeer) *lsCommandeer { |
| 18 | + commandeer := &lsCommandeer{ |
| 19 | + rootCommandeer: rootCommandeer, |
| 20 | + } |
| 21 | + |
| 22 | + cmd := &cobra.Command{ |
| 23 | + Use: "ls <dir> [-l]", |
| 24 | + Short: "List files", |
| 25 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 26 | + |
| 27 | + if len(args) != 1 { |
| 28 | + return errors.New("ls requires a directory") |
| 29 | + } |
| 30 | + |
| 31 | + dir := args[0] |
| 32 | + |
| 33 | + // initialize root |
| 34 | + if err := commandeer.rootCommandeer.initialize(); err != nil { |
| 35 | + return errors.Wrap(err, "Failed to initialize root") |
| 36 | + } |
| 37 | + |
| 38 | + input := v3io.GetContainerContentsInput{Path: dir, GetAllAttributes: commandeer.withAttributes} |
| 39 | + for { |
| 40 | + res, err := rootCommandeer.container.GetContainerContentsSync(&input) |
| 41 | + if err != nil { |
| 42 | + return err |
| 43 | + } |
| 44 | + out := res.Output.(*v3io.GetContainerContentsOutput) |
| 45 | + err = printEntries(out.CommonPrefixes, out.Contents, commandeer.withAttributes) |
| 46 | + if err != nil { |
| 47 | + return err |
| 48 | + } |
| 49 | + if !out.IsTruncated { |
| 50 | + break |
| 51 | + } |
| 52 | + input.Marker = out.NextMarker |
| 53 | + } |
| 54 | + |
| 55 | + return nil |
| 56 | + }, |
| 57 | + } |
| 58 | + |
| 59 | + cmd.Flags().BoolVarP(&commandeer.withAttributes, "with-attributes", "l", false, "Show attributes") |
| 60 | + |
| 61 | + commandeer.cmd = cmd |
| 62 | + |
| 63 | + return commandeer |
| 64 | +} |
| 65 | + |
| 66 | +func printEntries(commonPrefixes []v3io.CommonPrefix, contents []v3io.Content, withDetail bool) error { |
| 67 | + if withDetail { |
| 68 | + for _, commonPrefix := range commonPrefixes { |
| 69 | + line, err := json.Marshal(commonPrefix) |
| 70 | + if err != nil { |
| 71 | + return errors.Wrapf(err, "failed to marshal common prefix %s", commonPrefix.Prefix) |
| 72 | + } |
| 73 | + fmt.Printf("%s\n", line) |
| 74 | + } |
| 75 | + for _, content := range contents { |
| 76 | + line, err := json.Marshal(content) |
| 77 | + if err != nil { |
| 78 | + return errors.Wrapf(err, "failed to marshal content %s", content.Key) |
| 79 | + } |
| 80 | + fmt.Printf("%s\n", line) |
| 81 | + } |
| 82 | + } else { |
| 83 | + for _, commonPrefix := range commonPrefixes { |
| 84 | + fmt.Println(commonPrefix.Prefix) |
| 85 | + } |
| 86 | + for _, content := range contents { |
| 87 | + fmt.Println(content.Key) |
| 88 | + } |
| 89 | + } |
| 90 | + return nil |
| 91 | +} |
0 commit comments