Skip to content

Commit d062ab5

Browse files
committed
Add human-readable format flag
1 parent 7a20096 commit d062ab5

File tree

5 files changed

+217
-26
lines changed

5 files changed

+217
-26
lines changed

bin/hexlet-path-size

4.3 KB
Binary file not shown.

cmd/hexlet-path-size/main.go

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,33 @@ import (
1111
)
1212

1313
func main() {
14-
1514
cmd := &cli.Command{
16-
Name: "hexlet-path-size",
17-
Usage: "print size of a file or directory;",
15+
UseShortOptionHandling: true,
16+
Name: "hexlet-path-size",
17+
Usage: "print size of a file or directory;",
18+
Flags: []cli.Flag{
19+
&cli.BoolFlag{
20+
Name: "human",
21+
Aliases: []string{"H"},
22+
Value: false,
23+
Usage: "human-readable sizes (auto-select unit)"},
24+
},
25+
Action: func(ctx context.Context, cmd *cli.Command) error {
26+
path := "." //default value
27+
if cmd.Args().Len() > 0 {
28+
path = cmd.Args().Get(0)
29+
}
30+
h := cmd.Bool("human")
31+
size, err := goproject242.GetSize(path, h)
32+
if err != nil {
33+
log.Println(err.Error())
34+
}
35+
fmt.Println(size)
36+
return nil
37+
},
1838
}
1939

2040
if err := cmd.Run(context.Background(), os.Args); err != nil {
2141
log.Fatal(err)
22-
path := os.Args[1]
23-
fmt.Println(goproject242.GetSize(path))
2442
}
25-
2643
}

path_size.go

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,14 @@
11
package goproject242
22

33
import (
4-
"context"
54
"errors"
65
"fmt"
7-
"log"
86
"os"
97
"path/filepath"
10-
11-
"github.com/urfave/cli/v3"
8+
"strconv"
129
)
1310

14-
func Help() {
15-
cmd := &cli.Command{
16-
Name: "hexlet-path-size",
17-
Usage: "print size of a file or directory;",
18-
}
19-
20-
if err := cmd.Run(context.Background(), os.Args); err != nil {
21-
log.Fatal(err)
22-
}
23-
}
24-
25-
func GetSize(path string) (string, error) {
11+
func GetSize(path string, human bool) (string, error) {
2612
if path == "" {
2713
return "", errors.New("не указан путь")
2814
}
@@ -35,7 +21,8 @@ func GetSize(path string) (string, error) {
3521
if err != nil {
3622
return "", errors.New("не удалось получить информацию о файле")
3723
}
38-
return fmt.Sprintf("%vB\t%s", i.Size(), path), nil
24+
//return fmt.Sprintf("%vB\t%s", i.Size(), path), nil
25+
return fmt.Sprintf("%v\t%s", FormatSize(i.Size(), human), path), nil
3926
}
4027

4128
var sum int64
@@ -53,5 +40,29 @@ func GetSize(path string) (string, error) {
5340
sum += stat.Size()
5441
}
5542
}
56-
return fmt.Sprintf("%vB\t%s", sum, path), nil
43+
//return fmt.Sprintf("%vB\t%s", sum, path), nil
44+
return fmt.Sprintf("%v\t%s", FormatSize(sum, human), path), nil
45+
}
46+
47+
func FormatSize(size int64, human bool) string {
48+
if human {
49+
str := strconv.Itoa(int(size))
50+
switch {
51+
case len(str) <= 3:
52+
return fmt.Sprintf("%vB", size)
53+
case len(str) > 3 && len(str) <= 6:
54+
return fmt.Sprintf("%.1fKB", float64(size)/1000)
55+
case len(str) >= 7 && len(str) < 10:
56+
return fmt.Sprintf("%.1fMB", float64(size)/1000000)
57+
case len(str) >= 10 && len(str) < 13:
58+
return fmt.Sprintf("%.1fGB", float64(size)/1000000000)
59+
case len(str) >= 13 && len(str) < 16:
60+
return fmt.Sprintf("%.1fTB", float64(size)/1000000000000)
61+
case len(str) >= 16 && len(str) < 19:
62+
return fmt.Sprintf("%.1fPB", float64(size)/1000000000000000)
63+
default:
64+
return fmt.Sprintf("%.1fEB", float64(size)/1000000000000000000)
65+
}
66+
}
67+
return fmt.Sprintf("%vB", size)
5768
}

path_size_test.go

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package goproject242
22

33
import (
44
"errors"
5+
"reflect"
56
"testing"
67

78
"github.com/stretchr/testify/assert"
@@ -12,37 +13,42 @@ var testCases = []struct {
1213
path_file string
1314
expect string
1415
err error
16+
human bool
1517
}{
1618
{
1719
name: "Path-file",
1820
path_file: "testdata/text.txt",
1921
expect: "23B\ttestdata/text.txt",
2022
err: nil,
23+
human: true,
2124
},
2225
{
2326
name: "Path-directory",
2427
path_file: "testdata",
25-
expect: "82B\ttestdata",
28+
expect: "8939B\ttestdata",
2629
err: nil,
30+
human: false,
2731
},
2832
{
2933
name: "Empty path",
3034
path_file: "",
3135
expect: "",
3236
err: errors.New("не указан путь"),
37+
human: true,
3338
},
3439
{
3540
name: "Wrong path",
3641
path_file: "testdata/text.txttt",
3742
expect: "",
3843
err: errors.New("не удалось прочитать путь к файлу или директории"),
44+
human: true,
3945
},
4046
}
4147

4248
func TestGetSize(t *testing.T) {
4349
for _, tc := range testCases {
4450
t.Run(tc.name, func(t *testing.T) {
45-
got, err := GetSize(tc.path_file)
51+
got, err := GetSize(tc.path_file, tc.human)
4652
if tc.err != nil {
4753
if err.Error() != tc.err.Error() {
4854
t.Errorf("ожидали %v, получили %v", tc.err.Error(), err.Error())
@@ -62,3 +68,38 @@ func TestGetSize(t *testing.T) {
6268
})
6369
}
6470
}
71+
72+
var testCases2 = []struct {
73+
name string
74+
size []int64
75+
human bool
76+
expect []string
77+
}{
78+
{
79+
name: "nonHumanReadable",
80+
size: []int64{123, 10000, 500000},
81+
human: false,
82+
expect: []string{"123B", "10000B", "500000B"},
83+
},
84+
{
85+
name: "HumanReadable",
86+
size: []int64{123, 10000, 999950},
87+
human: true,
88+
expect: []string{"123B", "10.0KB", "1000.0KB"},
89+
},
90+
}
91+
92+
func TestFormatSize(t *testing.T) {
93+
for _, tc := range testCases2 {
94+
t.Run(tc.name, func(t *testing.T) {
95+
var got []string
96+
for _, s := range tc.size {
97+
size := FormatSize(s, tc.human)
98+
got = append(got, size)
99+
}
100+
if !reflect.DeepEqual(got, tc.expect) {
101+
t.Errorf("ожидали %v, получили %v", tc.expect, got)
102+
}
103+
})
104+
}
105+
}

testdata/CLI_Utilities.txt

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
Individual utilities
2+
* arch: (coreutils)arch invocation. Print machine hardware name.
3+
* b2sum: (coreutils)b2sum invocation. Print or check BLAKE2 digests.
4+
* base32: (coreutils)base32 invocation. Base32 encode/decode data.
5+
* base64: (coreutils)base64 invocation. Base64 encode/decode data.
6+
* basename: (coreutils)basename invocation. Strip directory and suffix.
7+
* basenc: (coreutils)basenc invocation. Encoding/decoding of data.
8+
* cat: (coreutils)cat invocation. Concatenate and write files.
9+
* chcon: (coreutils)chcon invocation. Change SELinux CTX of files.
10+
* chgrp: (coreutils)chgrp invocation. Change file groups.
11+
* chmod: (coreutils)chmod invocation. Change access permissions.
12+
* chown: (coreutils)chown invocation. Change file owners and groups.
13+
* chroot: (coreutils)chroot invocation. Specify the root directory.
14+
* cksum: (coreutils)cksum invocation. Print POSIX CRC checksum.
15+
* cmp: (diffutils)Invoking cmp. Compare 2 files byte by byte.
16+
* comm: (coreutils)comm invocation. Compare sorted files by line.
17+
* cp: (coreutils)cp invocation. Copy files.
18+
* csplit: (coreutils)csplit invocation. Split by context.
19+
* cut: (coreutils)cut invocation. Print selected parts of lines.
20+
* date: (coreutils)date invocation. Print/set system date and time.
21+
* dd: (coreutils)dd invocation. Copy and convert a file.
22+
* df: (coreutils)df invocation. Report file system usage.
23+
* diff: (diffutils)Invoking diff. Compare 2 files line by line.
24+
* diff3: (diffutils)Invoking diff3. Compare 3 files line by line.
25+
* dir: (coreutils)dir invocation. List directories briefly.
26+
* dircolors: (coreutils)dircolors invocation. Color setup for ls.
27+
* dirname: (coreutils)dirname invocation. Strip last file name component.
28+
* du: (coreutils)du invocation. Report file usage.
29+
* echo: (coreutils)echo invocation. Print a line of text.
30+
* env: (coreutils)env invocation. Modify the environment.
31+
* expand: (coreutils)expand invocation. Convert tabs to spaces.
32+
* expr: (coreutils)expr invocation. Evaluate expressions.
33+
* factor: (coreutils)factor invocation. Print prime factors
34+
* false: (coreutils)false invocation. Do nothing, unsuccessfully.
35+
* find: (find)Finding Files. Finding and acting on files.
36+
* fmt: (coreutils)fmt invocation. Reformat paragraph text.
37+
* fold: (coreutils)fold invocation. Wrap long input lines.
38+
* groups: (coreutils)groups invocation. Print group names a user is in.
39+
* gunzip: (gzip)Overview. Decompression.
40+
* gzexe: (gzip)Overview. Compress executables.
41+
* head: (coreutils)head invocation. Output the first part of files.
42+
* hostid: (coreutils)hostid invocation. Print numeric host identifier.
43+
* hostname: (coreutils)hostname invocation. Print or set system name.
44+
* id: (coreutils)id invocation. Print user identity.
45+
* install: (coreutils)install invocation. Copy files and set attributes.
46+
* join: (coreutils)join invocation. Join lines on a common field.
47+
* kill: (coreutils)kill invocation. Send a signal to processes.
48+
* link: (coreutils)link invocation. Make hard links between files.
49+
* ln: (coreutils)ln invocation. Make links between files.
50+
* locate: (find)Invoking locate. Finding files in a database.
51+
* logname: (coreutils)logname invocation. Print current login name.
52+
* ls: (coreutils)ls invocation. List directory contents.
53+
* md5sum: (coreutils)md5sum invocation. Print or check MD5 digests.
54+
* mkdir: (coreutils)mkdir invocation. Create directories.
55+
* mkfifo: (coreutils)mkfifo invocation. Create FIFOs (named pipes).
56+
* mknod: (coreutils)mknod invocation. Create special files.
57+
* mktemp: (coreutils)mktemp invocation. Create temporary files.
58+
* mv: (coreutils)mv invocation. Rename files.
59+
* nice: (coreutils)nice invocation. Modify niceness.
60+
* nl: (coreutils)nl invocation. Number lines and write files.
61+
* nohup: (coreutils)nohup invocation. Immunize to hangups.
62+
* nproc: (coreutils)nproc invocation. Print the number of processors.
63+
* numfmt: (coreutils)numfmt invocation. Reformat numbers.
64+
* od: (coreutils)od invocation. Dump files in octal, etc.
65+
* paste: (coreutils)paste invocation. Merge lines of files.
66+
* patch: (diffutils)Invoking patch. Apply a patch to a file.
67+
* pathchk: (coreutils)pathchk invocation. Check file name portability.
68+
* pinky: (coreutils)pinky invocation. Print information about users.
69+
* pr: (coreutils)pr invocation. Paginate or columnate files.
70+
* printenv: (coreutils)printenv invocation. Print environment variables.
71+
* printf: (coreutils)printf invocation. Format and print data.
72+
* ptx: (coreutils)ptx invocation. Produce permuted indexes.
73+
* pwd: (coreutils)pwd invocation. Print working directory.
74+
* readlink: (coreutils)readlink invocation. Print referent of a symlink.
75+
* realpath: (coreutils)realpath invocation. Print resolved file names.
76+
* rm: (coreutils)rm invocation. Remove files.
77+
* rmdir: (coreutils)rmdir invocation. Remove empty directories.
78+
* runcon: (coreutils)runcon invocation. Run in specified SELinux CTX.
79+
* sdiff: (diffutils)Invoking sdiff. Merge 2 files side-by-side.
80+
* seq: (coreutils)seq invocation. Print numeric sequences
81+
* sha1sum: (coreutils)sha1sum invocation. Print or check SHA-1 digests.
82+
* sha2: (coreutils)sha2 utilities. Print or check SHA-2 digests.
83+
* shred: (coreutils)shred invocation. Remove files more securely.
84+
* shuf: (coreutils)shuf invocation. Shuffling text files.
85+
* sleep: (coreutils)sleep invocation. Delay for a specified time.
86+
* sort: (coreutils)sort invocation. Sort text files.
87+
* split: (coreutils)split invocation. Split into pieces.
88+
* stat: (coreutils)stat invocation. Report file(system) status.
89+
* stdbuf: (coreutils)stdbuf invocation. Modify stdio buffering.
90+
* stty: (coreutils)stty invocation. Print/change terminal settings.
91+
* sum: (coreutils)sum invocation. Print traditional checksum.
92+
* sync: (coreutils)sync invocation. Sync files to stable storage.
93+
* tac: (coreutils)tac invocation. Reverse files.
94+
* tail: (coreutils)tail invocation. Output the last part of files.
95+
* tee: (coreutils)tee invocation. Redirect to multiple files.
96+
* test: (coreutils)test invocation. File/string tests.
97+
* timeout: (coreutils)timeout invocation. Run with time limit.
98+
* touch: (coreutils)touch invocation. Change file timestamps.
99+
* tr: (coreutils)tr invocation. Translate characters.
100+
* true: (coreutils)true invocation. Do nothing, successfully.
101+
* truncate: (coreutils)truncate invocation. Shrink/extend size of a file.
102+
* tsort: (coreutils)tsort invocation. Topological sort.
103+
* tty: (coreutils)tty invocation. Print terminal name.
104+
* uname: (coreutils)uname invocation. Print system information.
105+
* unexpand: (coreutils)unexpand invocation. Convert spaces to tabs.
106+
* uniq: (coreutils)uniq invocation. Uniquify files.
107+
* unlink: (coreutils)unlink invocation. Removal via unlink(2).
108+
* updatedb: (find)Invoking updatedb. Building the locate database.
109+
* uptime: (coreutils)uptime invocation. Print uptime and load.
110+
* users: (coreutils)users invocation. Print current user names.
111+
* vdir: (coreutils)vdir invocation. List directories verbosely.
112+
* wc: (coreutils)wc invocation. Line, word, and byte counts.
113+
* who: (coreutils)who invocation. Print who is logged in.
114+
* whoami: (coreutils)whoami invocation. Print effective user ID.
115+
* xargs: (find)Invoking xargs. Operating on many files.
116+
* yes: (coreutils)yes invocation. Print a string indefinitely.
117+
* zcat: (gzip)Overview. Decompression to stdout.
118+
* zdiff: (gzip)Overview. Compare compressed files.
119+
* zforce: (gzip)Overview. Force .gz extension on files.
120+
* zgrep: (gzip)Overview. Search compressed files.
121+
* zmore: (gzip)Overview. Decompression output by pages.
122+

0 commit comments

Comments
 (0)