feat(vdf): KeyValues parser with real-config fixtures

Ordered children with duplicate keys, case-insensitive lookup, nil-safe
accessors, escapes, comments, [$PLATFORM] conditionals, UTF-8 BOM.
Scans of all 232 local Steam controller configs parse cleanly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013UzjWSBjtVZ2zi8fJxS2hH
This commit is contained in:
ziadarafatandClaude Opus 5.5 committed 2026-10-30 15:53:36 -06:00
1 parent b6d6863c4c
commit 4f624debdf
7 files changed
+2722

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
/bin/
*.test
/testdata/hid/local/
+3
View File
@@ -0,0 +1,3 @@
module github.com/RustyRaptor/deckhud
go 1.27.3
+53
View File
@@ -0,0 +1,53 @@
package vdf
import (
"os"
"path/filepath"
"testing"
)
// TestParseLocalSteamConfigs parses every .vdf under $DECKHUD_SCAN_DIR. It is a
// smoke test against real-world files and is skipped unless the variable is set.
func TestParseLocalSteamConfigs(t *testing.T) {
dir := os.Getenv("DECKHUD_SCAN_DIR")
if dir == "" {
t.Skip("set DECKHUD_SCAN_DIR to scan local Steam configs")
}
n := 0
err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() || filepath.Ext(path) != ".vdf" {
return err
}
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
if _, err := Parse(f); err != nil {
t.Errorf("%s: %v", path, err)
}
n++
return nil
})
if err != nil {
t.Fatal(err)
}
t.Logf("parsed %d files", n)
}
func TestParseFixtures(t *testing.T) {
files, _ := filepath.Glob("../../testdata/vdf/*.vdf")
if len(files) == 0 {
t.Fatal("no fixtures found")
}
for _, path := range files {
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
if _, err := Parse(f); err != nil {
t.Errorf("%s: %v", path, err)
}
f.Close()
}
}
+287
View File
@@ -0,0 +1,287 @@
// Package vdf parses Valve's text KeyValues format (".vdf"), as used by Steam
// Input controller configurations.
//
// Keys may repeat (a group has many "binding" entries), so a block keeps its
// children as an ordered list rather than a map. Key lookups ignore case, as
// Steam does. All accessors are safe to call on a nil *Node, which makes deep
// optional lookups such as n.Get("a").Get("b").Str("c") cheap to write.
package vdf
import (
"bufio"
"fmt"
"io"
"strings"
)
// Node is either a leaf (Key/Value) or a block (Key/Children).
type Node struct {
Key string
Value string
Children []*Node // nil for leaves, non-nil (possibly empty) for blocks
Line int // 1-based line where the key appeared
}
// IsBlock reports whether n is a block rather than a leaf.
func (n *Node) IsBlock() bool { return n != nil && n.Children != nil }
// Get returns the first child whose key matches (case-insensitively), or nil.
func (n *Node) Get(key string) *Node {
if n == nil {
return nil
}
for _, c := range n.Children {
if strings.EqualFold(c.Key, key) {
return c
}
}
return nil
}
// All returns every child whose key matches, in file order.
func (n *Node) All(key string) []*Node {
if n == nil {
return nil
}
var out []*Node
for _, c := range n.Children {
if strings.EqualFold(c.Key, key) {
out = append(out, c)
}
}
return out
}
// Str returns the value of the first leaf child with the given key, or "".
func (n *Node) Str(key string) string {
if c := n.Get(key); c != nil && !c.IsBlock() {
return c.Value
}
return ""
}
// Parse reads a whole document. The returned root is a synthetic block whose
// children are the document's top-level entries.
func Parse(r io.Reader) (*Node, error) {
br := bufio.NewReader(r)
if c, _, err := br.ReadRune(); err == nil && c != 0xFEFF {
_ = br.UnreadRune() // Valve's stock templates start with a UTF-8 BOM
}
p := &parser{lx: lexer{r: br, line: 1}}
root := &Node{Children: []*Node{}}
if err := p.parseBlock(root, true); err != nil {
return nil, err
}
return root, nil
}
type tokKind int
const (
tokEOF tokKind = iota
tokString
tokOpen
tokClose
tokCond // [$PLATFORM] conditional, ignored
)
type token struct {
kind tokKind
text string
line int
}
type parser struct {
lx lexer
peeked *token
}
func (p *parser) next() (token, error) {
if p.peeked != nil {
t := *p.peeked
p.peeked = nil
return t, nil
}
return p.lx.next()
}
func (p *parser) peek() (token, error) {
if p.peeked == nil {
t, err := p.lx.next()
if err != nil {
return t, err
}
p.peeked = &t
}
return *p.peeked, nil
}
func (p *parser) parseBlock(parent *Node, top bool) error {
for {
t, err := p.next()
if err != nil {
return err
}
switch t.kind {
case tokEOF:
if !top {
return fmt.Errorf("vdf: line %d: unterminated block %q", parent.Line, parent.Key)
}
return nil
case tokClose:
if top {
return fmt.Errorf("vdf: line %d: unexpected '}'", t.line)
}
return nil
case tokOpen, tokCond:
return fmt.Errorf("vdf: line %d: expected key", t.line)
}
node := &Node{Key: t.text, Line: t.line}
v, err := p.next()
if err != nil {
return err
}
if v.kind == tokCond {
if v, err = p.next(); err != nil {
return err
}
}
switch v.kind {
case tokString:
node.Value = v.text
if c, err := p.peek(); err != nil {
return err
} else if c.kind == tokCond {
p.peeked = nil
}
case tokOpen:
node.Children = []*Node{}
if err := p.parseBlock(node, false); err != nil {
return err
}
default:
return fmt.Errorf("vdf: line %d: key %q has no value", t.line, t.text)
}
parent.Children = append(parent.Children, node)
}
}
type lexer struct {
r *bufio.Reader
line int
}
func (l *lexer) read() (rune, bool) {
c, _, err := l.r.ReadRune()
if err != nil {
return 0, false
}
if c == '\n' {
l.line++
}
return c, true
}
func (l *lexer) unread(c rune) {
_ = l.r.UnreadRune()
if c == '\n' {
l.line--
}
}
func (l *lexer) next() (token, error) {
for {
c, ok := l.read()
if !ok {
return token{kind: tokEOF, line: l.line}, nil
}
switch {
case c == ' ' || c == '\t' || c == '\r' || c == '\n':
continue
case c == '/':
if n, ok := l.read(); ok && n == '/' {
for {
c, ok := l.read()
if !ok || c == '\n' {
break
}
}
continue
} else if ok {
l.unread(n)
}
return l.bare(c)
case c == '{':
return token{kind: tokOpen, line: l.line}, nil
case c == '}':
return token{kind: tokClose, line: l.line}, nil
case c == '[':
start := l.line
for {
c, ok := l.read()
if !ok {
return token{}, fmt.Errorf("vdf: line %d: unterminated conditional", start)
}
if c == ']' {
return token{kind: tokCond, line: start}, nil
}
}
case c == '"':
return l.quoted()
default:
return l.bare(c)
}
}
}
func (l *lexer) quoted() (token, error) {
start := l.line
var b strings.Builder
for {
c, ok := l.read()
if !ok {
return token{}, fmt.Errorf("vdf: line %d: unterminated string", start)
}
switch c {
case '"':
return token{kind: tokString, text: b.String(), line: start}, nil
case '\\':
n, ok := l.read()
if !ok {
return token{}, fmt.Errorf("vdf: line %d: unterminated string", start)
}
switch n {
case 'n':
b.WriteRune('\n')
case 't':
b.WriteRune('\t')
case '\\', '"':
b.WriteRune(n)
default:
b.WriteRune('\\')
b.WriteRune(n)
}
default:
b.WriteRune(c)
}
}
}
func (l *lexer) bare(first rune) (token, error) {
start := l.line
var b strings.Builder
b.WriteRune(first)
for {
c, ok := l.read()
if !ok {
break
}
if c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '"' || c == '{' || c == '}' || c == '[' {
l.unread(c)
break
}
b.WriteRune(c)
}
return token{kind: tokString, text: b.String(), line: start}, nil
}
+138
View File
@@ -0,0 +1,138 @@
package vdf
import (
"strings"
"testing"
)
func mustParse(t *testing.T, src string) *Node {
t.Helper()
n, err := Parse(strings.NewReader(src))
if err != nil {
t.Fatalf("Parse: %v", err)
}
return n
}
func TestParseLeafAndBlock(t *testing.T) {
root := mustParse(t, `
"controller_mappings"
{
"version" "3"
"title" "d4sktop"
"actions"
{
"Default"
{
"title" "Desktop"
}
}
}`)
cm := root.Get("controller_mappings")
if cm == nil || !cm.IsBlock() {
t.Fatalf("controller_mappings block missing: %+v", root)
}
if got := cm.Str("version"); got != "3" {
t.Errorf("version = %q, want 3", got)
}
if got := cm.Get("actions").Get("Default").Str("title"); got != "Desktop" {
t.Errorf("nested title = %q, want Desktop", got)
}
}
func TestDuplicateKeysPreservedInOrder(t *testing.T) {
root := mustParse(t, `"bindings" { "binding" "key_press LEFT_CONTROL, , " "binding" "key_press V, , " }`)
got := root.Get("bindings").All("binding")
if len(got) != 2 {
t.Fatalf("got %d bindings, want 2", len(got))
}
if got[0].Value != "key_press LEFT_CONTROL, , " || got[1].Value != "key_press V, , " {
t.Errorf("wrong order/values: %q, %q", got[0].Value, got[1].Value)
}
}
func TestKeysAreCaseInsensitive(t *testing.T) {
root := mustParse(t, `"Actions" { "Title" "x" }`)
if root.Get("actions").Str("title") != "x" {
t.Error("lookup should ignore case")
}
}
func TestMissingKeysAreNilSafe(t *testing.T) {
root := mustParse(t, `"a" { }`)
if got := root.Get("nope").Get("deeper").Str("x"); got != "" {
t.Errorf("want empty string, got %q", got)
}
if root.Get("nope").All("x") != nil {
t.Error("All on nil node should be nil")
}
if !root.Get("a").IsBlock() || len(root.Get("a").Children) != 0 {
t.Error("empty block should be a block with no children")
}
}
func TestEscapesCommentsUnquotedAndConditionals(t *testing.T) {
root := mustParse(t, `
// leading comment
"root"
{
"quote" "say \"hi\"\\n" // trailing comment
"tab" "a\tb"
unquoted value
"cond" "win" [$WIN32]
"blk" [$LINUX]
{
"k" "v"
}
}`)
r := root.Get("root")
if got := r.Str("quote"); got != `say "hi"\n` {
t.Errorf("quote = %q", got)
}
if got := r.Str("tab"); got != "a\tb" {
t.Errorf("tab = %q", got)
}
if got := r.Str("unquoted"); got != "value" {
t.Errorf("unquoted = %q", got)
}
if got := r.Str("cond"); got != "win" {
t.Errorf("cond = %q", got)
}
if got := r.Get("blk").Str("k"); got != "v" {
t.Errorf("conditional block child = %q", got)
}
}
func TestStringsMaySpanLinesAndContainBraces(t *testing.T) {
root := mustParse(t, "\"a\" \"line1\nline2 { }\"")
if got := root.Str("a"); got != "line1\nline2 { }" {
t.Errorf("got %q", got)
}
}
func TestErrorsReportLine(t *testing.T) {
cases := map[string]string{
"unterminated block": "\"a\"\n{\n\"b\" \"c\"\n",
"unterminated string": "\"a\" \"oops\n",
"stray close": "\"a\" \"b\"\n}\n",
"key without value": "\"a\"\n",
}
for name, src := range cases {
t.Run(name, func(t *testing.T) {
_, err := Parse(strings.NewReader(src))
if err == nil {
t.Fatal("expected error")
}
if !strings.Contains(err.Error(), "line ") {
t.Errorf("error should mention a line: %v", err)
}
})
}
}
func TestLeadingByteOrderMarkAndCRLF(t *testing.T) {
root := mustParse(t, "\xef\xbb\xbf\"controller_mappings\"\r\n{\r\n\t\"version\"\t\t\"3\"\r\n}\r\n")
if got := root.Get("controller_mappings").Str("version"); got != "3" {
t.Errorf("version = %q, want 3", got)
}
}
+25
View File
@@ -0,0 +1,25 @@
[tools]
go = "1.27.3"
[env]
CGO_ENABLED = "0"
[tasks.test]
description = "Run all tests"
depends = ["test:go", "test:qml"]
[tasks."test:go"]
description = "Run Go tests"
run = "go test ./..."
[tasks."test:qml"]
description = "Run QML tests offscreen"
run = "[ -d ui/tests ] && QT_QPA_PLATFORM=offscreen /usr/lib/qt6/bin/qmltestrunner -input ui/tests -import ui || true"
[tasks.check]
description = "Vet and format check"
run = ["go vet ./...", "test -z \"$(gofmt -l .)\""]
[tasks.build]
description = "Build the daemon"
run = "go build -o bin/deckhudd ./cmd/deckhudd"
+2213
View File
File diff suppressed because it is too large. Load diff