File: dev_bsd.go

package info (click to toggle)
gdu 5.25.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 624 kB
  • sloc: makefile: 122
file content (75 lines) | stat: -rw-r--r-- 1,607 bytes parent folder | download | duplicates (2)
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
//go:build netbsd || openbsd
// +build netbsd openbsd

package device

import (
	"bufio"
	"bytes"
	"errors"
	"io"
	"os/exec"
	"regexp"
	"strings"
)

// BSDDevicesInfoGetter returns info for Darwin devices
type BSDDevicesInfoGetter struct {
	MountCmd string
}

// Getter is current instance of DevicesInfoGetter
var Getter DevicesInfoGetter = BSDDevicesInfoGetter{MountCmd: "/sbin/mount"}

// GetMounts returns all mounted filesystems from output of /sbin/mount
func (t BSDDevicesInfoGetter) GetMounts() (Devices, error) {
	out, err := exec.Command(t.MountCmd).Output()
	if err != nil {
		return nil, err
	}

	rdr := bytes.NewReader(out)

	return readMountOutput(rdr)
}

// GetDevicesInfo returns result of GetMounts with usage info about mounted devices (by calling Statfs syscall)
func (t BSDDevicesInfoGetter) GetDevicesInfo() (Devices, error) {
	mounts, err := t.GetMounts()
	if err != nil {
		return nil, err
	}

	return processMounts(mounts, false)
}

func readMountOutput(rdr io.Reader) (Devices, error) {
	mounts := Devices{}

	scanner := bufio.NewScanner(rdr)
	for scanner.Scan() {
		line := scanner.Text()

		re := regexp.MustCompile("^(.*) on (/.*) type (.*) \\(([^)]+)\\)$")
		parts := re.FindAllStringSubmatch(line, -1)

		if len(parts) < 1 {
			return nil, errors.New("Cannot parse mount output")
		}

		fstype := strings.TrimSpace(strings.Split(parts[0][3], ",")[0])

		device := &Device{
			Name:       parts[0][1],
			MountPoint: parts[0][2],
			Fstype:     fstype,
		}
		mounts = append(mounts, device)
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return mounts, nil
}