-
-
Notifications
You must be signed in to change notification settings - Fork 403
/
main.go
315 lines (270 loc) · 7.75 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"strconv"
"strings"
wildcard "github.com/IGLOU-EU/go-wildcard"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/muesli/termenv"
"golang.org/x/term"
)
var (
// Version contains the application version number. It's set via ldflags
// when building.
Version = ""
// CommitSHA contains the SHA of the commit that this application was built
// against. It's set via ldflags when building.
CommitSHA = ""
env = termenv.EnvColorProfile()
theme Theme
groups = []string{localDevice, networkDevice, fuseDevice, specialDevice, loopsDevice, bindsMount}
allowedValues = strings.Join(groups, ", ")
all = flag.Bool("all", false, "include pseudo, duplicate, inaccessible file systems")
hideDevices = flag.String("hide", "", "hide specific devices, separated with commas:\n"+allowedValues)
hideFs = flag.String("hide-fs", "", "hide specific filesystems, separated with commas")
hideMp = flag.String("hide-mp", "", "hide specific mount points, separated with commas (supports wildcards)")
onlyDevices = flag.String("only", "", "show only specific devices, separated with commas:\n"+allowedValues)
onlyFs = flag.String("only-fs", "", "only specific filesystems, separated with commas")
onlyMp = flag.String("only-mp", "", "only specific mount points, separated with commas (supports wildcards)")
output = flag.String("output", "", "output fields: "+strings.Join(columnIDs(), ", "))
sortBy = flag.String("sort", "mountpoint", "sort output by: "+strings.Join(columnIDs(), ", "))
width = flag.Uint("width", 0, "max output width")
themeOpt = flag.String("theme", defaultThemeName(), "color themes: dark, light, ansi")
styleOpt = flag.String("style", defaultStyleName(), "style: unicode, ascii")
availThreshold = flag.String("avail-threshold", "10G,1G", "specifies the coloring threshold (yellow, red) of the avail column, must be integer with optional SI prefixes")
usageThreshold = flag.String("usage-threshold", "0.5,0.9", "specifies the coloring threshold (yellow, red) of the usage bars as a floating point number from 0 to 1")
inodes = flag.Bool("inodes", false, "list inode information instead of block usage")
jsonOutput = flag.Bool("json", false, "output all devices in JSON format")
warns = flag.Bool("warnings", false, "output all warnings to STDERR")
version = flag.Bool("version", false, "display version")
)
// renderJSON encodes the JSON output and prints it.
func renderJSON(m []Mount) error {
output, err := json.MarshalIndent(m, "", " ")
if err != nil {
return fmt.Errorf("error formatting the json output: %s", err)
}
fmt.Println(string(output))
return nil
}
// parseColumns parses the supplied output flag into a slice of column indices.
func parseColumns(cols string) ([]int, error) {
var i []int
s := strings.Split(cols, ",")
for _, v := range s {
v = strings.TrimSpace(v)
if len(v) == 0 {
continue
}
col, err := stringToColumn(v)
if err != nil {
return nil, err
}
i = append(i, col)
}
return i, nil
}
// parseStyle converts user-provided style option into a table.Style.
func parseStyle(styleOpt string) (table.Style, error) {
switch styleOpt {
case "unicode":
return table.StyleRounded, nil
case "ascii":
return table.StyleDefault, nil
default:
return table.Style{}, fmt.Errorf("unknown style option: %s", styleOpt)
}
}
// parseCommaSeparatedValues parses comma separated string into a map.
func parseCommaSeparatedValues(values string) map[string]struct{} {
m := make(map[string]struct{})
for _, v := range strings.Split(values, ",") {
v = strings.TrimSpace(v)
if len(v) == 0 {
continue
}
v = strings.ToLower(v)
m[v] = struct{}{}
}
return m
}
// validateGroups validates the parsed group maps.
func validateGroups(m map[string]struct{}) error {
for k := range m {
found := false
for _, g := range groups {
if g == k {
found = true
break
}
}
if !found {
return fmt.Errorf("unknown device group: %s", k)
}
}
return nil
}
// findInKey parse a slice of pattern to match the given key.
func findInKey(str string, km map[string]struct{}) bool {
for p := range km {
if wildcard.Match(p, str) {
return true
}
}
return false
}
func main() {
flag.Parse()
if *version {
if len(CommitSHA) > 7 {
CommitSHA = CommitSHA[:7]
}
if Version == "" {
Version = "(built from source)"
}
fmt.Printf("duf %s", Version)
if len(CommitSHA) > 0 {
fmt.Printf(" (%s)", CommitSHA)
}
fmt.Println()
os.Exit(0)
}
// read mount table
m, warnings, err := mounts()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// print JSON
if *jsonOutput {
if err = renderJSON(m); err != nil {
fmt.Fprintln(os.Stderr, err)
}
return
}
// validate theme
theme, err = loadTheme(*themeOpt)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if env == termenv.ANSI {
// enforce ANSI theme for limited color support
theme, err = loadTheme("ansi")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
// validate style
style, err := parseStyle(*styleOpt)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// validate output columns
columns, err := parseColumns(*output)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if len(columns) == 0 {
// no columns supplied, use defaults
if *inodes {
columns = []int{1, 6, 7, 8, 9, 10, 11}
} else {
columns = []int{1, 2, 3, 4, 5, 10, 11}
}
}
// validate sort column
sortCol, err := stringToSortIndex(*sortBy)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// validate filters
filters := FilterOptions{
HiddenDevices: parseCommaSeparatedValues(*hideDevices),
OnlyDevices: parseCommaSeparatedValues(*onlyDevices),
HiddenFilesystems: parseCommaSeparatedValues(*hideFs),
OnlyFilesystems: parseCommaSeparatedValues(*onlyFs),
HiddenMountPoints: parseCommaSeparatedValues(*hideMp),
OnlyMountPoints: parseCommaSeparatedValues(*onlyMp),
}
err = validateGroups(filters.HiddenDevices)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = validateGroups(filters.OnlyDevices)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// validate arguments
if len(flag.Args()) > 0 {
var mounts []Mount
for _, v := range flag.Args() {
var fm []Mount
fm, err = findMounts(m, v)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
mounts = append(mounts, fm...)
}
m = mounts
}
// validate availability thresholds
availbilityThresholds := strings.Split(*availThreshold, ",")
if len(availbilityThresholds) != 2 {
fmt.Fprintln(os.Stderr, fmt.Errorf("error parsing avail-threshold: invalid option '%s'", *availThreshold))
os.Exit(1)
}
for _, threshold := range availbilityThresholds {
_, err = stringToSize(threshold)
if err != nil {
fmt.Fprintln(os.Stderr, "error parsing avail-threshold:", err)
os.Exit(1)
}
}
// validate usage thresholds
usageThresholds := strings.Split(*usageThreshold, ",")
if len(usageThresholds) != 2 {
fmt.Fprintln(os.Stderr, fmt.Errorf("error parsing usage-threshold: invalid option '%s'", *usageThreshold))
os.Exit(1)
}
for _, threshold := range usageThresholds {
_, err = strconv.ParseFloat(threshold, 64)
if err != nil {
fmt.Fprintln(os.Stderr, "error parsing usage-threshold:", err)
os.Exit(1)
}
}
// print out warnings
if *warns {
for _, warning := range warnings {
fmt.Fprintln(os.Stderr, warning)
}
}
// detect terminal width
isTerminal := term.IsTerminal(int(os.Stdout.Fd()))
if isTerminal && *width == 0 {
w, _, err := term.GetSize(int(os.Stdout.Fd()))
if err == nil {
*width = uint(w)
}
}
if *width == 0 {
*width = 80
}
// print tables
renderTables(m, filters, TableOptions{
Columns: columns,
SortBy: sortCol,
Style: style,
})
}