Skip to content

Commit 5181037

Browse files
committed
Merge branch 'yaml'
* yaml: Add 'yaml' build tag for conditionally using gopkg.in/yaml.v2 Add YAML() for generating YAML blocks
2 parents 5c04ecb + 29a1d63 commit 5181037

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

util/tap.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,15 @@ func (t *T) Diagnostic(message string) {
151151
func (t *T) Diagnosticf(format string, a ...interface{}) {
152152
t.printf("# "+escapeNewlines(format)+"\n", a...)
153153
}
154+
155+
// YAML generates a YAML block from the message.
156+
func (t *T) YAML(message interface{}) error {
157+
bytes, err := yaml(message, " ")
158+
if err != nil {
159+
return err
160+
}
161+
t.printf(" ---\n ")
162+
t.printf(string(bytes))
163+
t.printf(" ...\n")
164+
return nil
165+
}

util/yaml_json.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// +build !yaml
2+
3+
package tap
4+
5+
import (
6+
"encoding/json"
7+
)
8+
9+
// yaml serializes a message to YAML. This implementation uses JSON,
10+
// which is a subset of YAML [1] and is implemented by Go's standard
11+
// library.
12+
//
13+
// [1]: http://www.yaml.org/spec/1.2/spec.html#id2759572
14+
func yaml(message interface{}, prefix string) (marshaled []byte, err error) {
15+
marshaled, err = json.MarshalIndent(message, prefix, " ")
16+
if err != nil {
17+
return marshaled, err
18+
}
19+
20+
marshaled = append(marshaled, []byte("\n")...)
21+
return marshaled, err
22+
}

util/yaml_yaml.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// +build yaml
2+
3+
package tap
4+
5+
import (
6+
"bytes"
7+
8+
goyaml "gopkg.in/yaml.v2"
9+
)
10+
11+
// yaml serializes a message to YAML. This implementation uses
12+
// non-JSON YAML, which has better prove support [1].
13+
//
14+
// [1]: https://rt.cpan.org/Public/Bug/Display.html?id=121606
15+
func yaml(message interface{}, prefix string) (marshaled []byte, err error) {
16+
marshaled, err = goyaml.Marshal(message)
17+
if err != nil {
18+
return marshaled, err
19+
}
20+
21+
marshaled = bytes.Replace(marshaled, []byte("\n"), []byte("\n"+prefix), -1)
22+
return marshaled[:len(marshaled)-len(prefix)], err
23+
}

0 commit comments

Comments
 (0)