Documentation
¶
Overview ¶
Package tomlsawyer provides comment-preserving TOML parsing and serialization.
This package wraps github.com/creachadair/tomledit to provide a stable, user-friendly API for reading, modifying, and writing TOML files while preserving comments, declaration order, and structural style choices (dotted keys vs sections, quote styles). Whitespace layout may be normalized.
Path Syntax ¶
All methods that accept a path parameter use TOML dotted-key syntax: simple keys like "name", nested keys like "server.host", and quoted keys for special characters like aliases."." or section."key with spaces". Paths are parsed using TOML's own key grammar, so any valid TOML key works as a path segment when quoted. Invalid paths like "foo." (trailing dot) or ".foo" (leading dot) are rejected.
Path segments and raw key names are different things. A path like aliases."." has two segments (aliases and .). The Document.Keys method returns raw key names, not paths.
Example usage:
doc, err := tomlsawyer.Parse([]byte(`
# This is a comment
[server]
host = "localhost"
port = 8080
`))
if err != nil {
log.Fatal(err)
}
// Modify a value
doc.Set("server.port", 9090)
// Use quoted keys for special characters
doc.Set(`aliases."."`, "status")
// Write back with comments preserved
output := doc.String()
Index ¶
- Variables
- func FormatValueToString(v any) (string, error)
- func WriteFile(path string, values map[string]any) error
- type Document
- func (d *Document) ApplyMap(values map[string]any) error
- func (d *Document) Bytes() []byte
- func (d *Document) Delete(path string) error
- func (d *Document) Get(path string) (any, bool, error)
- func (d *Document) Has(path string) (bool, error)
- func (d *Document) Keys(path string) ([]string, error)
- func (d *Document) Move(oldPath, newPath string) error
- func (d *Document) Prune()
- func (d *Document) ReplaceMap(values map[string]any) error
- func (d *Document) Set(path string, value any) error
- func (d *Document) String() string
- func (d *Document) TopLevelKeys() []string
- type KeyValue
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrNotValue = errors.New("path refers to a table section, not a value")
ErrNotValue is returned by Get when the path refers to a table section rather than a key-value entry.
Functions ¶
func FormatValueToString ¶
FormatValueToString converts a Go value into a TOML value string. This is useful for displaying values in a TOML-compatible format.
Types ¶
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document represents a parsed TOML document with preserved structure, including comments, formatting, and declaration order.
func Parse ¶
Parse parses a TOML document from bytes and returns a Document that preserves all structural information including comments.
func ParseString ¶
ParseString is a convenience wrapper around Parse that accepts a string.
func (*Document) ApplyMap ¶
ApplyMap merges the provided nested map into the document, preserving any existing keys that are not present in values. This allows partial updates without affecting unmanaged configuration.
Example ¶
package main
import (
"fmt"
"github.com/neongreen/tomlsawyer"
)
func main() {
doc, _ := tomlsawyer.ParseString(`name = "myapp"
version = "1.0"
`)
doc.ApplyMap(map[string]any{
"version": "2.0",
"author": "Alice",
})
fmt.Print(doc.String())
}
Output: name = "myapp" version = "2.0" author = "Alice"
func (*Document) Delete ¶
Delete removes a key at the given path. Returns nil if the path doesn't exist.
Path syntax is the same as Document.Get.
func (*Document) Get ¶
Get retrieves a value at the given path. Returns (value, true, nil) when the path exists and is a key-value entry, (nil, false, nil) when the path doesn't exist, and (nil, false, ErrNotValue) when the path refers to a table section.
The path uses TOML dotted-key syntax: segments are separated by dots. Use quoted segments for keys containing special characters:
doc.Get("server.host") // key "host" under section "server"
doc.Get(`aliases."."`) // key "." under section "aliases"
Example ¶
package main
import (
"fmt"
"github.com/neongreen/tomlsawyer"
)
func main() {
doc, _ := tomlsawyer.ParseString(`
[server]
host = "localhost"
port = 8080
`)
host, _, _ := doc.Get("server.host")
fmt.Println(host)
}
Output: localhost
func (*Document) Has ¶
Has reports whether the given path exists in the document. This includes key-value entries, table sections, and dotted key prefixes. Parse errors (e.g. invalid paths like "foo.") are returned as the second value.
Path syntax is the same as Document.Get.
Example ¶
package main
import (
"fmt"
"github.com/neongreen/tomlsawyer"
)
func main() {
doc, _ := tomlsawyer.ParseString(`
[server]
host = "localhost"
`)
h1, _ := doc.Has("server")
h2, _ := doc.Has("server.host")
h3, _ := doc.Has("nonexistent")
fmt.Println(h1)
fmt.Println(h2)
fmt.Println(h3)
}
Output: true true false
func (*Document) Keys ¶
Keys returns the child key names under the given path. For a table section like [foo], it returns the keys defined in that section. For an inline table value, it returns the keys of that inline table. Returns nil if the path doesn't exist or has no children.
Keys are returned in document order. For inline tables, this is the order they appear in the source. For Go maps passed to Set or FormatValueToString, keys are sorted alphabetically since Go maps have no inherent order.
The returned names are raw key names, not paths. For example, Keys("aliases") might return [".", "..", "l"] where "." is a literal key name containing a dot.
Path syntax is the same as Document.Get.
Example ¶
package main
import (
"fmt"
"github.com/neongreen/tomlsawyer"
)
func main() {
doc, _ := tomlsawyer.ParseString(`
[users]
alice = { role = "admin" }
bob = { role = "user" }
`)
keys, _ := doc.Keys("users")
fmt.Println(keys)
}
Output: [alice bob]
Example (QuotedKeys) ¶
package main
import (
"fmt"
"github.com/neongreen/tomlsawyer"
)
func main() {
doc, _ := tomlsawyer.ParseString(`
[aliases]
"." = "status"
".." = "show @-"
l = "log"
`)
keys, _ := doc.Keys("aliases")
for _, k := range keys {
val, _, _ := doc.Get(fmt.Sprintf(`aliases."%s"`, k))
fmt.Printf("%s = %s\n", k, val)
}
}
Output: . = status .. = show @- l = log
func (*Document) Move ¶
Move renames or moves a section or key, like Unix mv. Both oldPath and newPath use the same path syntax as Document.Get.
For sections, child sections are also renamed (e.g. moving "foo.bar" to "foo.qux" also renames "foo.bar.baz" to "foo.qux.baz"). Comments, formatting, and position are preserved.
For key-value entries within the same section (e.g. "server.host" to "server.addr"), the key is renamed in place. For cross-section moves (e.g. "server.host" to "app.host"), the key is removed from the source section and inserted into the destination, creating it if needed. Block comments and inline comments on the key are preserved.
Example ¶
package main
import (
"fmt"
"github.com/neongreen/tomlsawyer"
)
func main() {
doc, _ := tomlsawyer.ParseString(`
[server]
host = "localhost"
port = 8080
`)
doc.Move("server", "app.server")
fmt.Print(doc.String())
}
Output: [app.server] host = "localhost" port = 8080
Example (CrossSection) ¶
package main
import (
"fmt"
"github.com/neongreen/tomlsawyer"
)
func main() {
doc, _ := tomlsawyer.ParseString(`
[old]
timeout = 30
[new]
host = "localhost"
`)
doc.Move("old.timeout", "new.timeout")
doc.Prune() // remove empty [old] section
fmt.Print(doc.String())
}
Output: [new] host = "localhost" timeout = 30
func (*Document) Prune ¶
func (d *Document) Prune()
Prune removes empty sections from the document. A section is considered empty if it contains no key-value items (comments-only sections are also removed). This is useful after Delete or Move operations that may leave behind stale section headers.
func (*Document) ReplaceMap ¶
ReplaceMap updates the document with the provided nested map and removes any keys that are not present in values. Use ApplyMap instead if you want to preserve unmanaged keys.
func (*Document) Set ¶
Set sets a value at the given path, creating intermediate sections if necessary. The value can be a string, int, float64, bool, or []interface{}. This method preserves the original style (dotted keys vs sections, quote styles).
Path syntax is the same as Document.Get.
Example ¶
package main
import (
"fmt"
"github.com/neongreen/tomlsawyer"
)
func main() {
doc, _ := tomlsawyer.ParseString(`
[server]
host = "localhost"
port = 8080
`)
doc.Set("server.port", 9090)
fmt.Print(doc.String())
}
Output: [server] host = "localhost" port = 9090
func (*Document) String ¶
String serializes the document back to TOML format, preserving all comments, formatting, and declaration order.
func (*Document) TopLevelKeys ¶
TopLevelKeys returns all top-level key names in the document, deduplicated and in document order. The returned strings are raw key names (not paths).
Example ¶
package main
import (
"fmt"
"github.com/neongreen/tomlsawyer"
)
func main() {
doc, _ := tomlsawyer.ParseString(`
name = "myapp"
version = 1
[server]
host = "localhost"
[database]
url = "postgres://localhost"
`)
keys := doc.TopLevelKeys()
fmt.Println(keys)
}
Output: [name version server database]
type KeyValue ¶
KeyValue represents an ordered key-value pair for use in inline tables. Pass []KeyValue to Document.Set or FormatValueToString to control the output order of inline table keys. For unordered input, map[string]any is also accepted (keys will be sorted alphabetically).