fork/gdu
git clone https://git.julia.blue/fork/gdu
da638da
master
1//go:build freebsd || darwin 2 3package device 4 5import ( 6"bufio" 7"bytes" 8"errors" 9"io" 10"os/exec" 11"regexp" 12"strings" 13 14"golang.org/x/sys/unix" 15) 16 17// BSDDevicesInfoGetter returns info for Darwin devices 18type BSDDevicesInfoGetter struct { 19MountCmd string 20} 21 22// Getter is current instance of DevicesInfoGetter 23var Getter DevicesInfoGetter = BSDDevicesInfoGetter {MountCmd :"/sbin/mount" } 24 25// GetMounts returns all mounted filesystems from output of /sbin/mount 26func (t BSDDevicesInfoGetter )GetMounts () (devices Devices ,err error ) { 27var out []byte 28out ,err = exec .Command (t .MountCmd ).Output () 29if err != nil { 30return nil ,err 31 } 32 33rdr := bytes .NewReader (out ) 34 35return readMountOutput (rdr ) 36} 37 38// GetDevicesInfo returns result of GetMounts with usage info about mounted devices (by calling Statfs syscall) 39func (t BSDDevicesInfoGetter )GetDevicesInfo () (devices Devices ,err error ) { 40var mounts Devices 41mounts ,err = t .GetMounts () 42if err != nil { 43return nil ,err 44 } 45 46return processMounts (mounts ,false ) 47} 48 49func readMountOutput (rdr io.Reader ) (mounts Devices ,err error ) { 50scanner := bufio .NewScanner (rdr ) 51for scanner .Scan () { 52line := scanner .Text () 53 54re := regexp .MustCompile (`^(.*) on (/.*) \(([^)]+)\)$` ) 55parts := re .FindAllStringSubmatch (line ,- 1 ) 56 57if len (parts )< 1 { 58return nil ,errors .New ("cannot parse mount output" ) 59 } 60 61fstype := strings .TrimSpace (strings .Split (parts [0 ][3 ],"," )[0 ]) 62 63device := & Device { 64Name :parts [0 ][1 ], 65MountPoint :parts [0 ][2 ], 66Fstype :fstype , 67 } 68mounts = append (mounts ,device ) 69 } 70 71if err := scanner .Err ();err != nil { 72return nil ,err 73 } 74 75return mounts ,nil 76} 77 78func processMounts (mounts Devices ,ignoreErrors bool ) (devices Devices ,err error ) { 79for _ ,mount := range mounts { 80if ! strings .HasPrefix (mount .Name ,"/dev" )&& mount .Fstype != "zfs" { 81continue 82 } 83 84info := & unix.Statfs_t {} 85err := unix .Statfs (mount .MountPoint ,info ) 86if err != nil && ! ignoreErrors { 87return nil ,err 88 } 89 90mount .Size = int64 (info .Bsize )* int64 (info .Blocks ) 91mount .Free = int64 (info .Bsize )* int64 (info .Bavail ) 92 93devices = append (devices ,mount ) 94 } 95 96return devices ,nil 97}