### Apply a sequence of named transformation steps with transform.Plan Source: https://context7.com/creachadair/tomledit/llms.txt Use transform.Plan to apply a series of transformations sequentially. Attach an io.Writer via transform.WithLogWriter to receive per-step log output. The first failure aborts the plan. ```go package main import ( "context" "log" "os" "strings" "github.com/creachadair/tomledit" "github.com/creachadair/tomledit/parser" "github.com/creachadair/tomledit/transform" ) func main() { doc, err := tomledit.Parse(strings.NewReader(` [alpha_bravo] charlie_delta = "echo" golf = 0 [stale] data = "remove me" `)) if err != nil { log.Fatal(err) } ctx := transform.WithLogWriter(context.Background(), os.Stderr) plan := transform.Plan{ { Desc: "Convert snake_case keys to kebab-case", T: transform.SnakeToKebab(), }, { Desc: "Ensure a required key exists", T: transform.EnsureKey( parser.Key{"alpha-bravo"}, &parser.KeyValue{ Name: parser.Key{"timeout"}, Value: parser.MustValue("30").WithComment("seconds"), }, ), }, { Desc: "Remove optional legacy section (ok if missing)", T: transform.Remove(parser.Key{"stale"}), ErrorOK: false, }, } if err := plan.Apply(ctx, doc); err != nil { log.Fatalf("Plan failed: %v", err) } tomledit.Format(os.Stdout, doc) // Output: // [alpha-bravo] // charlie-delta = "echo" // golf = 0 // timeout = 30 # seconds } ``` -------------------------------- ### Key comparison and ordering for parser.Key Source: https://context7.com/creachadair/tomledit/llms.txt The `parser.Key` type, an alias for `[]string`, provides methods like `Equals`, `IsPrefixOf`, and `Before` for comparing and lexicographically ordering TOML keys. Keys can also be constructed programmatically. ```go root, _ := parser.ParseKey("server") child, _ := parser.ParseKey("server.tls.cert") other, _ := parser.ParseKey("client") fmt.Println(root.IsPrefixOf(child)) // true fmt.Println(root.IsPrefixOf(other)) // false fmt.Println(root.Equals(child)) // false fmt.Println(other.Before(root)) // true ("client" < "server") // Build a key programmatically (no parsing needed): manual := parser.Key{"database", "pool", "size"} fmt.Println(manual.String()) // database.pool.size ``` -------------------------------- ### parser.Key methods Source: https://context7.com/creachadair/tomledit/llms.txt Key comparison and ordering. `parser.Key` (alias for `[]string`) provides `Equals`, `IsPrefixOf`, and `Before` methods for comparing and ordering dotted TOML keys lexicographically. ```APIDOC ## parser.Key methods — Key comparison and ordering `parser.Key` (alias for `[]string`) provides `Equals`, `IsPrefixOf`, and `Before` methods for comparing and ordering dotted TOML keys lexicographically. ### Example ```go root, _ := parser.ParseKey("server") child, _ := parser.ParseKey("server.tls.cert") other, _ := parser.ParseKey("client") fmt.Println(root.IsPrefixOf(child)) // true fmt.Println(root.IsPrefixOf(other)) // false fmt.Println(root.Equals(child)) // false fmt.Println(other.Before(root)) // true ("client" < "server") // Build a key programmatically (no parsing needed): manual := parser.Key{"database", "pool", "size"} fmt.Println(manual.String()) // database.pool.size ``` ``` -------------------------------- ### transform.Plan.Apply Source: https://context7.com/creachadair/tomledit/llms.txt Applies a sequence of named transformation steps to a TOML document. The plan executes each step in order, and the first failure aborts the entire plan unless the step is configured to ignore errors. ```APIDOC ## transform.Plan.Apply — Apply a sequence of named transformation steps A `Plan` is an ordered slice of `Step` values, each wrapping an `Applier` with a human-readable description. Calling `Apply` runs each step in order; the first failure aborts the plan. Steps with `ErrorOK: true` have their errors silently ignored. Attach an `io.Writer` via `transform.WithLogWriter` to receive per-step log output. ### Method Apply ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go ctx := transform.WithLogWriter(context.Background(), os.Stderr) plan := transform.Plan{ { Desc: "Convert snake_case keys to kebab-case", T: transform.SnakeToKebab(), }, { Desc: "Ensure a required key exists", T: transform.EnsureKey( parser.Key{"alpha-bravo"}, &parser.KeyValue{ Name: parser.Key{"timeout"}, Value: parser.MustValue("30").WithComment("seconds"), }, ), }, { Desc: "Remove optional legacy section (ok if missing)", T: transform.Remove(parser.Key{"stale"}), ErrorOK: false, }, } if err := plan.Apply(ctx, doc); err != nil { log.Fatalf("Plan failed: %v", err) } ``` ### Response #### Success Response (200) None explicitly defined, but the document is modified in place. #### Response Example None ``` -------------------------------- ### Format TOML Document with tomledit Source: https://context7.com/creachadair/tomledit/llms.txt Use `tomledit.Format` or `tomledit.Formatter` to serialize a `*Document` back to an `io.Writer` as TOML text. This process preserves all comments, values, and structure. Values can be modified in-place before formatting. ```Go package main import ( "log" "os" "strings" "github.com/creachadair/tomledit" "github.com/creachadair/tomledit/parser" ) func main() { doc, err := tomledit.Parse(strings.NewReader(`# A b='c' [q."r"] # D e.f=true g=false # h i={j=1,k=2} # L `)) if err != nil { log.Fatal(err) } // Modify a value in-place before writing. if entry := doc.First("q", "r", "g"); entry != nil { entry.KeyValue.Value = parser.MustValue("true") } // Write back to stdout using the package-level helper. if err := tomledit.Format(os.Stdout, doc); err != nil { log.Fatalf("Format: %v", err) } // Output: // # A // b = 'c' // // [q.r] // // # D // e.f = true // g = true // // # h // i = {j = 1, k = 2} # L // Using Formatter explicitly (same options for now, zero value is default): var fmt tomledit.Formatter if err := fmt.Format(os.Stdout, doc); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Move a key-value mapping with transform.MoveKey Source: https://context7.com/creachadair/tomledit/llms.txt Use transform.MoveKey to relocate a key-value mapping from one section to another. The target section must exist, and the key is appended under a new name within that section. ```go doc, _ := tomledit.Parse(strings.NewReader(` [source] migrate_me = "value" stay = 42 [destination] existing = true `)) transform.MoveKey( parser.Key{"source", "migrate_me"}, // from parser.Key{"destination"}, // into this section parser.Key{"arrived"}, // under this new name ).Apply(context.Background(), doc) tomledit.Format(os.Stdout, doc) // Output: // [source] // stay = 42 // // [destination] // existing = true // arrived = "value" ``` -------------------------------- ### Walk all key-value entries in definition order Source: https://context7.com/creachadair/tomledit/llms.txt The `Document.Scan` method traverses all key-value pairs and section headers, including those in inline tables. The provided callback function can stop the traversal by returning `false`. ```go doc, _ := tomledit.Parse(strings.NewReader(` enabled = true [network] host = "example.com" ports = [80, 443] options = {tls = true, verify = false} `)) doc.Scan(func(key parser.Key, e *tomledit.Entry) bool { switch { case e.IsSection(): log.Printf("[section] %s", key) case e.IsInline(): log.Printf(" [inline] %s = %s", key, e.KeyValue.Value) default: log.Printf(" [kv] %s = %s", key, e.KeyValue.Value) } return true }) // Output: // [kv] enabled = true // [section] network // [kv] network.host = "example.com" // [kv] network.ports = [80, 443] // [kv] network.options = {tls = true, verify = false} // [inline] network.options.tls = true // [inline] network.options.verify = false ``` -------------------------------- ### Find and Mutate TOML Entry with Document.First Source: https://context7.com/creachadair/tomledit/llms.txt Use `doc.First` to locate a specific TOML entry by its key components. The returned `*Entry` is mutable, allowing direct modification of its value and associated comments. ```Go doc, _ := tomledit.Parse(strings.NewReader(` [server] host = "0.0.0.0" port = 8080 # default port `)) // Find and update a scalar value. entry := doc.First("server", "port") if entry == nil { log.Fatal("key not found") } // Replace value and attach a comment. entry.KeyValue.Value = parser.MustValue("9090").WithComment("overridden") tomledit.Format(os.Stdout, doc) // Output: // [server] // host = "0.0.0.0" // port = 9090 # overridden ``` -------------------------------- ### Find all entries matching a key Source: https://context7.com/creachadair/tomledit/llms.txt Use `Document.Find` to retrieve all `*Entry` values that match a given key. This is particularly useful for TOML array-of-tables where keys can be repeated. ```go doc, _ := tomledit.Parse(strings.NewReader(` [[plugin]] name = "alpha" [[plugin]] name = "beta" [[plugin]] name = "gamma" `)) entries := doc.Find("plugin") for i, e := range entries { log.Printf("plugin[%d]: heading=%s", i, e.Section.Heading) } // Output: // plugin[0]: heading=[[plugin]] // plugin[1]: heading=[[plugin]] // plugin[2]: heading=[[plugin]] ``` -------------------------------- ### Conditionally Insert Key-Value Pair with EnsureKey Source: https://context7.com/creachadair/tomledit/llms.txt Use EnsureKey to insert a key-value pair into a TOML table only if the key does not already exist. It returns an error if the target table is not found. Pass `replace=true` to InsertMapping for unconditional updates. ```go doc, _ := tomledit.Parse(strings.NewReader(` [config] existing = "leave me alone" `)) // Will NOT overwrite "existing". transform.EnsureKey( parser.Key{"config"}, &parser.KeyValue{ Name: parser.Key{"existing"}, Value: parser.MustValue(`"overwritten"`), }, ).Apply(context.Background(), doc) // WILL add "new_key" because it is absent. transform.EnsureKey( parser.Key{"config"}, &parser.KeyValue{ Block: parser.Comments{"added by migration"}, Name: parser.Key{"new_key"}, Value: parser.MustValue("true"), }, ).Apply(context.Background(), doc) tomledit.Format(os.Stdout, doc) ``` -------------------------------- ### Document.First Source: https://context7.com/creachadair/tomledit/llms.txt Looks up the first entry in the document matching a given key. Returns a pointer to the `*Entry` which can be directly mutated. Useful for finding and modifying specific values. ```APIDOC ## Document.First ### Description Looks up the first entry in the document whose full dotted key equals the given key components, or `nil` if not found. Entries are returned for both section headers and key-value mappings. The returned entry is directly mutable. ### Method `doc.First(keys ...string) *Entry` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go import ( "os" "strings" "github.com/creachadair/tomledit" "github.com/creachadair/tomledit/parser" ) doc, _ := tomledit.Parse(strings.NewReader(`[server]\nport = 8080`)) entry := doc.First("server", "port") if entry != nil { entry.KeyValue.Value = parser.MustValue("9090").WithComment("overridden") } tomledit.Format(os.Stdout, doc) ``` ### Response #### Success Response (200) - **entry** (*Entry) - A pointer to the found entry, or `nil` if not found. #### Response Example ```toml [server] port = 9090 # overridden ``` ``` -------------------------------- ### Document.Scan Source: https://context7.com/creachadair/tomledit/llms.txt Walk all key-value entries in definition order. Calls the provided callback for every key-value pair and every section header in the document, traversing inline tables recursively. Returning `false` from the callback stops the walk early. Scan returns `true` if the walk completed, `false` if it was stopped. ```APIDOC ## Document.Scan — Walk all key-value entries in definition order Calls the provided callback for every key-value pair and every section header in the document, traversing inline tables recursively. Returning `false` from the callback stops the walk early. Scan returns `true` if the walk completed, `false` if it was stopped. ### Example ```go doc, _ := tomledit.Parse(strings.NewReader(` enabled = true [network] host = "example.com" ports = [80, 443] options = {tls = true, verify = false} `)) doc.Scan(func(key parser.Key, e *tomledit.Entry) bool { switch { case e.IsSection(): log.Printf("[section] %s", key) case e.IsInline(): log.Printf(" [inline] %s = %s", key, e.KeyValue.Value) default: log.Printf(" [kv] %s = %s", key, e.KeyValue.Value) } return true }) // Output: // [kv] enabled = true // [section] network // [kv] network.host = "example.com" // [kv] network.ports = [80, 443] // [kv] network.options = {tls = true, verify = false} // [inline] network.options.tls = true // [inline] network.options.verify = false ``` ``` -------------------------------- ### Parse TOML from Reader with tomledit Source: https://context7.com/creachadair/tomledit/llms.txt Use `tomledit.Parse` to read TOML text from an `io.Reader`. It preserves comments, key order, and formatting but does not validate TOML semantics. The `Scan` method can be used to iterate over key-value pairs. ```Go package main import ( "log" "os" "strings" "github.com/creachadair/tomledit" "github.com/creachadair/tomledit/parser" ) func main() { input := ` # Application configuration title = "My App" [database] host = "localhost" # primary host port = 5432 enabled = true [database.pool] max_size = 10 min_size = 2 ` doc, err := tomledit.Parse(strings.NewReader(input)) if err != nil { log.Fatalf("Parse: %v", err) } // Walk all key-value pairs in definition order. doc.Scan(func(key parser.Key, e *tomledit.Entry) bool { if e.IsMapping() { log.Printf("key=%s value=%s", key, e.KeyValue.Value) } return true // return false to stop early }) // Output (abridged): // key=title value="My App" // key=database.host value="localhost" // key=database.port value=5432 // key=database.enabled value=true // key=database.pool.max_size value=10 // key=database.pool.min_size value=2 // Parse from a real file: f, err := os.Open("config.toml") if err != nil { log.Fatal(err) } defer f.Close() doc2, err := tomledit.Parse(f) if err != nil { log.Fatalf("Parse file: %v", err) } _ = doc2 } ``` -------------------------------- ### transform.MoveKey Source: https://context7.com/creachadair/tomledit/llms.txt Moves a key-value mapping from its original location to a specified target section within the TOML document. The target section must exist, and the key will be appended to it under a new name. ```APIDOC ## transform.MoveKey — Move a key-value mapping to a different section Removes the mapping at `oldKey` from its current location and appends it (under `newKey`) to the section identified by `rootKey`. The target section must already exist. ### Method Apply ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go transform.MoveKey( parser.Key{"source", "migrate_me"}, // from parser.Key{"destination"}, // into this section parser.Key{"arrived"}, // under this new name ).Apply(context.Background(), doc) ``` ### Response #### Success Response (200) None explicitly defined, but the document is modified in place. #### Response Example None ``` -------------------------------- ### Parse a dotted TOML key from a string Source: https://context7.com/creachadair/tomledit/llms.txt Use `parser.ParseKey` to convert a string representation of a TOML key (e.g., `"a.b.c"`) into a `parser.Key` type, which is an alias for `[]string`. It returns an error for invalid key formats. ```go key, err := parser.ParseKey(`database.pool.max_size`) if err != nil { log.Fatal(err) } fmt.Println(key) // [database pool max_size] fmt.Println(key.String()) // database.pool.max_size // Quoted segments: key2, _ := parser.ParseKey(`"my app".settings`) fmt.Println(key2) // [my app settings] // Key comparison: a, _ := parser.ParseKey("a.b") b, _ := parser.ParseKey("a.b.c") fmt.Println(a.IsPrefixOf(b)) // true fmt.Println(a.Equals(b)) // false ``` -------------------------------- ### tomledit.Format / tomledit.Formatter Source: https://context7.com/creachadair/tomledit/llms.txt Serializes a *Document back to TOML text, writing it to an io.Writer. Preserves all comments, values, and structure. Can be used via the convenience function `Format` or by instantiating a `Formatter`. ```APIDOC ## tomledit.Format / tomledit.Formatter ### Description Writes a `*Document` back to an `io.Writer` as valid, normalised TOML text. All comments, values, and structure present in the document are preserved. Use the `Format` convenience function or instantiate a `Formatter` directly (zero value is ready for use). ### Method `tomledit.Format(writer io.Writer, doc *Document) error` `tomledit.Formatter.Format(writer io.Writer, doc *Document) error` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go import ( "os" "strings" "github.com/creachadair/tomledit" ) doc, _ := tomledit.Parse(strings.NewReader(`title = "My App"`)) tomledit.Format(os.Stdout, doc) ``` ### Response #### Success Response (200) - **nil** (error) - Indicates successful serialization. #### Response Example ```toml title = "My App" ``` ``` -------------------------------- ### Insert or Replace Key-Value Pair with InsertMapping Source: https://context7.com/creachadair/tomledit/llms.txt InsertMapping appends a key-value pair to a section if the key is absent. Set `replace` to true to overwrite an existing mapping. Returns true if an insertion or replacement occurred. ```go doc, _ := tomledit.Parse(strings.NewReader("[settings]\ncolor = \"blue\"")) tab := transform.FindTable(doc, "settings") // Add a new key. transform.InsertMapping(tab.Section, &parser.KeyValue{ Name: parser.Key{"theme"}, Value: parser.MustValue(`"dark"`), }, false) // Replace an existing key. transform.InsertMapping(tab.Section, &parser.KeyValue{ Name: parser.Key{"color"}, Value: parser.MustValue(`"red"`), }, true) tomledit.Format(os.Stdout, doc) ``` -------------------------------- ### Find Table Entry by Name with FindTable Source: https://context7.com/creachadair/tomledit/llms.txt FindTable locates a TOML table section by its name. When called without arguments, it returns the global table. It returns nil if the table does not exist. ```go doc, _ := tomledit.Parse(strings.NewReader(` top = 1 [alpha] x = 10 [beta] y = 20 `)) global := transform.FindTable(doc) // global section alpha := transform.FindTable(doc, "alpha") // named section none := transform.FindTable(doc, "gamma") // not found fmt.Println(global != nil) // true fmt.Println(alpha.Section.TableName()) // [alpha] fmt.Println(none) // ``` -------------------------------- ### Document.Find Source: https://context7.com/creachadair/tomledit/llms.txt Find all entries matching a key. Useful for TOML array-of-tables (`[[name]]`) where a key can appear multiple times. ```APIDOC ## Document.Find — Find all entries matching a key Returns all `*Entry` values whose full key equals the given components. Useful for TOML array-of-tables (`[[name]]`) where a key can appear multiple times. ### Example ```go doc, _ := tomledit.Parse(strings.NewReader(` [[plugin]] name = "alpha" [[plugin]] name = "beta" [[plugin]] name = "gamma" `)) entries := doc.Find("plugin") for i, e := range entries { log.Printf("plugin[%d]: heading=%s", i, e.Section.Heading) } // Output: // plugin[0]: heading=[[plugin]] // plugin[1]: heading=[[plugin]] // plugin[2]: heading=[[plugin]] ``` ``` -------------------------------- ### Convert Snake Case to Kebab Case with SnakeToKebab Source: https://context7.com/creachadair/tomledit/llms.txt SnakeToKebab returns a function that transforms all snake_case key names to kebab-case throughout a TOML document. This is useful for migrating legacy configurations. ```go doc, _ := tomledit.Parse(strings.NewReader(` max_connections = 100 [server_config] bind_address = "0.0.0.0" read_timeout = 30 `)) transform.SnakeToKebab().Apply(context.Background(), doc) tomledit.Format(os.Stdout, doc) ``` -------------------------------- ### Parse a TOML value from a string Source: https://context7.com/creachadair/tomledit/llms.txt `parser.ParseValue` converts a string into a `parser.Value`, which wraps a `Datum`. `parser.MustValue` is similar but panics on error, suitable for static initialization. Values can optionally include trailing line comments. ```go // Parse various TOML value types. intVal, _ := parser.ParseValue("42") strVal, _ := parser.ParseValue(`"hello world"`) arrVal, _ := parser.ParseValue("[1, 2, 3]") tblVal, _ := parser.ParseValue(`{host = "localhost", port = 5432}`) fmt.Println(intVal) // 42 fmt.Println(strVal) // "hello world" fmt.Println(arrVal) // [1, 2, 3] fmt.Println(tblVal) // {host = "localhost", port = 5432} // MustValue for static use, with an attached comment. val := parser.MustValue("true").WithComment("enabled by default") fmt.Println(val) // true fmt.Println(val.Trailer) // # enabled by default // Assign back into a document entry: doc, _ := tomledit.Parse(strings.NewReader("[cfg]\ndebug=false\n")) doc.First("cfg", "debug").KeyValue.Value = val tomledit.Format(os.Stdout, doc) // Output: // [cfg] // debug = true # enabled by default ``` -------------------------------- ### Remove sections or mappings with transform.Remove Source: https://context7.com/creachadair/tomledit/llms.txt Use transform.Remove to delete specified TOML entries. All removals are attempted before returning; an error lists every key that was not found. This is useful for cleaning up obsolete data. ```go doc, _ := tomledit.Parse(strings.NewReader(` keep = true remove_me = false [keep_section] x = 1 [drop_section] y = 2 `)) err := transform.Remove( parser.Key{"remove_me"}, parser.Key{"drop_section"}, ).Apply(context.Background(), doc) if err != nil { log.Printf("some keys missing: %v", err) } tomledit.Format(os.Stdout, doc) // Output: // keep = true // // [keep_section] // x = 1 ``` -------------------------------- ### transform.SnakeToKebab Source: https://context7.com/creachadair/tomledit/llms.txt Returns a function that converts all snake_case key names to kebab-case throughout the TOML document. ```APIDOC ## transform.SnakeToKebab — Convert all key names from snake_case to kebab-case ### Description Returns a `Func` that walks the entire document and replaces every `_` with `-` in every section name and every key-value name. Useful for migrating legacy TOML configurations. ### Method Signature `transform.SnakeToKebab() Func` ### Returns - `Func`: A function that can be applied to a document to perform the transformation. ### Example Usage ```go doc, _ := tomledit.Parse(strings.NewReader(` max_connections = 100 [server_config] bind_address = "0.0.0.0" read_timeout = 30 `)) transform.SnakeToKebab().Apply(context.Background(), doc) tomledit.Format(os.Stdout, doc) ``` ``` -------------------------------- ### transform.FindTable Source: https://context7.com/creachadair/tomledit/llms.txt Locates a table entry by its name. Returns the corresponding `*Entry` or `nil` if the table is not found. When called without arguments, it returns the global table. ```APIDOC ## transform.FindTable — Locate a section entry by name ### Description Returns the `*Entry` for the named table section, or the global table when called with no name arguments. Returns `nil` if the table does not exist. ### Method Signature `transform.FindTable(doc *tomledit.Document, name ...string) *Entry` ### Parameters - `doc` (*tomledit.Document): The TOML document to search within. - `name` (string...): Optional names of the table to find. If omitted, the global table is returned. ### Example Usage ```go doc, _ := tomledit.Parse(strings.NewReader(` top = 1 [alpha] x = 10 [beta] y = 20 `)) global := transform.FindTable(doc) // global section alpha := transform.FindTable(doc, "alpha") // named section none := transform.FindTable(doc, "gamma") // not found fmt.Println(global != nil) // true fmt.Println(alpha.Section.TableName()) // [alpha] fmt.Println(none) // ``` ``` -------------------------------- ### parser.ParseKey Source: https://context7.com/creachadair/tomledit/llms.txt Parse a dotted TOML key from a string. Parses a string such as `"a.b.c"` or `"foo.\"bar baz\""` into a `parser.Key` (a `[]string`). Returns an error if the input is not a valid TOML key. ```APIDOC ## parser.ParseKey — Parse a dotted TOML key from a string Parses a string such as `"a.b.c"` or `"foo.\"bar baz\""` into a `parser.Key` (a `[]string`). Returns an error if the input is not a valid TOML key. ### Example ```go key, err := parser.ParseKey(`database.pool.max_size`) if err != nil { log.Fatal(err) } fmt.Println(key) // [database pool max_size] fmt.Println(key.String()) // database.pool.max_size // Quoted segments: key2, _ := parser.ParseKey(`"my app".settings`) fmt.Println(key2) // [my app settings] // Key comparison: a, _ := parser.ParseKey("a.b") b, _ := parser.ParseKey("a.b.c") fmt.Println(a.IsPrefixOf(b)) // true fmt.Println(a.Equals(b)) // false ``` ``` -------------------------------- ### transform.EnsureKey Source: https://context7.com/creachadair/tomledit/llms.txt Conditionally inserts a key-value mapping into a specified table only if the key does not already exist. Returns an error if the target table is not found. ```APIDOC ## transform.EnsureKey — Conditionally insert a key-value mapping ### Description Inserts the given `*parser.KeyValue` into a named table only if that key is not already present. Returns an error if the target table does not exist. ### Method Signature `transform.EnsureKey(tableKey parser.Key, kv *parser.KeyValue)` ### Parameters - `tableKey` (parser.Key): The key of the table to insert into. - `kv` (*parser.KeyValue): The key-value pair to insert. ### Example Usage ```go doc, _ := tomledit.Parse(strings.NewReader(` [config] existing = "leave me alone" `)) // Will NOT overwrite "existing". transform.EnsureKey( parser.Key{"config"}, &parser.KeyValue{ Name: parser.Key{"existing"}, Value: parser.MustValue(`"overwritten"`), }, ).Apply(context.Background(), doc) // WILL add "new_key" because it is absent. transform.EnsureKey( parser.Key{"config"}, &parser.KeyValue{ Block: parser.Comments{"added by migration"}, Name: parser.Key{"new_key"}, Value: parser.MustValue("true"), }, ).Apply(context.Background(), doc) tomledit.Format(os.Stdout, doc) ``` ``` -------------------------------- ### tomledit.Parse Source: https://context7.com/creachadair/tomledit/llms.txt Parses TOML text from an io.Reader into a mutable *Document, preserving all comments, key order, and formatting. It does not validate TOML semantics. ```APIDOC ## tomledit.Parse ### Description Reads TOML text from any `io.Reader` and returns a mutable `*Document`. The parser preserves all comments, key order, and formatting details. It does not validate TOML semantics (duplicate keys, illegal redefinitions, etc.). ### Method `tomledit.Parse(reader io.Reader) (*Document, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go import ( "strings" "github.com/creachadair/tomledit" ) input := `title = "My App" [database]\nhost = "localhost"` doc, err := tomledit.Parse(strings.NewReader(input)) if err != nil { // handle error } ``` ### Response #### Success Response (200) - **doc** (*Document) - A pointer to the parsed TOML document. - **err** (error) - An error if parsing fails. #### Response Example ```json { "title": "My App", "database": { "host": "localhost" } } ``` ``` -------------------------------- ### transform.InsertMapping Source: https://context7.com/creachadair/tomledit/llms.txt Inserts or replaces a key-value pair within a given section. If the key does not exist, it's appended. If `replace` is true, an existing key is overwritten. ```APIDOC ## transform.InsertMapping — Insert or replace a key-value pair in a section ### Description Appends `kv` to the section's item list if the key is absent. When `replace` is `true`, an existing mapping with the same name is overwritten in-place. Returns `true` if an insertion or replacement occurred. ### Method Signature `transform.InsertMapping(section *parser.Section, kv *parser.KeyValue, replace bool) bool` ### Parameters - `section` (*parser.Section): The section to insert the mapping into. - `kv` (*parser.KeyValue): The key-value pair to insert or replace. - `replace` (bool): If true, overwrites an existing key with the same name. ### Example Usage ```go doc, _ := tomledit.Parse(strings.NewReader("[settings]\ncolor = \"blue\"\n")) tab := transform.FindTable(doc, "settings") // Add a new key. transform.InsertMapping(tab.Section, &parser.KeyValue{ Name: parser.Key{"theme"}, Value: parser.MustValue(`"dark"`), }, false) // Replace an existing key. transform.InsertMapping(tab.Section, &parser.KeyValue{ Name: parser.Key{"color"}, Value: parser.MustValue(`"red"`), }, true) tomledit.Format(os.Stdout, doc) ``` ``` -------------------------------- ### Sort Table Sections Alphabetically with SortSectionsByName Source: https://context7.com/creachadair/tomledit/llms.txt SortSectionsByName performs a stable in-place sort of a slice of TOML sections based on their dotted table names. ```go doc, _ := tomledit.Parse(strings.NewReader(` [zebra] z = 1 [apple] a = 2 [mango] m = 3 `)) transform.SortSectionsByName(doc.Sections) tomledit.Format(os.Stdout, doc) ``` -------------------------------- ### parser.ParseValue / parser.MustValue Source: https://context7.com/creachadair/tomledit/llms.txt Parse a TOML value from a string. `ParseValue` parses a string into a `parser.Value` (wrapping a `Datum`). `MustValue` panics on error and is suitable for static initialisation. Values can carry an optional trailing line comment via `WithComment`. ```APIDOC ## parser.ParseValue / parser.MustValue — Parse a TOML value from a string `ParseValue` parses a string into a `parser.Value` (wrapping a `Datum`). `MustValue` panics on error and is suitable for static initialisation. Values can carry an optional trailing line comment via `WithComment`. ### Example ```go // Parse various TOML value types. intVal, _ := parser.ParseValue("42") strVal, _ := parser.ParseValue(`"hello world"`) arrVal, _ := parser.ParseValue("[1, 2, 3]") tblVal, _ := parser.ParseValue(`{host = "localhost", port = 5432}`) fmt.Println(intVal) // 42 fmt.Println(strVal) // "hello world" fmt.Println(arrVal) // [1, 2, 3] fmt.Println(tblVal) // {host = "localhost", port = 5432} // MustValue for static use, with an attached comment. val := parser.MustValue("true").WithComment("enabled by default") fmt.Println(val) // true fmt.Println(val.Trailer) // # enabled by default // Assign back into a document entry: doc, _ := tomledit.Parse(strings.NewReader("[cfg]\ndebug=false\n")) doc.First("cfg", "debug").KeyValue.Value = val tomledit.Format(os.Stdout, doc) // Output: // [cfg] // debug = true # enabled by default ``` ``` -------------------------------- ### Sort Key-Value Pairs within a Section with SortKeyValuesByName Source: https://context7.com/creachadair/tomledit/llms.txt SortKeyValuesByName performs a stable in-place sort of a slice of parser items within a TOML section. Key-value entries are ordered lexicographically by name, while comments maintain their relative positions. ```go doc, _ := tomledit.Parse(strings.NewReader(` [config] zebra = 3 # important comment apple = 1 mango = 2 `)) tab := transform.FindTable(doc, "config") transform.SortKeyValuesByName(tab.Items) tomledit.Format(os.Stdout, doc) ``` -------------------------------- ### transform.SortKeyValuesByName Source: https://context7.com/creachadair/tomledit/llms.txt Sorts the key-value pairs within a section alphabetically by their names, preserving the relative order of comments. ```APIDOC ## transform.SortKeyValuesByName — Sort key-value pairs within a section ### Description Performs a stable in-place sort of a `[]parser.Item` slice so that key-value entries appear in lexicographic order by name. Standalone comment blocks are left at their original relative positions. ### Method Signature `transform.SortKeyValuesByName(items []parser.Item)` ### Parameters - `items` ([]parser.Item): The slice of items (key-values and comments) within a section to sort. ### Example Usage ```go doc, _ := tomledit.Parse(strings.NewReader(` [config] zebra = 3 # important comment apple = 1 mango = 2 `)) tab := transform.FindTable(doc, "config") transform.SortKeyValuesByName(tab.Items) tomledit.Format(os.Stdout, doc) ``` ``` -------------------------------- ### Remove an entry from the document Source: https://context7.com/creachadair/tomledit/llms.txt The `Entry.Remove` method deletes a section or key-value mapping from its parent. It works on top-level keys, table sections, and inline table entries, returning `true` if a modification occurred. ```go doc, _ := tomledit.Parse(strings.NewReader(` x = 5 y = 10 [keep] a = true [drop] b = false `)) // Remove a top-level key. doc.First("y").Remove() // Remove an entire section. doc.First("drop").Remove() tomledit.Format(os.Stdout, doc) // Output: // x = 5 // // [keep] // a = true ``` -------------------------------- ### transform.Rename Source: https://context7.com/creachadair/tomledit/llms.txt Returns a transformation function that renames a TOML entry. This can be used to rename table section headings or individual key-value pairs, including nested inline table keys. ```APIDOC ## transform.Rename — Rename a section or key-value entry Returns a `Func` that renames the first entry matching `oldKey` to `newKey`. Works for both table section headings and individual key-value pairs (including nested inline table keys). ### Method Apply ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Rename the section. transform.Rename( parser.Key{"old_name"}, parser.Key{"new_name"}, ).Apply(ctx, doc) // Rename a nested inline key. transform.Rename( parser.Key{"new_name", "nested", "inner_key"}, parser.Key{"renamed_key"}, ).Apply(ctx, doc) ``` ### Response #### Success Response (200) None explicitly defined, but the document is modified in place. #### Response Example None ``` -------------------------------- ### transform.Remove Source: https://context7.com/creachadair/tomledit/llms.txt Returns a transformation function that removes specified entries from a TOML document. It can remove top-level keys or entire sections. All specified keys are attempted to be removed, and an error is returned listing any keys that were not found. ```APIDOC ## transform.Remove — Remove one or more sections or mappings Returns a `Func` that removes all entries at the specified keys. All removals are attempted before returning; an error lists every key that was not found. ### Method Apply ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go err := transform.Remove( parser.Key{"remove_me"}, parser.Key{"drop_section"}, ).Apply(context.Background(), doc) if err != nil { log.Printf("some keys missing: %v", err) } ``` ### Response #### Success Response (200) None explicitly defined, but the document is modified in place. #### Response Example None ``` -------------------------------- ### Rename a section or key-value entry with transform.Rename Source: https://context7.com/creachadair/tomledit/llms.txt Use transform.Rename to change the name of a TOML section or a key-value pair. This function works for top-level sections, nested inline table keys, and key-value pairs within sections. ```go doc, _ := tomledit.Parse(strings.NewReader(` [old_name] value = 1 nested = {inner_key = true} `)) ctx := context.Background() // Rename the section. transform.Rename( parser.Key{"old_name"}, parser.Key{"new_name"}, ).Apply(ctx, doc) // Rename a nested inline key. transform.Rename( parser.Key{"new_name", "nested", "inner_key"}, parser.Key{"renamed_key"}, ).Apply(ctx, doc) tomledit.Format(os.Stdout, doc) // Output: // [new_name] // value = 1 // nested = {renamed_key = true} ``` -------------------------------- ### Entry.Remove Source: https://context7.com/creachadair/tomledit/llms.txt Remove an entry from the document. Removes the entry (section or key-value mapping) from its parent container and reports whether any change was made. Works for global mappings, table sections, and inline table entries. ```APIDOC ## Entry.Remove — Remove an entry from the document Removes the entry (section or key-value mapping) from its parent container and reports whether any change was made. Works for global mappings, table sections, and inline table entries. ### Example ```go doc, _ := tomledit.Parse(strings.NewReader(` x = 5 y = 10 [keep] a = true [drop] b = false `)) // Remove a top-level key. doc.First("y").Remove() // Remove an entire section. doc.First("drop").Remove() tomledit.Format(os.Stdout, doc) // Output: // x = 5 // // [keep] // a = true ``` ``` -------------------------------- ### transform.SortSectionsByName Source: https://context7.com/creachadair/tomledit/llms.txt Sorts a slice of table sections alphabetically by their names in-place. ```APIDOC ## transform.SortSectionsByName — Sort table sections alphabetically ### Description Performs a stable in-place sort of a `[]*tomledit.Section` slice by each section's dotted table name. ### Method Signature `transform.SortSectionsByName(sections []*tomledit.Section)` ### Parameters - `sections` ([]*tomledit.Section): The slice of sections to sort. ### Example Usage ```go doc, _ := tomledit.Parse(strings.NewReader(` [zebra] z = 1 [apple] a = 2 [mango] m = 3 `)) transform.SortSectionsByName(doc.Sections) tomledit.Format(os.Stdout, doc) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.