Skip to content

Commit 0d45736

Browse files
committed
optimize directory reading logic
1 parent 1a309e6 commit 0d45736

File tree

1 file changed

+45
-2
lines changed

1 file changed

+45
-2
lines changed

dir_command.go

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,30 @@ import (
1010
type dirCmd struct {
1111
path string
1212
orderOpt Optioner
13+
sortOpt Optioner
14+
15+
files int
1316
}
1417

1518
func newDirCmd(path string) cmder {
1619
return &dirCmd{
1720
path: path,
1821
orderOpt: newOrderOption(),
22+
sortOpt: newSortOption(),
1923
}
2024
}
2125

2226
func (cmd *dirCmd) run(opts map[string]string) (int, error) {
2327
opts = cmd.orderOpt.extract(opts)
28+
opts = cmd.sortOpt.extract(opts)
2429
if len(opts) != 0 {
2530
return ExitCodeFailed, fmt.Errorf("the count of directory does not support options: [%s]", serializeMap(opts))
2631
}
2732
cmd.readFileNames(cmd.path, "")
33+
if cmd.sortOpt.value() == sortValueFiles {
34+
fmt.Println()
35+
fmt.Printf("the all files number: %d\n", cmd.files)
36+
}
2837
return ExitCodeSuccess, nil
2938
}
3039

@@ -35,14 +44,48 @@ func (cmd *dirCmd) readFileNames(path, prefix string) {
3544
os.Exit(ExitCodeFailed)
3645
}
3746
entries = cmd.sortEntries(entries)
47+
sortValue := cmd.sortOpt.value()
3848
prefix += "│----"
3949
for _, e := range entries {
40-
fmt.Println(prefix + e.Name())
50+
// deal directory
51+
p := filepath.Join(path, e.Name())
4152
if e.IsDir() {
42-
p := filepath.Join(path, e.Name())
53+
fmt.Println(prefix + e.Name())
4354
cmd.readFileNames(p, prefix)
4455
continue
4556
}
57+
58+
// increment files number
59+
cmd.files++
60+
if sortValue == sortValueFiles {
61+
fmt.Println(prefix + e.Name())
62+
continue
63+
}
64+
65+
// read file points
66+
ext := filepath.Ext(p)
67+
pj, miss := newPageJudger(ext)
68+
if miss {
69+
fmt.Println(prefix + e.Name())
70+
continue
71+
}
72+
pp := newPagePoint()
73+
if err := pp.extract(p, pj); err != nil {
74+
fmt.Println(prefix + e.Name() + " [ERROR: read failed]")
75+
continue
76+
}
77+
var tail string
78+
switch sortValue {
79+
case sortValueCode:
80+
tail = fmt.Sprintf("[codes: %d]", pp.codes)
81+
case sortValueBlank:
82+
tail = fmt.Sprintf("[blanks: %d]", pp.blanks)
83+
case sortValueComment:
84+
tail = fmt.Sprintf("[comments: %d]", pp.comments)
85+
default:
86+
tail = fmt.Sprintf("[codes: %d, comments: %d, blanks: %d]", pp.codes, pp.comments, pp.blanks)
87+
}
88+
fmt.Println(prefix + e.Name() + " ---------->" + tail)
4689
}
4790
}
4891

0 commit comments

Comments
 (0)