github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/cmds/core/lsdrivers/main_linux.go (about) 1 // Copyright 2012-2017 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // lsdrivers lists driver usage on Linux systems 6 // 7 // Synopsis: 8 // 9 // lsdrivers [-u] 10 // 11 // Description: 12 // 13 // List driver usage. This program is mostly useful for scripts. 14 // 15 // Options: 16 // 17 // -u: list unused drivers 18 package main 19 20 import ( 21 "flag" 22 "fmt" 23 "log" 24 "os" 25 "path/filepath" 26 "strings" 27 ) 28 29 var unused = flag.Bool("u", false, "Show unused drivers") 30 31 // hasDevices returns true if there is a non-symlink, i.e. regular, 32 // file in driverpath. This indicates that it is real hardware. 33 // If the path has any sort of error, return false. 34 func hasDevices(driverpath string) bool { 35 files, err := os.ReadDir(driverpath) 36 if err != nil { 37 return false 38 } 39 for _, file := range files { 40 if file.Type()&os.ModeSymlink != 0 { 41 return true 42 } 43 } 44 return false 45 } 46 47 func lsdrivers(bus string, unused bool) ([]string, error) { 48 var d []string 49 files, err := os.ReadDir(bus) 50 if err != nil { 51 return nil, err 52 } 53 54 for _, f := range files { 55 n := filepath.Join(bus, f.Name(), "drivers") 56 drivers, err := os.ReadDir(n) 57 // In some cases the directory does not exist. 58 if err != nil { 59 continue 60 } 61 for _, driver := range drivers { 62 n := filepath.Join(bus, f.Name(), "drivers", driver.Name()) 63 if hasDevices(n) != unused { 64 d = append(d, fmt.Sprintf(f.Name()+"."+driver.Name())) 65 } 66 } 67 } 68 return d, nil 69 } 70 71 func main() { 72 flag.Parse() 73 drivers, err := lsdrivers("/sys/bus", *unused) 74 if err != nil { 75 log.Fatal(err) 76 } 77 if _, err := fmt.Println(strings.Join(drivers, "\n")); err != nil { 78 log.Fatal(err) 79 } 80 }