Skip to content

Commit

Permalink
Merge pull request #140 from goccy/feature/support-new-apis
Browse files Browse the repository at this point in the history
Add new convenient APIs
  • Loading branch information
goccy authored Jul 16, 2020
2 parents fc5218d + 174a7d2 commit 912026d
Show file tree
Hide file tree
Showing 10 changed files with 1,280 additions and 484 deletions.
32 changes: 7 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -308,27 +308,8 @@ import (
"fmt"

"github.com/goccy/go-yaml"
"github.com/goccy/go-yaml/parser"
"github.com/goccy/go-yaml/printer"
)

func yamlSourceByPath(originalSource string, pathStr string) (string, error) {
file, err := parser.ParseBytes([]byte(originalSource), 0)
if err != nil {
return "", err
}
path, err := yaml.PathString(pathStr)
if err != nil {
return "", err
}
node, err := path.FilterFile(file)
if err != nil {
return "", err
}
var p printer.Printer
return p.PrintErrorToken(node.GetToken(), true), nil
}

func main() {
yml := `
a: 1
Expand All @@ -343,19 +324,20 @@ b: "hello"
}
if v.A != 2 {
// output error with YAML source
source, err := yamlSourceByPath(yml, "$.a")
path, err := yaml.PathString("$.a")
if err != nil {
panic(err)
}
fmt.Printf("a value expected 2 but actual %d:\n%s\n", v.A, source)
source, err := path.AnnotateSource([]byte(yml), true)
if err != nil {
panic(err)
}
fmt.Printf("a value expected 2 but actual %d:\n%s\n", v.A, string(source))
}
}
```

`printer.PrintErrorToken` can output YAML source with error point,
and you can get `token.Token` of error point by `yaml.Path` .

output result is following
output result is the following.

<img src="https://user-images.githubusercontent.com/209884/84148813-7aca8680-aa9a-11ea-8fc9-37dece2ebdac.png"></img>

Expand Down
Loading

0 comments on commit 912026d

Please sign in to comment.