forked from godarch/darch
-
Notifications
You must be signed in to change notification settings - Fork 4
/
block.go
98 lines (79 loc) · 2.19 KB
/
block.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
package block
import (
"bufio"
"fmt"
"github.com/pkg/errors"
"os/exec"
"path"
"strings"
)
// GetBlockDeviceForPath Get the block device for the given path
func GetBlockDeviceForPath(path string) (string, error) {
if len(path) == 0 {
return "", fmt.Errorf("path required")
}
result, err := runCommand("df", "--output=source", path)
if err != nil {
return "", err
}
if len(result) == 2 {
if result[1] == "-" {
return "", fmt.Errorf("error getting block device for %s, possibly not on block device", path)
}
return result[1], nil
}
return "", errors.Wrap(fmt.Errorf(strings.Join(result, " ")), "error running df")
}
// GetUUIDForBlockDevice Get the UUID for the given block device.
func GetUUIDForBlockDevice(blockDevice string) (string, error) {
if len(blockDevice) == 0 {
return "", fmt.Errorf("block device required")
}
result, err := runCommand("blkid", blockDevice)
if err != nil {
return "", err
}
if len(result) == 1 {
values := strings.Split(result[0], " ")
for _, value := range values {
if strings.HasPrefix(value, "UUID=\"") {
return value[6 : len(value)-1], nil
}
}
}
return "", errors.Wrap(fmt.Errorf(strings.Join(result, " ")), "error running blkid")
}
// GetPathRelativeToBlockDevice Give a full path to your system, and it will return it's path, relative to the device it is hosted on.
// For example, if a device is mounted on "/test/mount" and you invoke this method with "/test/mount/with/this/file",
// then you will get /with/this/file returned.
func GetPathRelativeToBlockDevice(p string) (string, error) {
if len(p) == 0 {
return "", fmt.Errorf("path required")
}
result, err := runCommand("df", p, "--output=target")
if err != nil {
return "", err
}
if len(result) == 2 {
return path.Join("/", p[len(result[1]):]), nil
}
return "", nil
}
func runCommand(name string, args ...string) ([]string, error) {
cmd := exec.Command(name, args...)
cmdOut, _ := cmd.StdoutPipe()
result := []string{}
err := cmd.Start()
if err != nil {
return result, err
}
scanner := bufio.NewScanner(cmdOut)
for scanner.Scan() {
result = append(result, scanner.Text())
}
err = cmd.Wait()
if err != nil {
return result, err
}
return result, nil
}