-
Notifications
You must be signed in to change notification settings - Fork 0
/
lsblk.go
548 lines (489 loc) · 14.4 KB
/
lsblk.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
"text/tabwriter"
)
type Partition struct {
Name string
Type string
Identifier string
Size string
FSType string
Label string
UUID string
Mountpoint string
PartitionType string
}
type Disk struct {
Name string
Size string
Type string
Identifier string
Partitions []Partition
FSType string
Label string
UUID string
Mountpoint string
PartitionType string
}
func main() {
// Define flags
bytesFlag := flag.Bool("b", false, "Print the SIZE column in bytes rather than in a human-readable format.")
flag.BoolVar(bytesFlag, "bytes", false, "Print the SIZE column in bytes rather than in a human-readable format.")
nodepsFlag := flag.Bool("d", false, "Do not print holder devices or replicas.")
flag.BoolVar(nodepsFlag, "nodeps", false, "Do not print holder devices or replicas.")
excludeList := flag.String("e", "", "Exclude the devices specified by the comma-separated list of names.")
flag.StringVar(excludeList, "exclude", "", "Exclude the devices specified by the comma-separated list of names.")
fsFlag := flag.Bool("f", false, "Output info about filesystems.")
flag.BoolVar(fsFlag, "fs", false, "Output info about filesystems.")
helpFlag := flag.Bool("h", false, "Display help text and exit.")
flag.BoolVar(helpFlag, "help", false, "Display help text and exit.")
includeList := flag.String("I", "", "Include devices specified by the comma-separated list of names.")
flag.StringVar(includeList, "include", "", "Include devices specified by the comma-separated list of names.")
asciiFlag := flag.Bool("i", false, "Use ASCII characters for tree formatting.")
flag.BoolVar(asciiFlag, "ascii", false, "Use ASCII characters for tree formatting.")
jsonFlag := flag.Bool("J", false, "Use JSON output format.")
flag.BoolVar(jsonFlag, "json", false, "Use JSON output format.")
listFlag := flag.Bool("l", false, "Produce output in the form of a list.")
flag.BoolVar(listFlag, "list", false, "Produce output in the form of a list.")
noheadingsFlag := flag.Bool("n", false, "Do not print a header line.")
flag.BoolVar(noheadingsFlag, "noheadings", false, "Do not print a header line.")
pathsFlag := flag.Bool("p", false, "Print full device paths.")
flag.BoolVar(pathsFlag, "paths", false, "Print full device paths.")
sortColumn := flag.String("x", "", "Sort by column (name, size, type, identifier)")
flag.StringVar(sortColumn, "sort", "", "Sort by column (name, size, type, identifier)")
versionFlag := flag.Bool("v", false, "Print version")
flag.Parse()
if *helpFlag {
flag.Usage()
fmt.Println("mac lsblk v0.1 hacked together by jake.trock.com :^]")
return
}
if *versionFlag {
fmt.Println("mac lsblk v0.1 hacked together by jake.trock.com :^]")
return
}
// Run diskutil list
cmd := exec.Command("diskutil", "list")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
fmt.Printf("Error running diskutil list: %v\n", err)
return
}
// Run df
dfCmd := exec.Command("df")
var dfOut bytes.Buffer
dfCmd.Stdout = &dfOut
err = dfCmd.Run()
if err != nil {
fmt.Printf("Error running df -h: %v\n", err)
return
}
// Get mountpoints
mounts := getMounts(dfOut.String())
disks := parseDiskutilOutput(out.String(), mounts)
// Apply include and exclude filters
if *includeList != "" {
disks = includeDisks(disks, strings.Split(*includeList, ","))
}
if *excludeList != "" {
disks = excludeDisks(disks, strings.Split(*excludeList, ","))
}
if *nodepsFlag {
// Remove partitions
for i := range disks {
disks[i].Partitions = nil
}
}
if *sortColumn != "" {
sortDisks(disks, *sortColumn)
}
// Handle bytes flag
if *bytesFlag {
for i := range disks {
disks[i].Size = sizeToBytes(disks[i].Size)
for j := range disks[i].Partitions {
disks[i].Partitions[j].Size = sizeToBytes(disks[i].Partitions[j].Size)
}
}
}
// Handle fs flag
if *fsFlag {
// Get filesystem info for disks and partitions
for i := range disks {
getFilesystemInfo(&disks[i])
for j := range disks[i].Partitions {
getPartitionFilesystemInfo(&disks[i].Partitions[j])
}
}
}
if *jsonFlag {
jsonOutput(disks)
return
}
// Prepare to print in table format
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
if !*noheadingsFlag {
if *fsFlag {
fmt.Fprintln(w, "NAME\tSIZE\tFSTYPE\tLABEL\tUUID\tMOUNTPOINT")
} else {
fmt.Fprintln(w, "NAME\tSIZE\tTYPE\tIDENTIFIER")
}
}
for _, disk := range disks {
name := disk.Name
if *pathsFlag {
name = "/dev/" + name
}
fmt.Fprintf(w, "%s\t%s", name, disk.Size)
if *fsFlag {
fmt.Fprintf(w, "\t%s\t%s\t%s\t%s\n", disk.FSType, disk.Label, disk.UUID, disk.Mountpoint)
} else {
fmt.Fprintf(w, "\t%s\t%s\n", disk.Type, disk.Identifier)
}
if !*nodepsFlag {
for ind, part := range disk.Partitions {
partName := part.Name
if *pathsFlag {
partName = "/dev/" + part.Identifier
}
prefix := "├─"
if ind == len(disk.Partitions)-1 {
prefix = "└─"
}
if *asciiFlag {
if prefix == "├─" {
prefix = "|-"
} else {
prefix = "`-"
}
}
fmt.Fprintf(w, "%s%s\t%s", prefix, partName, part.Size)
if *fsFlag {
fmt.Fprintf(w, "\t%s\t%s\t%s\t%s\n", part.FSType, part.Label, part.UUID, part.Mountpoint)
} else {
fmt.Fprintf(w, "\t%s\t%s\n", part.Type, part.Identifier)
}
}
}
}
w.Flush()
}
func getMounts(dfOutput string) map[string]string {
mounts := make(map[string]string)
lines := strings.Split(dfOutput, "\n")
// Skip the header line
if len(lines) < 2 {
return mounts
}
// Regex pattern to match the filesystem and mounted on columns
pattern := `^(\S+)\s+\d+\s+\d+\s+\d+\s+\d+%\s+\d+\s+\d+\s+\d+%\s+(.+)$`
re := regexp.MustCompile(pattern)
for _, line := range lines[1:] {
matches := re.FindStringSubmatch(line)
if len(matches) == 3 {
filesystem := strings.TrimSpace(matches[1])
mountedOn := strings.TrimSpace(matches[2])
if filesystem != "" && mountedOn != "" {
mounts[filesystem] = mountedOn
}
}
}
return mounts
}
func parseDiskutilOutput(output string, mounts map[string]string) []Disk {
lines := strings.Split(output, "\n")
var disks []Disk
var currentDisk *Disk
diskHeaderRegex := regexp.MustCompile(`^\/dev\/(disk\d+)`)
diskInfoRegex := regexp.MustCompile(`^\/dev\/(disk\d+).*?\*\s*([\d\.]+\s\w+).*`)
partitionRegex := regexp.MustCompile(`^\s+(\d+):\s+(\S+)\s+(.*?)\s+([\d\.]+\s\w+)\s+(\S+)$`)
for _, line := range lines {
if diskHeaderRegex.MatchString(line) {
matches := diskHeaderRegex.FindStringSubmatch(line)
cmd := exec.Command("diskutil", "info", matches[1])
out, _ := cmd.Output()
info := string(out)
currentDisk = &Disk{
Name: func() string {
if matches[1] != "" {
return matches[1]
}
return getValueForKey(info, "Volume Name:")
}(),
Type: "disk",
Identifier: func() string {
if matches[1] != "" {
return matches[1]
}
return getValueForKey(info, "Device Identifier:")
}(),
Size: getValueForKey(info, "Total Size:"),
Mountpoint: func() string {
if matches[1] != "" {
return mounts[matches[1]]
}
return mounts[getValueForKey(info, "Volume Name:")]
}(),
FSType: getValueForKey(info, "Type (Bundle):"),
Label: getValueForKey(info, "Volume Name:"),
UUID: getValueForKey(info, "Volume UUID:"),
PartitionType: getValueForKey(info, "Partition Type:"),
}
// Call parseInfo to fill additional info
disks = append(disks, *currentDisk)
} else if diskInfoRegex.MatchString(line) {
matches := diskInfoRegex.FindStringSubmatch(line)
cmd := exec.Command("diskutil", "info", matches[1])
out, _ := cmd.Output()
info := string(out)
currentDisk = &Disk{
Name: func() string {
if matches[1] != "" {
return matches[1]
}
return getValueForKey(info, "Volume Name:")
}(),
Type: "disk",
Identifier: func() string {
if matches[1] != "" {
return matches[1]
}
return getValueForKey(info, "Device Identifier:")
}(),
Size: getValueForKey(info, "Total Size:"),
Mountpoint: func() string {
if matches[1] != "" {
return mounts[matches[1]]
}
return mounts[getValueForKey(info, "Volume Name:")]
}(),
FSType: getValueForKey(info, "Type (Bundle):"),
Label: getValueForKey(info, "Volume Name:"),
UUID: getValueForKey(info, "Volume UUID:"),
PartitionType: getValueForKey(info, "Partition Type:"),
}
disks = append(disks, *currentDisk)
} else if partitionRegex.MatchString(line) && currentDisk != nil {
matches := partitionRegex.FindStringSubmatch(line)
partition := Partition{
Name: matches[3],
Type: matches[2],
Size: matches[4],
Identifier: matches[5],
PartitionType: getValueForKey(matches[5], "Partition Type:"),
UUID: getValueForKey(matches[5], "Volume UUID:"),
Label: getValueForKey(matches[5], "Volume Name:"),
Mountpoint: mounts["/dev/"+matches[5]],
}
// Add partition to the last disk in the slice
diskIndex := len(disks) - 1
disks[diskIndex].Partitions = append(disks[diskIndex].Partitions, partition)
}
}
return disks
}
func sortDisks(disks []Disk, sortColumn string) {
switch sortColumn {
case "name":
sort.Slice(disks, func(i, j int) bool {
return disks[i].Name < disks[j].Name
})
case "size":
sort.Slice(disks, func(i, j int) bool {
return compareSizeStrings(disks[i].Size, disks[j].Size)
})
case "type":
sort.Slice(disks, func(i, j int) bool {
return disks[i].Type < disks[j].Type
})
case "identifier":
sort.Slice(disks, func(i, j int) bool {
return disks[i].Identifier < disks[j].Identifier
})
}
for i := range disks {
sortPartitions(disks[i].Partitions, sortColumn)
}
}
func sortPartitions(partitions []Partition, sortColumn string) {
switch sortColumn {
case "name":
sort.Slice(partitions, func(i, j int) bool {
return partitions[i].Name < partitions[j].Name
})
case "size":
sort.Slice(partitions, func(i, j int) bool {
return compareSizeStrings(partitions[i].Size, partitions[j].Size)
})
case "type":
sort.Slice(partitions, func(i, j int) bool {
return partitions[i].Type < partitions[j].Type
})
case "identifier":
sort.Slice(partitions, func(i, j int) bool {
return partitions[i].Identifier < partitions[j].Identifier
})
}
}
func compareSizeStrings(size1, size2 string) bool {
bytes1 := parseSizeToBytes(size1)
bytes2 := parseSizeToBytes(size2)
return bytes1 < bytes2
}
func parseSizeToBytes(sizeStr string) int64 {
sizeStr = strings.TrimSpace(sizeStr)
re := regexp.MustCompile(`([\d\.]+)\s*(\w+)`)
matches := re.FindStringSubmatch(sizeStr)
if len(matches) != 3 {
return 0
}
sizeValue, _ := strconv.ParseFloat(matches[1], 64)
unit := strings.ToUpper(matches[2])
multiplier := map[string]float64{
"B": 1,
"KB": 1 << 10,
"MB": 1 << 20,
"GB": 1 << 30,
"TB": 1 << 40,
}
return int64(sizeValue * multiplier[unit])
}
func sizeToBytes(sizeStr string) string {
bytes := parseSizeToBytes(sizeStr)
return fmt.Sprintf("%d", bytes)
}
func getFilesystemInfo(disk *Disk) {
cmd := exec.Command("diskutil", "info", disk.Identifier)
out, err := cmd.Output()
if err != nil {
return
}
// Parse the output to extract filesystem info
info := string(out)
disk.FSType = getValueForKey(info, "Type (Bundle):")
disk.Label = getValueForKey(info, "Volume Name:")
disk.UUID = getValueForKey(info, "Volume UUID:")
disk.Mountpoint = getValueForKey(info, "Mount Point:")
}
func getPartitionFilesystemInfo(part *Partition) {
cmd := exec.Command("diskutil", "info", part.Identifier)
out, err := cmd.Output()
if err != nil {
return
}
// Parse the output to extract filesystem info
info := string(out)
part.FSType = getValueForKey(info, "Type (Bundle):")
part.Label = getValueForKey(info, "Volume Name:")
part.UUID = getValueForKey(info, "Volume UUID:")
part.Mountpoint = getValueForKey(info, "Mount Point:")
}
func getValueForKey(info string, key string) string {
re := regexp.MustCompile(key + `\s*(.*)`)
matches := re.FindStringSubmatch(info)
if len(matches) == 2 {
return strings.TrimSpace(matches[1])
}
return ""
}
func includeDisks(disks []Disk, include []string) []Disk {
var result []Disk
includeMap := make(map[string]bool)
for _, name := range include {
includeMap[name] = true
}
for _, disk := range disks {
if includeMap[disk.Name] {
result = append(result, disk)
}
}
return result
}
func excludeDisks(disks []Disk, exclude []string) []Disk {
var result []Disk
excludeMap := make(map[string]bool)
for _, name := range exclude {
excludeMap[name] = true
}
for _, disk := range disks {
if !excludeMap[disk.Name] {
result = append(result, disk)
}
}
return result
}
func jsonOutput(disks []Disk) {
genericJSON := make(map[string]interface{})
for _, disk := range disks {
diskJSON := make(map[string]interface{})
if disk.Size != "" {
diskJSON["size"] = disk.Size
}
diskJSON["type"] = disk.Type
diskJSON["identifier"] = disk.Identifier
if disk.FSType != "" {
diskJSON["fstype"] = disk.FSType
}
if disk.Label != "" {
diskJSON["label"] = disk.Label
}
if disk.UUID != "" {
diskJSON["uuid"] = disk.UUID
}
if disk.Mountpoint != "" {
diskJSON["mountpoint"] = disk.Mountpoint
}
if disk.PartitionType != "" {
diskJSON["partitiontype"] = disk.PartitionType
}
partitions := make([]map[string]interface{}, len(disk.Partitions))
for i, part := range disk.Partitions {
partJSON := make(map[string]interface{})
partJSON["name"] = part.Name
partJSON["type"] = part.Type
if part.Identifier != "" {
partJSON["identifier"] = part.Identifier
}
if part.Size != "" {
partJSON["size"] = part.Size
}
if part.FSType != "" {
partJSON["fstype"] = part.FSType
}
if part.Label != "" {
partJSON["label"] = part.Label
}
if part.UUID != "" {
partJSON["uuid"] = part.UUID
}
if part.Mountpoint != "" {
partJSON["mountpoint"] = part.Mountpoint
}
if part.PartitionType != "" {
partJSON["partitiontype"] = part.PartitionType
}
partitions[i] = partJSON
}
diskJSON["partitions"] = partitions
genericJSON[disk.Name] = diskJSON
}
// Remove blank fields
data, err := json.MarshalIndent(genericJSON, "", " ")
if err != nil {
fmt.Printf("Error generating JSON output: %v\n", err)
return
}
fmt.Println(string(data))
}