commit 72cb1db80f2f4a272e2a55bc202a2cf8141e3873
parent a794732c16b21f34a8b12197e2709e76cdf5f811
Author: yuin <yuin@inforno.net>
Date: Sat, 31 Oct 2020 15:31:25 +0900
Add TryGet
Diffstat:
2 files changed, 39 insertions(+), 1 deletion(-)
diff --git a/meta.go b/meta.go
@@ -37,6 +37,20 @@ func Get(pc parser.Context) map[string]interface{} {
return d.Map
}
+// TryGet tries to get a YAML metadata.
+// If there are YAML parsing errors, then nil and error are returned
+func TryGet(pc parser.Context) (map[string]interface{}, error) {
+ dtmp := pc.Get(contextKey)
+ if dtmp == nil {
+ return nil, nil
+ }
+ d := dtmp.(*data)
+ if d.Error != nil {
+ return nil, d.Error
+ }
+ return d.Map, nil
+}
+
// GetItems returns a YAML metadata.
// GetItems preserves defined key order.
func GetItems(pc parser.Context) yaml.MapSlice {
@@ -48,6 +62,21 @@ func GetItems(pc parser.Context) yaml.MapSlice {
return d.Items
}
+// TryGetItems returns a YAML metadata.
+// TryGetItems preserves defined key order.
+// If there are YAML parsing errors, then nil and erro are returned.
+func TryGetItems(pc parser.Context) (yaml.MapSlice, error) {
+ dtmp := pc.Get(contextKey)
+ if dtmp == nil {
+ return nil, nil
+ }
+ d := dtmp.(*data)
+ if d.Error != nil {
+ return nil, d.Error
+ }
+ return d.Items, nil
+}
+
type metaParser struct {
}
diff --git a/meta_test.go b/meta_test.go
@@ -128,7 +128,8 @@ Tags:
`
var buf bytes.Buffer
- if err := markdown.Convert([]byte(source), &buf); err != nil {
+ context := parser.NewContext()
+ if err := markdown.Convert([]byte(source), &buf, parser.WithContext(context)); err != nil {
panic(err)
}
if buf.String() != `Title: goldmark-meta
@@ -143,6 +144,14 @@ Tags:
` {
t.Error("invalid error output")
}
+
+ v, err := TryGet(context)
+ if err == nil {
+ t.Error("error should not be nil")
+ }
+ if v != nil {
+ t.Error("data should be nil when there are errors")
+ }
}
func TestMetaTableWithBlankline(t *testing.T) {