Skip to content

Commit

Permalink
Merge pull request #119 from numtide/cleanup
Browse files Browse the repository at this point in the history
Save 1MB by not using charmbracelet/log
  • Loading branch information
brianmcgee authored Sep 25, 2024
2 parents 1534b9a + 754c899 commit 4a180aa
Show file tree
Hide file tree
Showing 11 changed files with 114 additions and 207 deletions.
172 changes: 85 additions & 87 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,123 +2,121 @@ package cmd

import (
"encoding/json"
"flag"
"fmt"
"log"
"os"
"slices"
"strings"

"github.com/numtide/nixos-facter/pkg/hwinfo"

"github.com/numtide/nixos-facter/pkg/facter"

"github.com/spf13/cobra"
"github.com/numtide/nixos-facter/pkg/hwinfo"
)

var (
cfgFile string
outputPath string
logLevel string
hardwareFeatures []string

scanner = facter.Scanner{}
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "nixos-facter",
Short: "Hardware report generator",
// todo Long description
// todo add Long description
RunE: func(cmd *cobra.Command, args []string) error {
// check the effective user id is 0 e.g. root
if os.Geteuid() != 0 {
cmd.SilenceUsage = true
return fmt.Errorf("you must run this program as root")
}

// convert the hardware features into probe features
for _, str := range hardwareFeatures {
probe, err := hwinfo.ProbeFeatureString(str)
if err != nil {
return fmt.Errorf("invalid hardware feature: %w", err)
}
scanner.Features = append(scanner.Features, probe)
}
func init() {
// Define flags
flag.StringVar(&outputPath, "output", "", "path to write the report")
flag.StringVar(&outputPath, "o", "", "path to write the report")
flag.BoolVar(&scanner.Swap, "swap", false, "capture swap entries")
flag.BoolVar(&scanner.Ephemeral, "ephemeral", false, "capture all ephemeral properties e.g. swap, filesystems and so on")
flag.StringVar(&logLevel, "log-level", "info", "log level")

report, err := scanner.Scan()
if err != nil {
return err
}
defaultFeatures := []string{
"memory", "pci", "net", "serial", "cpu", "bios", "monitor", "scsi", "usb", "prom", "sbus", "sys", "sysfs",
"udev", "block", "wlan",
}

bytes, err := json.MarshalIndent(report, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal report to json: %w", err)
probeFeatures := hwinfo.ProbeFeatureStrings()
filteredFeatures := []string{}
for _, feature := range probeFeatures {
if feature != "default" && feature != "int" {
filteredFeatures = append(filteredFeatures, feature)
}
}

// if a file path is provided write the report to it, otherwise output the report on stdout
if outputPath == "" {
if _, err = os.Stdout.Write(bytes); err != nil {
return fmt.Errorf("failed to write report to stdout: %w", err)
}
fmt.Println()
} else if err = os.WriteFile(outputPath, bytes, 0o644); err != nil {
return fmt.Errorf("failed to write report to output path: %w", err)
}
hardwareFeatures = defaultFeatures

flag.Func("hardware", "Hardware items to probe (comma separated).", func(flagValue string) error {
hardwareFeatures = strings.Split(flagValue, ",")
return nil
},
})
possibleValues := strings.Join(filteredFeatures, ",")
defaultValues := strings.Join(defaultFeatures, ",")
const usage = `nixos-facter [flags]
Hardware report generator
Usage:
nixos-facter [flags]
Flags:
--ephemeral capture all ephemeral properties e.g. swap, filesystems and so on
-h, --help help for nixos-facter
-o, --output string path to write the report
--swap capture swap entries
--hardware strings Hardware items to probe.
Default: %s
Possible values: %s
`

// Custom usage function
flag.Usage = func() { fmt.Fprintf(os.Stderr, usage, defaultValues, possibleValues) }
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
flag.Parse()

func init() {
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.s
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.nixos-facter.yaml)")
// Check if the effective user id is 0 e.g. root
if os.Geteuid() != 0 {
log.Fatalf("you must run this program as root")
}

// Cobra also supports local flags, which will only run when this action is called directly.
f := rootCmd.Flags()
f.StringVarP(&outputPath, "output", "o", "", "path to write the report")
// Convert the hardware features into probe features
for _, str := range hardwareFeatures {
probe, err := hwinfo.ProbeFeatureString(str)
if err != nil {
log.Fatalf("invalid hardware feature: %v", err)
}
scanner.Features = append(scanner.Features, probe)
}

// Options for optional ephemeral system properties.
f.BoolVarP(&scanner.Swap, "swap", "s", false, "capture swap entries")
f.BoolVarP(&scanner.Ephemeral, "ephemeral", "e", false, "capture all ephemeral properties e.g. swap, filesystems and so on")
// Set the log level
switch logLevel {
case "debug":
log.SetFlags(log.LstdFlags | log.Lshortfile)
case "info":
log.SetFlags(log.LstdFlags)
case "warn", "error":
log.SetFlags(0)
default:
log.Fatalf("invalid log level: %s", logLevel)
}

// We currently support all probe features at a high level as they share some generic information,
// but we do not have mappings for all of their detail sections.
// These will be added on a priority / need basis.
report, err := scanner.Scan()
if err != nil {
log.Fatalf("failed to scan: %v", err)
}

defaultFeatures := []string{
"memory", "pci", "net", "serial", "cpu", "bios", "monitor", "scsi", "usb", "prom", "sbus", "sys", "sysfs",
"udev", "block", "wlan",
bytes, err := json.MarshalIndent(report, "", " ")
if err != nil {
log.Fatalf("failed to marshal report to json: %v", err)
}

// we strip default and int from the feature list
probeFeatures := hwinfo.ProbeFeatureStrings()
slices.DeleteFunc(probeFeatures, func(str string) bool {
switch str {
case "default", "int":
return true
default:
return false
// If a file path is provided write the report to it, otherwise output the report on stdout
if outputPath == "" {
if _, err = os.Stdout.Write(bytes); err != nil {
log.Fatalf("failed to write report to stdout: %v", err)
}
})

f.StringSliceVarP(
&hardwareFeatures,
"hardware",
"f",
defaultFeatures,
fmt.Sprintf(
"Hardware items to probe. Possible values are %s",
strings.Join(probeFeatures, ","),
),
)
fmt.Println()
} else if err = os.WriteFile(outputPath, bytes, 0o644); err != nil {
log.Fatalf("failed to write report to output path: %v", err)
}
}
14 changes: 0 additions & 14 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,14 @@ module github.com/numtide/nixos-facter
go 1.22.3

require (
github.com/charmbracelet/log v0.4.0
github.com/klauspost/cpuid/v2 v2.2.9-0.20240805145549-92d5326f011e
github.com/spf13/cobra v1.8.1
github.com/stretchr/testify v1.9.0
)

require (
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/charmbracelet/lipgloss v0.10.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.18 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.15.2 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
golang.org/x/sys v0.22.0 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
34 changes: 0 additions & 34 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,53 +1,19 @@
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/charmbracelet/lipgloss v0.10.0 h1:KWeXFSexGcfahHX+54URiZGkBFazf70JNMtwg/AFW3s=
github.com/charmbracelet/lipgloss v0.10.0/go.mod h1:Wig9DSfvANsxqkRsqj6x87irdy123SR4dOXlKa91ciE=
github.com/charmbracelet/log v0.4.0 h1:G9bQAcx8rWA2T3pWvx7YtPTPwgqpk7D68BX21IRW8ZM=
github.com/charmbracelet/log v0.4.0/go.mod h1:63bXt/djrizTec0l11H20t8FDSvA4CRZJ1KH22MdptM=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4=
github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/klauspost/cpuid/v2 v2.2.9-0.20240805145549-92d5326f011e h1:XLeT7xVis8xyC0F4CqQ2fAcuBar61PMI7GhrUEBBKas=
github.com/klauspost/cpuid/v2 v2.2.9-0.20240805145549-92d5326f011e/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=
github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
42 changes: 0 additions & 42 deletions nix/packages/nixos-facter/gomod2nix.toml
Original file line number Diff line number Diff line change
@@ -1,63 +1,21 @@
schema = 3

[mod]
[mod."github.com/aymanbagabas/go-osc52/v2"]
version = "v2.0.1"
hash = "sha256-6Bp0jBZ6npvsYcKZGHHIUSVSTAMEyieweAX2YAKDjjg="
[mod."github.com/charmbracelet/lipgloss"]
version = "v0.10.0"
hash = "sha256-JZD1iVeizYe0mp3qQcJbUZdYN6HP/DNC67ja79DTe6s="
[mod."github.com/charmbracelet/log"]
version = "v0.4.0"
hash = "sha256-VQerB44vC646n3fe3haJ3DHa9L5+GRhCfDfm1p3QnZk="
[mod."github.com/davecgh/go-spew"]
version = "v1.1.2-0.20180830191138-d8f796af33cc"
hash = "sha256-fV9oI51xjHdOmEx6+dlq7Ku2Ag+m/bmbzPo6A4Y74qc="
[mod."github.com/go-logfmt/logfmt"]
version = "v0.6.0"
hash = "sha256-RtIG2qARd5sT10WQ7F3LR8YJhS8exs+KiuUiVf75bWg="
[mod."github.com/inconshreveable/mousetrap"]
version = "v1.1.0"
hash = "sha256-XWlYH0c8IcxAwQTnIi6WYqq44nOKUylSWxWO/vi+8pE="
[mod."github.com/klauspost/cpuid/v2"]
version = "v2.2.9-0.20240805145549-92d5326f011e"
hash = "sha256-yCZS40L97G7WZHhy/A6I8ArEkyHi86DGAW43SziYPek="
[mod."github.com/kr/pretty"]
version = "v0.3.1"
hash = "sha256-DlER7XM+xiaLjvebcIPiB12oVNjyZHuJHoRGITzzpKU="
[mod."github.com/lucasb-eyer/go-colorful"]
version = "v1.2.0"
hash = "sha256-Gg9dDJFCTaHrKHRR1SrJgZ8fWieJkybljybkI9x0gyE="
[mod."github.com/mattn/go-isatty"]
version = "v0.0.18"
hash = "sha256-QpIn0DSggtBn2ocyj0RlXDKLK5F5KZG1/ogzrqBCjF8="
[mod."github.com/mattn/go-runewidth"]
version = "v0.0.15"
hash = "sha256-WP39EU2UrQbByYfnwrkBDoKN7xzXsBssDq3pNryBGm0="
[mod."github.com/muesli/reflow"]
version = "v0.3.0"
hash = "sha256-Pou2ybE9SFSZG6YfZLVV1Eyfm+X4FuVpDPLxhpn47Cc="
[mod."github.com/muesli/termenv"]
version = "v0.15.2"
hash = "sha256-Eum/SpyytcNIchANPkG4bYGBgcezLgej7j/+6IhqoMU="
[mod."github.com/pmezard/go-difflib"]
version = "v1.0.1-0.20181226105442-5d4384ee4fb2"
hash = "sha256-XA4Oj1gdmdV/F/+8kMI+DBxKPthZ768hbKsO3d9Gx90="
[mod."github.com/rivo/uniseg"]
version = "v0.4.7"
hash = "sha256-rDcdNYH6ZD8KouyyiZCUEy8JrjOQoAkxHBhugrfHjFo="
[mod."github.com/spf13/cobra"]
version = "v1.8.1"
hash = "sha256-yDF6yAHycV1IZOrt3/hofR+QINe+B2yqkcIaVov3Ky8="
[mod."github.com/spf13/pflag"]
version = "v1.0.5"
hash = "sha256-w9LLYzxxP74WHT4ouBspH/iQZXjuAh2WQCHsuvyEjAw="
[mod."github.com/stretchr/testify"]
version = "v1.9.0"
hash = "sha256-uUp/On+1nK+lARkTVtb5RxlW15zxtw2kaAFuIASA+J0="
[mod."golang.org/x/exp"]
version = "v0.0.0-20240506185415-9bf2ced13842"
hash = "sha256-5JZE4OhePWHtObIT4RJOS+2zv265Io1yJkFeE8wHXY4="
[mod."golang.org/x/sys"]
version = "v0.22.0"
hash = "sha256-RbG0XaXGGlErCsl2agvUxMnrkRwdbJLmriYT1H24FwA="
Expand Down
2 changes: 1 addition & 1 deletion nix/packages/nixos-facter/tests/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ in
extraTestScript = ''
import json
report = json.loads(machine.succeed("nixos-facter -e"))
report = json.loads(machine.succeed("nixos-facter --ephemeral"))
with subtest("Capture system"):
assert report['system'] == '${system}'
Expand Down
Loading

0 comments on commit 4a180aa

Please sign in to comment.