Преглед изворни кода

Support custom indentation via Encoder.SetIndent.

Gustavo Niemeyer пре 7 година
родитељ
комит
2c9fce8bed
3 измењених фајлова са 21 додато и 0 уклоњено
  1. 2 0
      encode.go
  2. 11 0
      encode_test.go
  3. 8 0
      yaml.go

+ 2 - 0
encode.go

@@ -18,6 +18,7 @@ type encoder struct {
 	event    yaml_event_t
 	out      []byte
 	flow     bool
+	indent   int
 	doneInit bool
 }
 
@@ -41,6 +42,7 @@ func (e *encoder) init() {
 	if e.doneInit {
 		return
 	}
+	e.emitter.best_indent = e.indent
 	yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING)
 	e.emit()
 	e.doneInit = true

+ 11 - 0
encode_test.go

@@ -512,6 +512,17 @@ func (s *S) TestMarshalerError(c *C) {
 	c.Assert(err, Equals, failingErr)
 }
 
+func (s *S) TestSetIndent(c *C) {
+	var buf bytes.Buffer
+	enc := yaml.NewEncoder(&buf)
+	enc.SetIndent(8)
+	err := enc.Encode(map[string]interface{}{"a": map[string]interface{}{"b": map[string]string{"c": "d"}}})
+	c.Assert(err, Equals, nil)
+	err = enc.Close()
+	c.Assert(err, Equals, nil)
+	c.Assert(buf.String(), Equals, "a:\n        b:\n                c: d\n")
+}
+
 func (s *S) TestSortedOutput(c *C) {
 	order := []interface{}{
 		false,

+ 8 - 0
yaml.go

@@ -239,6 +239,14 @@ func (e *Encoder) Encode(v interface{}) (err error) {
 	return nil
 }
 
+// SetIndent changes the used indentation used when encoding.
+func (e *Encoder) SetIndent(spaces int) {
+	if spaces < 0 {
+		panic("yaml: cannot indent to a negative number of spaces")
+	}
+	e.encoder.indent = spaces
+}
+
 // Close closes the encoder by writing any remaining data.
 // It does not write a stream terminating string "...".
 func (e *Encoder) Close() (err error) {