Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ COUNT ?= 5

LIMACTL ?= limactl
LIMA_INSTANCE_PREFIX ?= facts
LIMA_GO_VERSION ?= 1.26.4
LIMA_GO_VERSION ?= 1.26.5
LIMA_GO_SERIES ?= 1.26
LIMA_GOARCH ?= arm64
LIMA_CPUS ?= 6
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/ncode/facts

go 1.26.4
go 1.26.5

require gopkg.in/yaml.v3 v3.0.1

Expand Down
29 changes: 12 additions & 17 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,24 +249,19 @@ func runQuery(stdout, stderr io.Writer, args []string) error {
if err != nil {
return err
}
facts := snapshot.Facts()
presentation := snapshot.OutputProjection(mergeDottedFacts)
resolutionDuration := time.Since(resolutionStart).Seconds()
out, err := engine.BuildFormatter(engine.FormatOptions{
JSON: options.JSON,
YAML: options.YAML,
HOCON: options.HOCON,
IncludeTypedDotted: mergeDottedFacts,
Colorize: colorOutput,
}).Format(facts)
JSON: options.JSON,
YAML: options.YAML,
HOCON: options.HOCON,
Colorize: colorOutput,
})(presentation)
if err != nil {
return err
}
if options.Timing {
for _, fact := range facts {
name := fact.UserQuery
if name == "" {
name = fact.Name
}
for _, name := range presentation.PresentationNames() {
if _, err := fmt.Fprintf(stdout, "fact '%s', took: (%.3f) seconds\n", name, resolutionDuration); err != nil {
return err
}
Expand All @@ -283,7 +278,7 @@ func runQuery(stdout, stderr io.Writer, args []string) error {
}
}
if options.Strict {
missing := engine.NewProjection(facts, mergeDottedFacts).MissingQueries(facts)
missing := presentation.MissingQueries()
if len(missing) > 0 {
for _, name := range missing {
writeError(stderr, fmt.Sprintf("fact %q does not exist.", name), colorDiagnostics)
Expand Down Expand Up @@ -392,15 +387,15 @@ func canUseVersionQueryFastPath(queries, externalDirs []string, disabledFacts ma
}

func writeVersionQuery(stdout io.Writer, jsonOutput, yamlOutput, hoconOutput bool) error {
facts := []engine.ResolvedFact{{Name: "facterversion", Value: engine.Version, UserQuery: "facterversion"}}
presentation := engine.NewProjection([]engine.ResolvedFact{{Name: "facterversion", Value: engine.Version, UserQuery: "facterversion"}}, false)
// The fast path carries only the three format booleans: it deliberately
// ignores --color and --force-dot-resolution, so Colorize/IncludeTypedDotted
// stay false and formatter selection reuses the engine's own precedence.
// ignores --color and --force-dot-resolution, so it uses an uncolored,
// non-force-dot Projection and the engine's own formatter precedence.
out, err := engine.BuildFormatter(engine.FormatOptions{
JSON: jsonOutput,
YAML: yamlOutput,
HOCON: hoconOutput,
}).Format(facts)
})(presentation)
if err != nil {
return err
}
Expand Down
43 changes: 43 additions & 0 deletions internal/app/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -782,6 +782,49 @@ func TestRun_timingPrintsResolutionDuration(t *testing.T) {
}
}

func TestRun_sharedPresentationProjectionPreservesTimingOutputAndStrictOrder(t *testing.T) {
var stdout, stderr bytes.Buffer

err := Run(&stdout, &stderr, []string{"--timing", "--strict", "--json", "os.name", "missing_fact", "missing_fact"})
status, ok := err.(ExitStatus)
if !ok {
t.Fatalf("Run() err = %T %[1]v, want ExitStatus", err)
}
if status.Code() != 1 {
t.Fatalf("Run() status = %d, want 1", status.Code())
}

lines := strings.Split(strings.TrimSpace(stdout.String()), "\n")
if len(lines) < 4 {
t.Fatalf("stdout = %q, want three timing lines followed by JSON", stdout.String())
}
for i, name := range []string{"os.name", "missing_fact", "missing_fact"} {
want := regexp.MustCompile(`^fact '` + regexp.QuoteMeta(name) + `', took: \([0-9]+\.[0-9]{3}\) seconds$`)
if !want.MatchString(lines[i]) {
t.Fatalf("timing line %d = %q, want query %q", i, lines[i], name)
}
}
formatted := strings.Join(lines[3:], "\n")
var got map[string]any
if err := json.Unmarshal([]byte(formatted), &got); err != nil {
t.Fatalf("formatted output after timing lines is not JSON: %q: %v", formatted, err)
}
if got["os.name"] == nil {
t.Fatalf("formatted output = %q, want resolved os.name", formatted)
}
if value, exists := got["missing_fact"]; !exists || value != nil {
t.Fatalf("formatted output = %q, want missing_fact null", formatted)
}
if strings.Index(formatted, `"missing_fact"`) > strings.Index(formatted, `"os.name"`) {
t.Fatalf("formatted output order = %q, want missing_fact before os.name", formatted)
}
wantStderr := "ERROR Facts - fact \"missing_fact\" does not exist.\n" +
"ERROR Facts - fact \"missing_fact\" does not exist.\n"
if got := stderr.String(); got != wantStderr {
t.Fatalf("stderr = %q, want %q", got, wantStderr)
}
}

func TestRun_rejectsRemovedCustomFactOptions(t *testing.T) {
tests := []struct {
name string
Expand Down
4 changes: 0 additions & 4 deletions internal/engine/augeas.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,6 @@ func parseAugeasVersion(out string) string {
return augeasVersionPattern.FindString(out)
}

func augeasFacts(out string) []ResolvedFact {
return augeasVersionFacts(parseAugeasVersion(out))
}

// augeasVersionFacts returns the augeas fact, or nothing when no augparse
// binary produced a version: Ruby Facter omits the fact instead of emitting
// an empty version string.
Expand Down
12 changes: 3 additions & 9 deletions internal/engine/augeas_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,13 @@ import (
"testing"
)

func TestAugeasFacts_returnsStructuredVersion(t *testing.T) {
got := augeasFacts("augparse 1.14.1 <http://augeas.net/>")
func TestAugeasVersionFacts_returnsParsedVersion(t *testing.T) {
got := augeasVersionFacts(parseAugeasVersion("augparse 1.14.1 <http://augeas.net/>"))
want := []ResolvedFact{
{Name: "augeas.version", Value: "1.14.1"},
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("augeasFacts() = %#v, want %#v", got, want)
}
}

func TestAugeasFacts_skipsMissingVersion(t *testing.T) {
if got := augeasFacts(""); got != nil {
t.Fatalf("augeasFacts() = %#v, want nil", got)
t.Fatalf("augeasVersionFacts(parseAugeasVersion()) = %#v, want %#v", got, want)
}
}

Expand Down
18 changes: 0 additions & 18 deletions internal/engine/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,28 +157,10 @@ func missingFileReader(string) ([]byte, error) {
return nil, os.ErrNotExist
}

func rootedPath(root, path string) string {
if root == "/" {
return "/" + strings.TrimPrefix(path, "/")
}
return filepath.Join(root, path)
}

func (s *Session) commandOutput(name string, args ...string) string {
return s.host.run(s.ctx, name, args...)
}

func bytesToMB(value any) any {
number, ok := numericValue(value)
if !ok {
return nil
}
if number <= 0 {
return 0.0
}
return number / (1024.0 * 1024.0)
}

func bytesToHumanReadable(value any) any {
number, original, ok := byteValue(value)
if !ok {
Expand Down
1 change: 0 additions & 1 deletion internal/engine/core_benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ func BenchmarkParseMacOSSystemProfilerHardware(b *testing.B) {
func BenchmarkUnitFormatting(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
_ = bytesToMB(256_586_343)
_ = bytesToHumanReadable(1_048_575)
_ = hertzToHumanReadable(2_365_000_000)
}
Expand Down
10 changes: 1 addition & 9 deletions internal/engine/core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,7 @@ func TestPathEntries_splitsAndDropsEmpty(t *testing.T) {
}
}

func TestRootedPathAndIsSymlinkHelpers(t *testing.T) {
if got, want := rootedPath("/", "var/cache"), "/var/cache"; got != want {
t.Fatalf("rootedPath(/) = %q, want %q", got, want)
}
root := t.TempDir()
if got, want := rootedPath(root, "var/cache"), filepath.Join(root, "var/cache"); got != want {
t.Fatalf("rootedPath(temp) = %q, want %q", got, want)
}

func TestIsSymlinkHelper(t *testing.T) {
lstat := func(path string) (os.FileInfo, error) {
switch path {
case "/link":
Expand Down
7 changes: 0 additions & 7 deletions internal/engine/dmi.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,13 +188,6 @@ func freeBSDDMIFacts(values map[string]string) []ResolvedFact {
return []ResolvedFact{{Name: "dmi", Value: dmi}}
}

func dragonFlyDMIFacts(values map[string]string, biosOutput, systemOutput, chassisOutput string) []ResolvedFact {
if facts := freeBSDDMIFacts(values); len(facts) > 0 {
return facts
}
return dragonFlyDMIDecodeFacts(biosOutput, systemOutput, chassisOutput)
}

func dragonFlyDMIDecodeFacts(biosOutput, systemOutput, chassisOutput string) []ResolvedFact {
biosValues := parseColonValues(biosOutput)
systemValues := parseColonValues(systemOutput)
Expand Down
50 changes: 27 additions & 23 deletions internal/engine/dmi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,9 @@ func TestFreeBSDDMIFacts_returnsStructuredFacts(t *testing.T) {
}
}

func TestDragonFlyDMIFacts_fallsBackToDMIDecodeWhenKenvHasNoSMBIOS(t *testing.T) {
func TestCurrentDragonFlyDMIFactsFallsBackToDMIDecodeWhenKenvHasNoSMBIOS(t *testing.T) {
t.Parallel()

bios := `BIOS Information
Vendor: SeaBIOS
Version: 1.16.3-debian-1.16.3-2
Expand All @@ -295,7 +297,19 @@ func TestDragonFlyDMIFacts_fallsBackToDMIDecodeWhenKenvHasNoSMBIOS(t *testing.T)
Asset Tag: Not Specified
`

facts := dragonFlyDMIFacts(map[string]string{}, bios, system, chassis)
host := &fakeHostOS{
platform: "dragonfly",
emptyRunDefault: true,
runOutputs: map[string]string{
fakeRunKey("/usr/local/sbin/dmidecode", "-t", "bios"): bios,
fakeRunKey("/usr/local/sbin/dmidecode", "-t", "system"): system,
fakeRunKey("/usr/local/sbin/dmidecode", "-t", "chassis"): chassis,
},
}
s := NewSessionContext(t.Context())
s.host = host

facts := currentDragonFlyDMIFacts(s)
collection := Collection(facts)

want := map[string]any{
Expand All @@ -318,29 +332,19 @@ func TestDragonFlyDMIFacts_fallsBackToDMIDecodeWhenKenvHasNoSMBIOS(t *testing.T)
},
}
if !reflect.DeepEqual(collection, want) {
t.Fatalf("dragonFlyDMIFacts() = %#v, want %#v", collection, want)
}
}

func TestDragonFlyDMIFactsPrefersKenvSMBIOSValues(t *testing.T) {
values := map[string]string{
"smbios.system.maker": "DragonFly Maker",
"smbios.system.product": "DragonFly Product",
t.Fatalf("currentDragonFlyDMIFacts() = %#v, want %#v", collection, want)
}

facts := dragonFlyDMIFacts(values, "Vendor: dmidecode BIOS", "Manufacturer: dmidecode", "Type: Other")
collection := Collection(facts)

want := map[string]any{
"dmi": map[string]any{
"manufacturer": "DragonFly Maker",
"product": map[string]any{
"name": "DragonFly Product",
},
},
wantCalls := make([]fakeHostRunCall, 0, len(freeBSDDMIKeys)+3)
for _, key := range freeBSDDMIKeys {
wantCalls = append(wantCalls, fakeHostRunCall{name: "kenv", args: []string{key}})
}
if !reflect.DeepEqual(collection, want) {
t.Fatalf("dragonFlyDMIFacts() = %#v, want %#v", collection, want)
wantCalls = append(wantCalls,
fakeHostRunCall{name: "/usr/local/sbin/dmidecode", args: []string{"-t", "bios"}},
fakeHostRunCall{name: "/usr/local/sbin/dmidecode", args: []string{"-t", "system"}},
fakeHostRunCall{name: "/usr/local/sbin/dmidecode", args: []string{"-t", "chassis"}},
)
if !reflect.DeepEqual(host.runCalls, wantCalls) {
t.Fatalf("currentDragonFlyDMIFacts() run calls = %#v, want %#v", host.runCalls, wantCalls)
}
}

Expand Down
4 changes: 2 additions & 2 deletions internal/engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ func (e *Engine) Discover(ctx context.Context, queries ...string) (*Snapshot, er
facts = FilterDisabledFacts(facts, plan.disabledFacts)

if len(plan.queries) > 0 {
facts = NewProjection(facts, plan.includeTypedDotted).Select(plan.queries)
facts = NewProjection(facts, plan.includeTypedDotted).selectFacts(plan.queries)
}

if plan.useCache && ctx.Err() == nil {
Expand All @@ -258,7 +258,7 @@ func (e *Engine) Discover(ctx context.Context, queries ...string) (*Snapshot, er
}
facts = append(remaining, cached...)
if len(plan.queries) > 0 {
facts = NewProjection(facts, plan.includeTypedDotted).Select(plan.queries)
facts = NewProjection(facts, plan.includeTypedDotted).selectFacts(plan.queries)
}
}

Expand Down
36 changes: 0 additions & 36 deletions internal/engine/factsutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package engine

import (
"fmt"
"strconv"
"strings"
)

Expand Down Expand Up @@ -73,41 +72,6 @@ func releaseHashFromString(version string, includePatch bool) map[string]any {
return release
}

func releaseHashFromMatchData(match []string) map[string]any {
if len(match) < 2 {
return nil
}
return releaseHashFromString(match[1], false)
}

func tryToBool(value string) any {
switch value {
case "true":
return true
case "false":
return false
default:
return value
}
}

func tryToInt(value any) any {
switch v := value.(type) {
case int:
return v
case float64:
return int(v)
case string:
parsed, err := strconv.Atoi(v)
if err != nil {
return v
}
return parsed
default:
return value
}
}

func deepStringifyKeys(value any) any {
switch v := value.(type) {
case map[any]any:
Expand Down
Loading
Loading