-
Notifications
You must be signed in to change notification settings - Fork 394
/
lsdrivers_linux.go
80 lines (73 loc) · 1.65 KB
/
lsdrivers_linux.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
// Copyright 2012-2017 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// lsdrivers lists driver usage on Linux systems
//
// Synopsis:
//
// lsdrivers [-u]
//
// Description:
//
// List driver usage. This program is mostly useful for scripts.
//
// Options:
//
// -u: list unused drivers
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
)
var unused = flag.Bool("u", false, "Show unused drivers")
// hasDevices returns true if there is a non-symlink, i.e. regular,
// file in driverpath. This indicates that it is real hardware.
// If the path has any sort of error, return false.
func hasDevices(driverpath string) bool {
files, err := os.ReadDir(driverpath)
if err != nil {
return false
}
for _, file := range files {
if file.Type()&os.ModeSymlink != 0 {
return true
}
}
return false
}
func lsdrivers(bus string, unused bool) ([]string, error) {
var d []string
files, err := os.ReadDir(bus)
if err != nil {
return nil, err
}
for _, f := range files {
n := filepath.Join(bus, f.Name(), "drivers")
drivers, err := os.ReadDir(n)
// In some cases the directory does not exist.
if err != nil {
continue
}
for _, driver := range drivers {
n := filepath.Join(bus, f.Name(), "drivers", driver.Name())
if hasDevices(n) != unused {
d = append(d, fmt.Sprintf(f.Name()+"."+driver.Name()))
}
}
}
return d, nil
}
func main() {
flag.Parse()
drivers, err := lsdrivers("/sys/bus", *unused)
if err != nil {
log.Fatal(err)
}
if _, err := fmt.Println(strings.Join(drivers, "\n")); err != nil {
log.Fatal(err)
}
}