### Run go-yaml Examples Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Examples can be run directly using 'go run' or from within their respective directories. ```bash go run example/basic_loader.go ``` ```bash cd example go run basic_loader.go ``` -------------------------------- ### Quick Start with Default Settings Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Demonstrates the simplest way to use go-yaml with its default settings for encoding data. ```go import "go.yaml.in/yaml/v4" // Uses v4 defaults (2-space indent, compact sequences) dumper, _ := yaml.NewDumper(writer) dumper.Dump(&myData) dumper.Close() ``` -------------------------------- ### Install go.yaml.in/yaml/v4 Source: https://github.com/yaml/go-yaml/blob/main/README.md Use 'go get' to install the latest version of the YAML package for Go. This command fetches and installs the package, making it available for use in your Go projects. ```bash go get go.yaml.in/yaml/v4 ``` -------------------------------- ### Enabling Explicit Start Marker Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Demonstrates how to explicitly enable the document start marker (---) using the WithExplicitStart option. ```go yaml.WithExplicitStart() // Enable (same as WithExplicitStart(true)) yaml.WithExplicitStart(false) // Explicitly disable ``` -------------------------------- ### Comprehensive go-yaml Feature Demonstration Source: https://github.com/yaml/go-yaml/blob/main/example/README.md A comprehensive example covering Loader, Dumper, and various options, providing a good overview of the library's capabilities. ```go import "go.yaml.in/yaml/v4" // This is a placeholder for the comprehensive demo file. // The actual code would involve setting up readers/writers, // defining structs, and demonstrating various Load/Dump scenarios with options. ``` -------------------------------- ### Install go-yaml CLI Tool Source: https://github.com/yaml/go-yaml/blob/main/CONTRIBUTING.md Install the go-yaml CLI tool globally using go install. This tool is useful for debugging and reporting issues. ```bash go install go.yaml.in/yaml/v4/cmd/go-yaml@latest ``` -------------------------------- ### Load Configuration with Strict Options Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Load application configuration from a file using strict YAML options. This example uses `WithKnownFields()` to catch typos and `WithSingleDocument()` to ensure exactly one YAML document is present. ```go type AppConfig struct { Database DatabaseConfig `yaml:"database"` Server ServerConfig `yaml:"server"` } func LoadConfig(filename string) (*AppConfig, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() loader, err := yaml.NewLoader(f, yaml.WithV4Defaults(), yaml.WithKnownFields(), // Catch typos (defaults to true) yaml.WithSingleDocument(), // Expect exactly one doc ) if err != nil { return nil, err } var config AppConfig if err := loader.Load(&config); err != nil { return nil, err } return &config, nil } ``` -------------------------------- ### Set Go Installation Path Source: https://github.com/yaml/go-yaml/blob/main/README.md Export GO_YAML_PATH to use your system's Go installation. This overrides any GO-VERSION settings. ```bash export GO_YAML_PATH=$(dirname "$(command -v go)") make # or: make GO_YAML_PATH=$(dirname "$(command -v go)") ``` -------------------------------- ### Always Emitting Document Start Marker Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Ensures that the document start marker (`---`) is always emitted at the beginning of the document. ```go yaml.NewDumper(w, yaml.WithExplicitStart()) ``` -------------------------------- ### Encoding Nodes with Different Options Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Shows node.Dump() with various formatting options, comparing default, v3, and custom indent styles, and demonstrating explicit start markers. ```go import "go.yaml.in/yaml/v4/node" // Dump node with options var n node.Node // ... build or load node n ... // Default dump dataDefault := n.Dump() // Dump with v3 defaults (4-space indent) dataV3 := n.Dump(node.WithV3Defaults()) // Dump with custom indent and start marker dataCustom := n.Dump(node.WithIndent(2), node.WithExplicitStartMarker()) ``` -------------------------------- ### Override 2-space Indent with v3 Defaults Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Start with a 2-space indent and then apply v3 defaults, which will override the indent to 4 spaces. ```go // Start with 2-space, then apply v3 (4-space wins) dumper, _ := yaml.NewDumper(writer, yaml.WithIndent(2), yaml.WithV3Defaults(), // This overrides to 4 ) ``` -------------------------------- ### Emit with Custom Indentation Configuration Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Shows how to emit YAML with a custom indentation configuration. This snippet includes stream and document start events, followed by a mapping start event, with a specified indent of 4. ```yaml - emit-config: name: Custom indent conf: indent: 4 data: - STREAM_START_EVENT: encoding: UTF8_ENCODING - DOCUMENT_START_EVENT: implicit: true - MAPPING_START_EVENT: implicit: true style: BLOCK_MAPPING_STYLE # ... more events want: key ``` -------------------------------- ### Use Local Go with Makefile Source: https://github.com/yaml/go-yaml/blob/main/CONTRIBUTING.md Configure the makefile to use your locally installed Go environment by setting the GO_YAML_PATH environment variable. This allows using your preferred Go version for development and testing. ```bash export GO_YAML_PATH=$(dirname "$(command -v go)") make test ``` ```bash make test GO_YAML_PATH=$(dirname "$(command -v go)") ``` -------------------------------- ### Test Event Constructor: NewStreamStartEvent Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Tests the constructor for creating a new stream start event. It verifies that the event type is correctly set to STREAM_START_EVENT and the encoding is UTF8_ENCODING. ```yaml - api-new-event: name: New stream start event call: [NewStreamStartEvent, UTF8_ENCODING] test: - eq: [Type, STREAM_START_EVENT] - eq: [encoding, UTF8_ENCODING] ``` -------------------------------- ### Get Makefile Shell Environment Source: https://github.com/yaml/go-yaml/blob/main/CONTRIBUTING.md Launch a subshell with the same environment and binaries used by the makefile. This is useful for running custom commands within the project's build environment. ```bash make shell ``` ```bash make bash ``` ```bash make zsh ``` ```bash make shell GO_VERSION=1.23.4 ``` -------------------------------- ### Override v3 Defaults with 2-space Indent Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Start with v3 defaults (4-space indent) and then override the indent to 2 spaces. Options are applied left-to-right, so the later option takes precedence. ```go // Start with v3 defaults (4-space), then override to 2-space dumper, _ := yaml.NewDumper(writer, yaml.WithV3Defaults(), yaml.WithIndent(2), // This wins ) ``` -------------------------------- ### Test Style Accessor Method Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Tests the style accessor methods for events. This example checks the ScalarStyle accessor against the DOUBLE_QUOTED_SCALAR_STYLE constant. ```yaml - style-accessor: name: Event scalar style test: [ScalarStyle, DOUBLE_QUOTED_SCALAR_STYLE] ``` -------------------------------- ### YAML Configuration: Disabling Depth Checking Source: https://github.com/yaml/go-yaml/blob/main/docs/plugins.md Provides an example of a YAML configuration snippet to disable depth checking for the limit plugin while retaining default alias limits. ```yaml # Disable depth checking, keep default alias limits plugin: limit: depth: null ``` -------------------------------- ### Using Version Presets Pattern Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Demonstrates how to apply version presets like yaml.WithV4Defaults() when creating a Dumper to easily configure common settings. ```go import "go.yaml.in/yaml/v4" // Use v4 defaults for dumping dumper, _ := yaml.NewDumper(writer, yaml.WithV4Defaults(), ) ``` -------------------------------- ### Limit Plugin: Default and Custom Settings Source: https://github.com/yaml/go-yaml/blob/main/docs/plugins.md Demonstrates how to initialize the limit plugin with default settings, disable alias checking, or set a custom depth limit. ```go import "go.yaml.in/yaml/v4/plugin/limit" // Default limits (same as library defaults) loader := yaml.NewLoader(data, yaml.WithPlugin(limit.New())) // Disable alias checking (e.g. for documents with many programmatic aliases) loader := yaml.NewLoader(data, yaml.WithPlugin(limit.New(limit.AliasNone()))) // Custom depth limit loader := yaml.NewLoader(data, yaml.WithPlugin(limit.New(limit.DepthValue(50)))) ``` -------------------------------- ### Using v4 Option Presets Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Demonstrates yaml.WithV4Defaults() which applies v4 defaults, including 2-space indentation, and compares it with default (v3) output. ```go import "go.yaml.in/yaml/v4" // Use v4 defaults data, _ := yaml.Dump(&config, yaml.WithV4Defaults()) ``` -------------------------------- ### Build YAML Programmatically with Nodes Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Demonstrates building complex Node structures programmatically, performing a round-trip (Dump then Load) with options, and shows a typical node manipulation workflow. ```go import "go.yaml.in/yaml/v4/node" // Build node programmatically root := node.NewMapping() root.Set( ``` -------------------------------- ### Basic YAML Loading Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Demonstrates simple YAML loading into Go structs using a Loader. ```go import "go.yaml.in/yaml/v4" // Load var config Config yaml.Load(yamlData, &config) ``` -------------------------------- ### Configuring Plugins via YAML Source: https://github.com/yaml/go-yaml/blob/main/docs/plugins.md Illustrates how to configure plugins, such as the limit plugin, using YAML options. This allows setting depth and alias limits directly within a YAML configuration string. ```go opts, err := yaml.OptsYAML(` plugin: limit: depth: 50 alias: 1000 `) ``` -------------------------------- ### Streaming with Options Pattern Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Shows how to use NewLoader and NewDumper with specific options for streaming YAML data, such as enabling strict field checking or custom indentation. ```go import "go.yaml.in/yaml/v4" // Load with options loader, _ := yaml.NewLoader(reader, yaml.WithKnownFields(), yaml.WithSingleDocument(), ) loader.Load(&config) // Dump with options dumper, _ := yaml.NewDumper(writer, yaml.WithIndent(2), ) dumper.Dump(&config) dumper.Close() ``` -------------------------------- ### Basic YAML Dumping Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Demonstrates simple YAML dumping from Go structs to a writer using a Dumper. ```go import "go.yaml.in/yaml/v4" // Dump data, _ := yaml.Dump(&config) ``` -------------------------------- ### Build and Use go-yaml CLI Source: https://github.com/yaml/go-yaml/blob/main/README.md Build the go-yaml CLI tool using make and run it to inspect YAML processing. Use the -n flag to show decoded Node structs. ```bash make go-yaml ./go-yaml --help ./go-yaml <<< ' foo: &a1 bar *a1: baz ' -n # Show value on decoded Node structs (formatted in YAML) ``` -------------------------------- ### Application Config Loader with Options Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Loads a single configuration file, enforcing strict validation for known fields. ```go loader, _ := yaml.NewLoader(configFile, yaml.WithSingleDocument(), // Only one config file yaml.WithKnownFields(), // Strict validation (defaults to true) ) ``` -------------------------------- ### Basic Load and Dump Pattern Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Illustrates the fundamental pattern for loading YAML data into Go structs and dumping Go structs back into YAML format. ```go import "go.yaml.in/yaml/v4" // Load var config Config yaml.Load(yamlData, &config) // Dump data, _ := yaml.Dump(&config) ``` -------------------------------- ### Implementing a Custom Limit Plugin Source: https://github.com/yaml/go-yaml/blob/main/docs/plugins.md Demonstrates how to implement a third-party limit plugin by defining a struct that satisfies the `yaml.LimitPlugin` interface and providing custom checks for depth and alias counts. ```go type LimitPlugin interface { CheckDepth(depth int, ctx *DepthContext) error CheckAlias(aliasCount, constructCount int) error } func (s *StrictLimit) CheckDepth(depth int, ctx *yaml.DepthContext) error { if depth > 100 { return fmt.Errorf("depth %d exceeds policy limit of 100", depth) } return nil } func (s *StrictLimit) CheckAlias(aliasCount, constructCount int) error { if aliasCount > 1000 { return fmt.Errorf("alias count %d exceeds policy limit", aliasCount) } return nil } yaml.NewLoader(data, yaml.WithPlugin(&StrictLimit{})) ``` -------------------------------- ### Run All Tests in Package Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Execute all tests defined within the ./internal/libyaml package. ```bash # Run all tests in the package go test ./internal/libyaml ``` -------------------------------- ### Registering Plugins with WithPlugin Source: https://github.com/yaml/go-yaml/blob/main/docs/plugins.md Shows the basic usage of registering a plugin, specifically the limit plugin with alias checking disabled, when creating a new loader. ```go import ( "go.yaml.in/yaml/v4" "go.yaml.in/yaml/v4/plugin/limit" ) loader := yaml.NewLoader(data, yaml.WithPlugin(limit.New(limit.AliasNone()))) var result any loader.Load(&result) ``` -------------------------------- ### Development and Testing with make Source: https://github.com/yaml/go-yaml/blob/main/README.md Utilize the project's makefile for deterministic testing, automation, and development tasks. Common commands include `make test`, `make lint tidy`, and `make shell`. ```makefile make test make lint tidy make test-shell make test v=1 make test o='-foo --bar=baz' # Add extra CLI options make test GO-VERSION=1.2.34 make test GO_YAML_PATH=/usr/local/go/bin make shell # Start a shell with the local `go` environment make shell GO-VERSION=1.2.34 make distclean # Remove all generated files including `.cache/` ``` -------------------------------- ### Customizing Indentation and Sequence Style Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Shows how to configure the dumper for 4-space indentation and non-compact sequences, similar to v3 behavior. ```go dumper, _ := yaml.NewDumper(writer, yaml.WithIndent(4), // 4-space indentation (v3 style) yaml.WithCompactSeqIndent(false), // Non-compact lists (v3 style) ) ``` -------------------------------- ### Format Code with Makefile Source: https://github.com/yaml/go-yaml/blob/main/CONTRIBUTING.md Format your code according to project conventions using the make fmt command. This should be run before committing changes. ```bash make fmt ``` -------------------------------- ### Compare Decode() vs Load() for Nodes Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Provides a side-by-side comparison of the old node.Decode() and the new node.Load() approaches, highlighting that Decode() loses options while Load() preserves them. ```go import "go.yaml.in/yaml/v4/node" // Example data var yamlData = []byte(`field1: value1\nfield2: 123`) // Using node.Decode() - options are lost var dataDecode map[string]interface{} node.Decode(yamlData, &dataDecode) // Options like WithKnownFields are ignored // Using node.Load() - options are preserved var dataLoad map[string]interface{} node.Load(yamlData, &dataLoad, node.WithKnownFields()) // WithKnownFields() is respected ``` -------------------------------- ### Run Tests with Makefile Source: https://github.com/yaml/go-yaml/blob/main/CONTRIBUTING.md Execute all tests using the make test command. This is a crucial step to ensure new changes do not break existing functionality. ```bash make test ``` -------------------------------- ### Use go-yaml v4 Defaults (Default) Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Configure for modern YAML output with a 2-space indent and compact sequences. This is the default behavior, so specifying `yaml.WithV4Defaults()` is usually for explicitness. ```go dumper, _ := yaml.NewDumper(writer, yaml.WithV4Defaults()) ``` -------------------------------- ### Overriding Option Presets Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Combines version presets with individual options, showing how later options override earlier ones. ```go import "go.yaml.in/yaml/v4" // Combine and override options data, _ := yaml.Dump(&config, yaml.WithV4Defaults(), // Sets default indent to 2 yaml.WithIndent(4), // Overrides indent to 4 ) ``` -------------------------------- ### Use go-yaml v2 Defaults Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Use this to match go-yaml v2 output format, which typically uses a 2-space indent. ```go dumper, _ := yaml.NewDumper(writer, yaml.WithV2Defaults()) ``` -------------------------------- ### Format YAML with User-Configurable Preferences Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Reformat input YAML using user-defined preferences loaded from a string. This involves loading user preferences into options, parsing the input YAML, and then dumping it with the specified options. ```go func FormatYAML(input []byte, userPrefs string) ([]byte, error) { // Load user's formatting preferences opts, err := yaml.OptsYAML(userPrefs) if err != nil { return nil, err } // Parse input var node yaml.Node if err := yaml.Load(input, &node); err != nil { return nil, err } // Reformat with user preferences var buf bytes.Buffer dumper, _ := yaml.NewDumper(&buf, opts) dumper.Dump(&node) dumper.Close() return buf.Bytes(), nil } ``` -------------------------------- ### Run Tests with Makefile Source: https://github.com/yaml/go-yaml/blob/main/CONTRIBUTING.md Execute all tests, linters, and formatters using the make check command. This ensures code quality and adherence to project standards. ```bash make check ``` -------------------------------- ### Run Tests with Verbose Output Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Execute all tests in the ./internal/libyaml package and display verbose output, showing the names of passing tests. ```bash # Run with verbose output go test -v ./internal/libyaml ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Execute all tests in the ./internal/libyaml package and generate a code coverage report. ```bash # Run with coverage go test -cover ./internal/libyaml ``` -------------------------------- ### Load Options from YAML Configuration Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Load YAML processing options, such as indent and compact sequence settings, directly from a YAML configuration string. This allows for configurable formatting. ```go configYAML := ` indent: 3 compact-seq-indent: true known-fields: true ` opts, err := yaml.OptsYAML(configYAML) if err != nil { log.Fatal(err) } dumper, _ := yaml.NewDumper(writer, opts) ``` -------------------------------- ### Combining Multiple Loader Options Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Uses WithSingleDocument and WithKnownFields together to enable strict field checking and ensure only the first document is loaded. ```go import "go.yaml.in/yaml/v4" // Combine loader options loader, _ := yaml.NewLoader(reader, yaml.WithKnownFields(), yaml.WithSingleDocument(), ) loader.Load(&config) ``` -------------------------------- ### Load Multi-Document Stream with Options Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Processes a multi-document YAML stream, allowing unknown fields and iterating through each document. ```go func ProcessMultiDocs(reader io.Reader) error { loader, err := yaml.NewLoader(reader, yaml.WithKnownFields(false), // Allow unknown fields (override default) ) if err != nil { return err } for { var doc Document err := loader.Load(&doc) if err == io.EOF { break } if err != nil { return err } // Process document... processDocument(&doc) } return nil } ``` -------------------------------- ### Compare Different Indentation Levels Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Shows the output of YAML dumping with different space indentations (2, 4, and 8 spaces). ```go import "go.yaml.in/yaml/v4" // Compare indent levels fmt.Println("--- Indent 2 ---") fmt.Println(yaml.DumpString(&config, yaml.WithIndent(2))) fmt.Println("--- Indent 4 ---") fmt.Println(yaml.DumpString(&config, yaml.WithIndent(4))) fmt.Println("--- Indent 8 ---") fmt.Println(yaml.DumpString(&config, yaml.WithIndent(8))) ``` -------------------------------- ### Load YAML into Node Representation Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Uses the Node type for low-level YAML access and demonstrates working with the YAML AST. ```go import "go.yaml.in/yaml/v4/node" // Load into Node var n node.Node n, _ = node.Load(yamlData) ``` -------------------------------- ### Generate CI-Compatible YAML with v2 Defaults Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Generate YAML output that matches the format expected by a CI system, specifically using go-yaml v2 defaults (2-space indent). ```go func GenerateCI(config *CIConfig) ([]byte, error) { var buf bytes.Buffer dumper, err := yaml.NewDumper(&buf, yaml.WithV2Defaults(), ) if err != nil { return nil, err } if err := dumper.Dump(config); err != nil { return nil, err } dumper.Close() return buf.Bytes(), nil } ``` -------------------------------- ### Use go-yaml v3 Defaults Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Explicitly request v3 behavior, characterized by a 4-space indent and non-compact sequences. Useful for compatibility with older v3 output. ```go dumper, _ := yaml.NewDumper(writer, yaml.WithV3Defaults()) ``` -------------------------------- ### Unmarshal and Marshal YAML Data in Go Source: https://github.com/yaml/go-yaml/blob/main/README.md Demonstrates how to unmarshal YAML strings into Go structs and maps, and then marshal them back into YAML format. Ensure struct fields are public for correct unmarshaling. The `yaml:",flow"` tag enables inline slice representation. ```go package main import ( "fmt" "log" "go.yaml.in/yaml/v4" ) var data = ` a: Easy! b: c: 2 d: [3, 4] ` // Note: struct fields must be public in order for unmarshal to // correctly populate the data. type T struct { A string B struct { RenamedC int `yaml:"c"` D []int `yaml:",flow"` } } func main() { t := T{} err := yaml.Unmarshal([]byte(data), &t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t:\n%v\n\n", t) d, err := yaml.Marshal(&t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t dump:\n%s\n\n", string(d)) m := make(map[any]any) err = yaml.Unmarshal([]byte(data), &m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m:\n%v\n\n", m) d, err = yaml.Marshal(&m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m dump:\n%s\n\n", string(d)) } ``` -------------------------------- ### Setting Preferred Line Width for Wrapping Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Configures the dumper to wrap long strings at a specified line width. ```go yaml.NewDumper(w, yaml.WithLineWidth(40)) ``` ```go yaml.NewDumper(w, yaml.WithLineWidth(-1)) ``` -------------------------------- ### Setting Windows Line Endings Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Configures the dumper to use Windows-style line endings (`\r\n`). ```go yaml.NewDumper(w, yaml.WithLineBreak(yaml.LineBreakCRLN)) ``` -------------------------------- ### Match Legacy YAML Format Dumper Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Creates a YAML dumper configured to match the legacy go-yaml v3 format, using 4-space indentation. ```go dumper, _ := yaml.NewDumper(output, yaml.WithV3Defaults()) // 4-space like old go-yaml ``` -------------------------------- ### Enable Single Document Loading Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Only load the first YAML document and then return EOF. This is useful when you expect exactly one document and want to catch any extra documents. ```go yaml.WithSingleDocument() yaml.WithSingleDocument(singleDoc) ``` ```go loader, _ := yaml.NewLoader(reader, yaml.WithSingleDocument(), ) var doc1 Doc loader.Load(&doc1) var doc2 Doc loader.Load(&doc2) ``` -------------------------------- ### Setting Unix Line Endings Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Configures the dumper to use Unix-style line endings (`\n`). ```go yaml.NewDumper(w, yaml.WithLineBreak(yaml.LineBreakLN)) ``` -------------------------------- ### Load Multiple YAML Documents Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Processes multi-document YAML streams by looping through documents until EOF. ```go import "go.yaml.in/yaml/v4" // Load multiple documents for { var config Config err := yaml.Load(&config) // Loads one document per call if err == io.EOF { break } // Process config } ``` -------------------------------- ### Default YAML Output Dumper Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Creates a YAML dumper using v4 defaults, resulting in 2-space indentation and compact sequences. ```go dumper, _ := yaml.NewDumper(output) // Uses v4 defaults (2-space, compact) ``` -------------------------------- ### Enabling Compact Sequence Indentation Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Enables compact sequence indentation, where the list indicator `- ` is part of the indentation. ```go yaml.NewDumper(w, yaml.WithIndent(4), yaml.WithCompactSeqIndent(), ) ``` -------------------------------- ### Run Linters with Makefile Source: https://github.com/yaml/go-yaml/blob/main/CONTRIBUTING.md Check code for potential issues and style violations using the make lint command. This helps maintain code quality. ```bash make lint ``` -------------------------------- ### Run Specific Test Case Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Execute a particular test case (subtest) within a test file in the ./internal/libyaml package. ```bash # Run specific test case (using subtest name) go test ./internal/libyaml -run TestScanner/Block_sequence go test ./internal/libyaml -run TestParser/Anchor_and_alias go test ./internal/libyaml -run TestEmitter/Flow_mapping go test ./internal/libyaml -run TestLoader/Scientific_notation_lowercase_e ``` -------------------------------- ### Test Parser Constructors Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Tests the various constructors available for creating a new parser. It includes tests for nil and capacity settings for both raw-buffer and buffer. ```yaml - api-new: name: New parser with: NewParser test: - nil: [raw-buffer, false] - cap: [raw-buffer, 512] - nil: [buffer, false] - cap: [buffer, 1536] ``` -------------------------------- ### Run Specific Test File Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Execute tests contained within a specific test file in the ./internal/libyaml package. ```bash # Run specific test file go test ./internal/libyaml -run TestScanner go test ./internal/libyaml -run TestParser go test ./internal/libyaml -run TestEmitter go test ./internal/libyaml -run TestAPI go test ./internal/libyaml -run TestYAML go test ./internal/libyaml -run TestLoader ``` -------------------------------- ### Dump Multiple YAML Documents Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Creates a multi-document YAML stream where multiple Dump() calls are separated by '---'. ```go import "go.yaml.in/yaml/v4" // Dump multiple documents dumper, _ := yaml.NewDumper(writer) dumper.Dump(&config1) dumper.Dump(&config2) dumper.Close() ``` -------------------------------- ### Control Duplicate Key Detection Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Enforce unique keys in mappings during loading. When enabled, loading fails if duplicate keys are found, which helps prevent key override attacks. ```go yaml.WithUniqueKeys() yaml.WithUniqueKeys(false) ``` ```yaml admin: false admin: true # Error: duplicate key ``` -------------------------------- ### Allowing Unicode Characters Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Configures the dumper to allow non-ASCII characters to appear as-is in the output. ```go yaml.NewDumper(w, yaml.WithUnicode(true)) ``` -------------------------------- ### Roundtrip YAML Parsing and Emitting Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Tests the roundtrip functionality by parsing a given YAML string and then emitting it, verifying the output against an expected list of values. This is useful for ensuring data integrity after transformations. ```yaml - roundtrip: name: Roundtrip yaml: | key: value list: - item1 - item2 want: - key - value - item1 ``` -------------------------------- ### Parser Test: Simple Event Sequence Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Verifies the event sequence generated for a simple YAML mapping. ```yaml - parse-events: name: Simple mapping yaml: | key: value want: - STREAM_START_EVENT - DOCUMENT_START_EVENT - MAPPING_START_EVENT - SCALAR_EVENT - SCALAR_EVENT - MAPPING_END_EVENT - DOCUMENT_END_EVENT - STREAM_END_EVENT ``` -------------------------------- ### Setting 2-Space Indentation Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Configures the dumper to use 2-space indentation for YAML output. ```go yaml.NewDumper(w, yaml.WithIndent(2)) ``` -------------------------------- ### Load Only First YAML Document Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Uses the WithSingleDocument option to load only the first document in a stream. Subsequent Load() calls will return EOF. ```go import "go.yaml.in/yaml/v4" // Load single document var config Config yaml.Load(yamlData, &config, yaml.WithSingleDocument()) ``` -------------------------------- ### Override Default (v4) with 4-space Indent Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Apply a 4-space indent, overriding the default 2-space indent of v4. ```go // Default (v4) + override to 4-space indent dumper, _ := yaml.NewDumper(writer, yaml.WithIndent(4), // Overrides default 2-space ) ``` -------------------------------- ### Inspect YAML Processing with go-yaml CLI Source: https://github.com/yaml/go-yaml/blob/main/CONTRIBUTING.md Use the go-yaml CLI tool to inspect intermediate stages and final results of YAML processing. This is crucial for debugging parsing logic. ```bash ./go-yaml -t <<<' foo: &a1 bar *a1: baz ' ``` -------------------------------- ### Setting 8-Space Indentation Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Configures the dumper to use 8-space indentation for YAML output. ```go yaml.NewDumper(w, yaml.WithIndent(8)) ``` -------------------------------- ### Emit Simple Scalar Event Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Demonstrates emitting a simple scalar event with basic stream and document start/end events. The expected output is the scalar value. ```yaml - emit: name: Simple scalar data: - STREAM_START_EVENT: encoding: UTF8_ENCODING - DOCUMENT_START_EVENT: implicit: true - SCALAR_EVENT: value: hello implicit: true style: PLAIN_SCALAR_STYLE - DOCUMENT_END_EVENT: implicit: true - STREAM_END_EVENT want: hello ``` -------------------------------- ### Setting 4-Space Indentation Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Configures the dumper to use 4-space indentation for YAML output. ```go yaml.NewDumper(w, yaml.WithIndent(4)) ``` -------------------------------- ### Update Go Module Dependencies Source: https://github.com/yaml/go-yaml/blob/main/CONTRIBUTING.md Ensure Go module dependencies are tidy using the make tidy command. This removes unused dependencies and updates module information. ```bash make tidy ``` -------------------------------- ### Emit Events to an io.Writer Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Demonstrates emitting YAML events directly to an io.Writer. This is useful for streaming YAML output without needing to buffer the entire content in memory. The expected output is 'test'. ```yaml - emit-writer: name: Writer data: - STREAM_START_EVENT: encoding: UTF8_ENCODING # ... more events want: test ``` -------------------------------- ### Parser Test: Detailed Event Properties Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Verifies event properties, including anchors and aliases, for a sequence. ```yaml - parse-events-detailed: name: Anchor and alias yaml: | - &anchor value - *anchor want: - STREAM_START_EVENT - DOCUMENT_START_EVENT - SEQUENCE_START_EVENT - SCALAR_EVENT: anchor: anchor value: value - ALIAS_EVENT: anchor: anchor - SEQUENCE_END_EVENT - DOCUMENT_END_EVENT - STREAM_END_EVENT ``` -------------------------------- ### Control Simple Collection Style Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Use flow style for simple collections (sequences and mappings with only scalar values) to achieve a more compact, JSON-like output. This is useful for simple data structures. ```go yaml.NewDumper(w, yaml.WithFlowSimpleCollections()) ``` -------------------------------- ### Test Parser Method: SetInputString Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Tests the SetInputString method of the parser to set its input. It verifies that the input is correctly set and the input position is reset to 0. It also checks that the read-handler is not nil. ```yaml - api-method: name: Parser set input string with: NewParser byte: true call: [SetInputString, 'key: value'] test: - eq: [input, 'key: value'] - eq: [input-pos, 0] - nil: [read-handler, false] ``` -------------------------------- ### Scanner Test: Simple Scalar Tokens Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Verifies the basic token sequence for a simple scalar value. ```yaml - scan-tokens: name: Simple scalar yaml: |- hello want: - STREAM_START_TOKEN - SCALAR_TOKEN - STREAM_END_TOKEN ``` -------------------------------- ### Custom Indentation for YAML Dumping Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Uses the WithIndent option to control the indentation level of the dumped YAML output. ```go import "go.yaml.in/yaml/v4" // Dump with custom indent data, _ := yaml.Dump(&config, yaml.WithIndent(2)) ``` -------------------------------- ### Enable Strict Field Checking on Load Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Fail loading if the YAML contains fields that do not exist in the target struct. This is great for catching typos in configuration files and enforcing strict schemas. ```go yaml.WithKnownFields() yaml.WithKnownFields(false) ``` ```go loader, _ := yaml.NewLoader(reader, yaml.WithKnownFields(), ) var config Config err := loader.Load(&config) ``` -------------------------------- ### Escaping Non-ASCII Characters Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Configures the dumper to escape non-ASCII characters, useful for ASCII-only output requirements. ```go yaml.NewDumper(w, yaml.WithUnicode(false)) ``` -------------------------------- ### Strict Field Checking in Custom Unmarshalers Source: https://github.com/yaml/go-yaml/blob/main/example/README.md Solves Issue #460 by using node.Load() with WithKnownFields() in custom UnmarshalYAML implementations, demonstrating proper error handling for unknown fields. ```go import ( "go.yaml.in/yaml/v4/node" "errors" ) type MyStruct struct { Field1 string Field2 int } func (m *MyStruct) UnmarshalYAML(node *node.Node) error { // Use node.Load with options for strict checking err := node.Load(m, node.WithKnownFields()) if err != nil { // Handle unknown fields error specifically if needed if errors.Is(err, node.ErrUnknownField) { return fmt.Errorf("unknown field encountered: %w", err) } return err } return nil } ``` -------------------------------- ### Scanner Test: Detailed Token Properties Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Verifies token properties, including style and value, for a single-quoted scalar. ```yaml - scan-tokens-detailed: name: Single quoted scalar yaml: |- 'hello world' want: - STREAM_START_TOKEN - SCALAR_TOKEN: style: SINGLE_QUOTED_SCALAR_STYLE value: hello world - STREAM_END_TOKEN ``` -------------------------------- ### Forcing Canonical YAML Output Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Enables strictly canonical YAML output with explicit tags, primarily for debugging and spec testing. ```go yaml.NewDumper(w, yaml.WithCanonical(true)) ``` -------------------------------- ### Test Parser Cleanup: Delete Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Tests the cleanup functionality of the parser using the Delete method. It verifies that after deletion, the input and buffer lengths are reset to 0, indicating proper resource release. ```yaml - api-delete: name: Parser delete with: NewParser byte: true init: [SetInputString, test] test: - len: [input, 0] - len: [buffer, 0] ``` -------------------------------- ### Always Emitting Document End Marker Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Ensures that the document end marker (`...`) is always emitted at the end of the document. ```go yaml.NewDumper(w, yaml.WithExplicitEnd()) ``` -------------------------------- ### Test Parser Panic: SetInputString Twice Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Tests that calling SetInputString more than once on a parser causes a panic. The test verifies that the panic message contains the expected substring 'must set the input source only once'. ```yaml - api-panic: name: Parser set input string twice with: NewParser byte: true init: [SetInputString, first] call: [SetInputString, second] want: must set the input source only once ``` -------------------------------- ### Parser Test: Error Detection Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Verifies error detection during parsing for invalid YAML syntax. ```yaml - parse-error: name: Error state yaml: | key: : invalid ``` -------------------------------- ### Test Enum String Method: ScalarStyle Plain Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Tests the String() method for the ScalarStyle enum, specifically for the PLAIN_SCALAR_STYLE value. It asserts that the String() method returns 'Plain'. ```yaml - enum-string: name: Scalar style plain enum: [ScalarStyle, PLAIN_SCALAR_STYLE] want: Plain ``` -------------------------------- ### Test Scalar Type Resolution: Negative Float Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Tests the scalar type resolution for a negative float. The input '-2.5' is expected to be resolved to the float64 type. ```yaml - scalar-resolution: name: Negative float yaml: "-2.5" want: -2.5 ``` -------------------------------- ### Set Quote Preference for Strings Source: https://github.com/yaml/go-yaml/blob/main/docs/options.md Control the type of quotes used for strings that require quoting. This option affects strings that look like other YAML types, have leading/trailing whitespace, contain special characters, or are empty in certain contexts. ```go yaml.NewDumper(w, yaml.WithQuotePreference(yaml.QuoteSingle)) ``` ```go yaml.NewDumper(w, yaml.WithQuotePreference(yaml.QuoteDouble)) ``` ```go yaml.NewDumper(w, yaml.WithQuotePreference(yaml.QuoteLegacy)) ``` -------------------------------- ### Test Scalar Type Resolution: Positive Integer Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Tests the scalar type resolution for a positive integer. The input '42' is expected to be resolved to the integer type. ```yaml - scalar-resolution: name: Positive integer yaml: "42" want: 42 ``` -------------------------------- ### Scanner Test: Error Detection Source: https://github.com/yaml/go-yaml/blob/main/internal/libyaml/README.md Verifies error detection for invalid characters during scanning. ```yaml - scan-error: name: Invalid character yaml: "\x01" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.