fork/gdu
git clone https://git.julia.blue/fork/gdu
81b1d22
master
1package device 2 3import ( 4"bufio" 5"fmt" 6"io" 7"os" 8"strings" 9 10"golang.org/x/sys/unix" 11) 12 13// LinuxDevicesInfoGetter returns info for Linux devices 14type LinuxDevicesInfoGetter struct { 15MountsPath string 16} 17 18// Getter is current instance of DevicesInfoGetter 19var Getter DevicesInfoGetter = LinuxDevicesInfoGetter {MountsPath :"/proc/mounts" } 20 21// GetMounts returns all mounted filesystems from /proc/mounts 22func (t LinuxDevicesInfoGetter )GetMounts () (devices Devices ,err error ) { 23file ,err := os .Open (t .MountsPath ) 24if err != nil { 25return nil ,err 26 } 27 28devices ,err = readMountsFile (file ) 29if err != nil { 30if cerr := file .Close ();cerr != nil { 31return nil ,fmt .Errorf ("%w; %s" ,err ,cerr .Error ()) 32 } 33return nil ,err 34 } 35if err := file .Close ();err != nil { 36return nil ,err 37 } 38return devices ,nil 39} 40 41// GetDevicesInfo returns result of GetMounts with usage info about mounted devices (by calling Statfs syscall) 42func (t LinuxDevicesInfoGetter )GetDevicesInfo () (devices Devices ,err error ) { 43mounts ,err := t .GetMounts () 44if err != nil { 45return nil ,err 46 } 47 48return processMounts (mounts ,false ) 49} 50 51func readMountsFile (file io.Reader ) (mounts Devices ,err error ) { 52mounts = Devices {} 53 54scanner := bufio .NewScanner (file ) 55for scanner .Scan () { 56line := scanner .Text () 57parts := strings .Fields (line ) 58 59// skip malformed lines, a valid entry has at least device, mount point and fstype 60if len (parts )< 3 { 61continue 62 } 63 64device := & Device { 65Name :parts [0 ], 66MountPoint :unescapeString (parts [1 ]), 67Fstype :parts [2 ], 68 } 69mounts = append (mounts ,device ) 70 } 71 72if err := scanner .Err ();err != nil { 73return nil ,err 74 } 75 76return mounts ,nil 77} 78 79func processMounts (mounts Devices ,ignoreErrors bool ) (devices Devices ,err error ) { 80devices = Devices {} 81 82for _ ,mount := range mounts { 83if strings .Contains (mount .MountPoint ,"/snap/" ) { 84continue 85 } 86 87if strings .HasPrefix (mount .Name ,"/dev" )|| 88mount .Fstype == "zfs" || 89mount .Fstype == "nfs" || 90mount .Fstype == "nfs4" { 91info := & unix.Statfs_t {} 92err = unix .Statfs (mount .MountPoint ,info ) 93if err != nil && ! ignoreErrors { 94return nil ,err 95 } 96 97mount .Size = int64 (info .Bsize )* int64 (info .Blocks ) 98mount .Free = int64 (info .Bsize )* int64 (info .Bavail ) 99 100devices = append (devices ,mount ) 101 } 102 } 103 104return devices ,nil 105} 106 107func unescapeString (str string )string { 108return strings .ReplaceAll (str ,"\\040" ," " ) 109}