Skip to content

Commit

Permalink
Merge pull request #10 from owlinux1000/add_showing_filesize_option
Browse files Browse the repository at this point in the history
Add showing file size option (Close #5)
  • Loading branch information
owlinux1000 authored Oct 1, 2023
2 parents bcac69f + 86d31aa commit 1ca3229
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 2 deletions.
3 changes: 3 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,10 @@ var rootCmd = &cobra.Command{
}

withColorized, _ := cmd.Flags().GetBool("no-color")
withSize, _ := cmd.Flags().GetBool("filesize")
option := internal.PrintOption{
WithColorized: !withColorized,
WithSize: withSize,
}
gcsTree, err := internal.NewGCSTree(ctx, client, bucket, &option)
if err != nil {
Expand All @@ -60,4 +62,5 @@ func Execute() {
func init() {
rootCmd.Flags().BoolP("version", "v", false, "show the gcstree version")
rootCmd.Flags().BoolP("no-color", "n", false, "disable colorized outputs")
rootCmd.Flags().BoolP("filesize", "f", false, "show the file size")
}
2 changes: 1 addition & 1 deletion internal/gcstree.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"google.golang.org/api/iterator"
)

const GCSTREE_VERSION = "0.0.5"
const GCSTREE_VERSION = "1.0.0"

type GCSTree struct {
bucket string
Expand Down
9 changes: 8 additions & 1 deletion internal/tree.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package internal

import (
"fmt"
"path/filepath"
"strings"

Expand All @@ -22,8 +23,14 @@ func tree(bucket string, objList []*storage.ObjectAttrs, option *PrintOption) (s
if s == "" {
continue
}
originalFilename := s
if option.WithSize {
if s == file {
s = fmt.Sprintf("[%4s] %s", formatBytes(obj.Size), s)
}
}
if option.WithColorized {
if s != file {
if originalFilename != file {
s = color.BlueString("%s", s)
}
}
Expand Down
19 changes: 19 additions & 0 deletions internal/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package internal

import (
"fmt"
)

// ref: https://yourbasic.org/golang/formatting-byte-size-to-human-readable-format/
func formatBytes(b int64) string {
const unit = 1000
if b < unit {
return fmt.Sprintf("%d", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f%c", float64(b)/float64(div), "KMGTPE"[exp])
}
19 changes: 19 additions & 0 deletions internal/util_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package internal

import "testing"

func TestFormatBytes(t *testing.T) {
tests := map[int64]string{
999: "999",
1024: "1.0K",
1536: "1.5K",
987654321: "987.7M",
}
for key, value := range tests {
got := formatBytes(key)
want := value
if got != want {
t.Fatalf("got: %v, want: %v\n", got, want)
}
}
}

0 comments on commit 1ca3229

Please sign in to comment.