-
Notifications
You must be signed in to change notification settings - Fork 0
/
disks.go
71 lines (58 loc) · 1.33 KB
/
disks.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
package drivelist
import (
"io/ioutil"
"strings"
)
type Disks struct {
Devices []*DiskDevice
devNames map[string]int
}
func GetDisks() (*Disks, error) {
d := &Disks{}
d.Devices = make([]*DiskDevice, 0)
d.devNames = make(map[string]int)
names, err := GetDiskNames()
if err != nil {
return d, err
}
for i, name := range names {
dev, err := NewDiskDevice("/dev/" + name)
if err != nil {
return d, err
}
d.Devices = append(d.Devices, dev)
for _, devName := range d.Devices[i].Devices {
d.devNames[devName] = i
}
}
return d, nil
}
func (d *Disks) GetDiskByName(name string) *DiskDevice {
index, ok := d.devNames[name]
if ok {
return d.Devices[index]
}
// Not found. But we could be looking at a partitioned device
// (/dev/sda1, or /dev/disks/by-id/foo-part1, so let's strip
// those and try again.
name = strings.TrimRight(name, "0123456789") // remove trailing partition number, if it's there.
name = strings.TrimSuffix(name, "-part")
index, ok = d.devNames[name]
if ok {
return d.Devices[index]
}
return nil
}
func GetDiskNames() ([]string, error) {
disks := []string{}
files, err := ioutil.ReadDir("/sys/block/")
if err != nil {
return disks, err
}
for _, file := range files {
if strings.HasPrefix(file.Name(), "sd") {
disks = append(disks, file.Name())
}
}
return disks, nil
}