-
Notifications
You must be signed in to change notification settings - Fork 4
/
fstype.go
64 lines (53 loc) · 1.29 KB
/
fstype.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
package main
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
)
// Given a file or directory, finds which filesystem it is on,
// by parsing /proc/self/mountinfo and comparing dev_t
// of the file to that in the mountinfo field.
func GetFilesystemType(path string) (string, error) {
var st syscall.Stat_t
err := syscall.Stat(path, &st)
if err != nil {
return "", err
}
return getFSTypeByDev(st.Dev)
}
// convert minor:major string from /proc/self/mountinfo into dev_t
func parseDev(s string) uint64 {
var major uint32
var minor uint32
n, _ := fmt.Sscanf(s, "%d:%d", &major, &minor)
if n != 2 {
return 0
}
return uint64(major<<8 + minor)
}
func getFSTypeByDev(dev uint64) (string, error) {
mi, err := os.Open("/proc/self/mountinfo")
if err != nil {
return "", err
}
defer mi.Close()
sc := bufio.NewScanner(mi)
for sc.Scan() {
line := strings.Split(sc.Text(), " ")
if len(line) < 10 {
return "", fmt.Errorf("Short line in /proc/self/mountinfo: %v\n", line)
}
dstr := line[2] // major:minor: value of st_dev for files on filesystem
fs := line[8] // filesystem type: name of filesystem of the form "type[.subtype]"
d := parseDev(dstr)
if d == 0 {
return "", fmt.Errorf("Can't parse device %s", dstr)
}
if d == dev {
return fs, nil
}
}
return "", nil
}