-
Notifications
You must be signed in to change notification settings - Fork 0
/
cf.go
88 lines (77 loc) · 1.93 KB
/
cf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// CF -- count files in directories and subdirectories (like du(1) but
// for counting files rather than file sizes)
//
// SvM 30-JAN-2021 - 05-JUL-2022
//
// created from https://raw.githubusercontent.com/missedone/dugo/master/du.go
// and https://golang.org/pkg/os/#Stat by chipping away anrything we
// don't need
package main
import (
"flag"
"fmt"
"os"
"path"
)
var only_sum bool // -s option
var print_tot bool // -c option
var print_sep bool // -S option
var also_dots bool // -a option
func count_files(currPath string, depth int) int64 {
var count int64
stat, err := os.Lstat(currPath)
if err != nil {
fmt.Println(err)
return count
}
switch mode := stat.Mode(); {
case mode.IsDir():
files, err := os.ReadDir(currPath)
if err != nil {
fmt.Println(err)
return count
}
for _, file := range files {
if file.IsDir() {
count += count_files(fmt.Sprintf("%s/%s", currPath, file.Name()), depth+1)
} else if file.Type().IsRegular() {
if also_dots == true || file.Name()[0] != '.' {
// println(file.Name())
count++
}
}
}
case mode.IsRegular():
// no need to add also_dots logic because we only get
// here when currPath was specified on command line??
count++
}
if only_sum == false || (only_sum == true && depth == 0) {
fmt.Printf("%d\t%s\n", count, path.Clean(currPath))
}
if print_sep {
return 0
} else {
return count
}
}
func main() {
var dir string
var tot int64
flag.BoolVar(&only_sum, "s", false, "print only a total for each argument")
flag.BoolVar(&print_tot, "c", false, "print grand total")
flag.BoolVar(&print_sep, "S", false, "don't add subdirectories to directory counts")
flag.BoolVar(&also_dots, "a", false, "do not ignore entries starting with .")
flag.Parse()
if flag.NArg() > 0 {
for _, dir = range flag.Args() {
tot += count_files(dir, 0)
}
} else {
dir = "."
tot = count_files(dir, 0)
}
if print_tot {
fmt.Printf("%d\t%s\n", tot, "total")
}
}