ufasoli
ufasoli

Reputation: 1068

Go: How Do I Preserve Root Indentation in yaml?

I'm having trouble while re-encoding a YAML file with go and yaml.v3. Basically I have a YAML file for which the root indentation is 6 (the root is indented by 6 spaces).

I need to read this file then manipulate a few values and rewrite the file, however when rewriting the YAML structure to file I loose this indentation. Any idea of how I can achieve this? otherwise I'll probably re-read the file as a text file and add the indentation.

Below is the code I'm using.

YAML file excerpt:

      doc:
        a: 'default'
        b: 42
        c: 3
        structure: 'flat'

     
      use_timezone: ''
      kafka_nodes: 3
      

Parsing the YAML file and writing back to file

var ymlConfig yaml.Node
err = yaml.Unmarshal([]byte(pullConfig()), &ymlConfig)
//code ommited for brievity (some value verification and modification)

file, err := os.OpenFile("config.yml", os.O_WRONLY, os.ModeAppend)
if err != nil {
    panic(err)
}
defer file.Close()

d := yaml.NewEncoder(file)
d.SetIndent(4)// tried changing the indent but it does not change the root
defer d.Close()


if err := d.Encode(&ymlConfig); err != nil {
    panic(err)
}

Result of re encoding

doc:
  a: 'default'
  b: 42
  c: 3
  structure: 'flat'

     
use_timezone: ''
kafka_nodes: 3
      

Upvotes: 3

Views: 3382

Answers (1)

Steven Eckhoff
Steven Eckhoff

Reputation: 1042

You could do something as simple as this.

package main

import (
    "bytes"
    "fmt"
    "gopkg.in/yaml.v3"
)

func addRootIndent(b []byte, n int) []byte {
    prefix := append([]byte("\n"), bytes.Repeat([]byte(" "), n)...)
    b = append(prefix[1:], b...)  // Indent first line
    return bytes.ReplaceAll(b, []byte("\n"), prefix)
}

func main() {
    t := struct {
        Doc map[string]interface{}
    } {
        Doc: map[string]interface{}{
            "a": "The meaning is...",
            "b": 42,
        },
    }

    b, _ := yaml.Marshal(t)
    b = addRootIndent(b, 6)

    fmt.Println(string(b))
}

To alter the indentation in the yaml doc use

func (e *Encoder) SetIndent(spaces int)

Upvotes: 2

Related Questions