| 1 | package yaml |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | |
| 10 | "github.com/goccy/go-yaml/ast" |
| 11 | "github.com/goccy/go-yaml/parser" |
| 12 | "github.com/goccy/go-yaml/printer" |
| 13 | ) |
| 14 | |
| 15 | // PathString create Path from string |
| 16 | // |
| 17 | // YAMLPath rule |
| 18 | // $ : the root object/element |
| 19 | // . : child operator |
| 20 | // .. : recursive descent |
| 21 | // [num] : object/element of array by number |
| 22 | // [*] : all objects/elements for array. |
| 23 | // |
| 24 | // If you want to use reserved characters such as `.` and `*` as a key name, |
| 25 | // enclose them in single quotation as follows ( $.foo.'bar.baz-*'.hoge ). |
| 26 | // If you want to use a single quote with reserved characters, escape it with `\` ( $.foo.'bar.baz\'s value'.hoge ). |
| 27 | func PathString(s string) (*Path, error) { |
| 28 | buf := []rune(s) |
| 29 | length := len(buf) |
| 30 | cursor := 0 |
| 31 | builder := &PathBuilder{} |
| 32 | for cursor < length { |
| 33 | c := buf[cursor] |
| 34 | switch c { |
| 35 | case '$': |
| 36 | builder = builder.Root() |
| 37 | cursor++ |
| 38 | case '.': |
| 39 | b, buf, c, err := parsePathDot(builder, buf, cursor) |
| 40 | if err != nil { |
| 41 | return nil, err |
| 42 | } |
| 43 | length = len(buf) |
| 44 | builder = b |
| 45 | cursor = c |
| 46 | case '[': |
| 47 | b, buf, c, err := parsePathIndex(builder, buf, cursor) |
| 48 | if err != nil { |
| 49 | return nil, err |
| 50 | } |
| 51 | length = len(buf) |
| 52 | builder = b |
| 53 | cursor = c |
| 54 | default: |
| 55 | return nil, fmt.Errorf("invalid path at %d: %w", cursor, ErrInvalidPathString) |
| 56 | } |
| 57 | } |
| 58 | return builder.Build(), nil |
| 59 | } |
| 60 | |
| 61 | func parsePathRecursive(b *PathBuilder, buf []rune, cursor int) (*PathBuilder, []rune, int, error) { |
| 62 | length := len(buf) |
| 63 | cursor += 2 // skip .. characters |
| 64 | start := cursor |
| 65 | for ; cursor < length; cursor++ { |
| 66 | c := buf[cursor] |
| 67 | switch c { |
| 68 | case '$': |
| 69 | return nil, nil, 0, fmt.Errorf("specified '$' after '..' character: %w", ErrInvalidPathString) |
| 70 | case '*': |
| 71 | return nil, nil, 0, fmt.Errorf("specified '*' after '..' character: %w", ErrInvalidPathString) |
| 72 | case '.', '[': |
| 73 | goto end |
| 74 | case ']': |
| 75 | return nil, nil, 0, fmt.Errorf("specified ']' after '..' character: %w", ErrInvalidPathString) |
| 76 | } |
| 77 | } |
| 78 | end: |
| 79 | if start == cursor { |
| 80 | return nil, nil, 0, fmt.Errorf("not found recursive selector: %w", ErrInvalidPathString) |
| 81 | } |
| 82 | return b.Recursive(string(buf[start:cursor])), buf, cursor, nil |
| 83 | } |
| 84 | |
| 85 | func parsePathDot(b *PathBuilder, buf []rune, cursor int) (*PathBuilder, []rune, int, error) { |
| 86 | if b.root == nil || b.node == nil { |
| 87 | return nil, nil, 0, fmt.Errorf("required '$' character at first: %w", ErrInvalidPathString) |
| 88 | } |
| 89 | length := len(buf) |
| 90 | if cursor+1 < length && buf[cursor+1] == '.' { |
| 91 | b, buf, c, err := parsePathRecursive(b, buf, cursor) |
| 92 | if err != nil { |
| 93 | return nil, nil, 0, err |
| 94 | } |
| 95 | return b, buf, c, nil |
| 96 | } |
| 97 | cursor++ // skip . character |
| 98 | start := cursor |
| 99 | |
| 100 | // if started single quote, looking for end single quote char |
| 101 | if cursor < length && buf[cursor] == '\'' { |
| 102 | return parseQuotedKey(b, buf, cursor) |
| 103 | } |
| 104 | for ; cursor < length; cursor++ { |
| 105 | c := buf[cursor] |
| 106 | switch c { |
| 107 | case '$': |
| 108 | return nil, nil, 0, fmt.Errorf("specified '$' after '.' character: %w", ErrInvalidPathString) |
| 109 | case '*': |
| 110 | return nil, nil, 0, fmt.Errorf("specified '*' after '.' character: %w", ErrInvalidPathString) |
| 111 | case '.', '[': |
| 112 | goto end |
| 113 | case ']': |
| 114 | return nil, nil, 0, fmt.Errorf("specified ']' after '.' character: %w", ErrInvalidPathString) |
| 115 | } |
| 116 | } |
| 117 | end: |
| 118 | if start == cursor { |
| 119 | return nil, nil, 0, fmt.Errorf("could not find by empty key: %w", ErrInvalidPathString) |
| 120 | } |
| 121 | return b.child(string(buf[start:cursor])), buf, cursor, nil |
| 122 | } |
| 123 | |
| 124 | func parseQuotedKey(b *PathBuilder, buf []rune, cursor int) (*PathBuilder, []rune, int, error) { |
| 125 | if b.root == nil || b.node == nil { |
| 126 | return nil, nil, 0, fmt.Errorf("required '$' character at first: %w", ErrInvalidPathString) |
| 127 | } |
| 128 | |
| 129 | cursor++ // skip single quote |
| 130 | start := cursor |
| 131 | length := len(buf) |
| 132 | var foundEndDelim bool |
| 133 | for ; cursor < length; cursor++ { |
| 134 | switch buf[cursor] { |
| 135 | case '\\': |
| 136 | buf = append(append([]rune{}, buf[:cursor]...), buf[cursor+1:]...) |
| 137 | length = len(buf) |
| 138 | case '\'': |
| 139 | foundEndDelim = true |
| 140 | goto end |
| 141 | } |
| 142 | } |
| 143 | end: |
| 144 | if !foundEndDelim { |
| 145 | return nil, nil, 0, fmt.Errorf("could not find end delimiter for key: %w", ErrInvalidPathString) |
| 146 | } |
| 147 | if start == cursor { |
| 148 | return nil, nil, 0, fmt.Errorf("could not find by empty key: %w", ErrInvalidPathString) |
| 149 | } |
| 150 | selector := buf[start:cursor] |
| 151 | cursor++ |
| 152 | if cursor < length { |
| 153 | switch buf[cursor] { |
| 154 | case '$': |
| 155 | return nil, nil, 0, fmt.Errorf("specified '$' after '.' character: %w", ErrInvalidPathString) |
| 156 | case '*': |
| 157 | return nil, nil, 0, fmt.Errorf("specified '*' after '.' character: %w", ErrInvalidPathString) |
| 158 | case ']': |
| 159 | return nil, nil, 0, fmt.Errorf("specified ']' after '.' character: %w", ErrInvalidPathString) |
| 160 | } |
| 161 | } |
| 162 | return b.child(string(selector)), buf, cursor, nil |
| 163 | } |
| 164 | |
| 165 | func parsePathIndex(b *PathBuilder, buf []rune, cursor int) (*PathBuilder, []rune, int, error) { |
| 166 | if b.root == nil || b.node == nil { |
| 167 | return nil, nil, 0, fmt.Errorf("required '$' character at first: %w", ErrInvalidPathString) |
| 168 | } |
| 169 | |
| 170 | length := len(buf) |
| 171 | cursor++ // skip '[' character |
| 172 | if length <= cursor { |
| 173 | return nil, nil, 0, fmt.Errorf("unexpected end of YAML Path: %w", ErrInvalidPathString) |
| 174 | } |
| 175 | c := buf[cursor] |
| 176 | switch c { |
| 177 | case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*': |
| 178 | start := cursor |
| 179 | cursor++ |
| 180 | for ; cursor < length; cursor++ { |
| 181 | c := buf[cursor] |
| 182 | switch c { |
| 183 | case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': |
| 184 | continue |
| 185 | } |
| 186 | break |
| 187 | } |
| 188 | if buf[cursor] != ']' { |
| 189 | return nil, nil, 0, fmt.Errorf("invalid character %s at %d: %w", string(buf[cursor]), cursor, ErrInvalidPathString) |
| 190 | } |
| 191 | numOrAll := string(buf[start:cursor]) |
| 192 | if numOrAll == "*" { |
| 193 | return b.IndexAll(), buf, cursor + 1, nil |
| 194 | } |
| 195 | num, err := strconv.ParseInt(numOrAll, 10, 64) |
| 196 | if err != nil { |
| 197 | return nil, nil, 0, err |
| 198 | } |
| 199 | return b.Index(uint(num)), buf, cursor + 1, nil |
| 200 | } |
| 201 | return nil, nil, 0, fmt.Errorf("invalid character %q at %d: %w", c, cursor, ErrInvalidPathString) |
| 202 | } |
| 203 | |
| 204 | // Path represent YAMLPath ( like a JSONPath ). |
| 205 | type Path struct { |
| 206 | node pathNode |
| 207 | } |
| 208 | |
| 209 | // String path to text. |
| 210 | func (p *Path) String() string { |
| 211 | return p.node.String() |
| 212 | } |
| 213 | |
| 214 | // Read decode from r and set extracted value by YAMLPath to v. |
| 215 | func (p *Path) Read(r io.Reader, v interface{}) error { |
| 216 | node, err := p.ReadNode(r) |
| 217 | if err != nil { |
| 218 | return err |
| 219 | } |
| 220 | if err := Unmarshal([]byte(node.String()), v); err != nil { |
| 221 | return err |
| 222 | } |
| 223 | return nil |
| 224 | } |
| 225 | |
| 226 | // ReadNode create AST from r and extract node by YAMLPath. |
| 227 | func (p *Path) ReadNode(r io.Reader) (ast.Node, error) { |
| 228 | if p.node == nil { |
| 229 | return nil, ErrInvalidPath |
| 230 | } |
| 231 | var buf bytes.Buffer |
| 232 | if _, err := io.Copy(&buf, r); err != nil { |
| 233 | return nil, err |
| 234 | } |
| 235 | f, err := parser.ParseBytes(buf.Bytes(), 0) |
| 236 | if err != nil { |
| 237 | return nil, err |
| 238 | } |
| 239 | node, err := p.FilterFile(f) |
| 240 | if err != nil { |
| 241 | return nil, err |
| 242 | } |
| 243 | return node, nil |
| 244 | } |
| 245 | |
| 246 | // Filter filter from target by YAMLPath and set it to v. |
| 247 | func (p *Path) Filter(target, v interface{}) error { |
| 248 | b, err := Marshal(target) |
| 249 | if err != nil { |
| 250 | return err |
| 251 | } |
| 252 | if err := p.Read(bytes.NewBuffer(b), v); err != nil { |
| 253 | return err |
| 254 | } |
| 255 | return nil |
| 256 | } |
| 257 | |
| 258 | // FilterFile filter from ast.File by YAMLPath. |
| 259 | func (p *Path) FilterFile(f *ast.File) (ast.Node, error) { |
| 260 | for _, doc := range f.Docs { |
| 261 | node, err := p.FilterNode(doc.Body) |
| 262 | if err != nil { |
| 263 | return nil, err |
| 264 | } |
| 265 | if node != nil { |
| 266 | return node, nil |
| 267 | } |
| 268 | } |
| 269 | return nil, fmt.Errorf("failed to find path ( %s ): %w", p.node, ErrNotFoundNode) |
| 270 | } |
| 271 | |
| 272 | // FilterNode filter from node by YAMLPath. |
| 273 | func (p *Path) FilterNode(node ast.Node) (ast.Node, error) { |
| 274 | if node == nil { |
| 275 | return nil, nil |
| 276 | } |
| 277 | n, err := p.node.filter(node) |
| 278 | if err != nil { |
| 279 | return nil, err |
| 280 | } |
| 281 | return n, nil |
| 282 | } |
| 283 | |
| 284 | // MergeFromReader merge YAML text into ast.File. |
| 285 | func (p *Path) MergeFromReader(dst *ast.File, src io.Reader) error { |
| 286 | var buf bytes.Buffer |
| 287 | if _, err := io.Copy(&buf, src); err != nil { |
| 288 | return err |
| 289 | } |
| 290 | file, err := parser.ParseBytes(buf.Bytes(), 0) |
| 291 | if err != nil { |
| 292 | return err |
| 293 | } |
| 294 | if err := p.MergeFromFile(dst, file); err != nil { |
| 295 | return err |
| 296 | } |
| 297 | return nil |
| 298 | } |
| 299 | |
| 300 | // MergeFromFile merge ast.File into ast.File. |
| 301 | func (p *Path) MergeFromFile(dst *ast.File, src *ast.File) error { |
| 302 | base, err := p.FilterFile(dst) |
| 303 | if err != nil { |
| 304 | return err |
| 305 | } |
| 306 | for _, doc := range src.Docs { |
| 307 | if err := ast.Merge(base, doc); err != nil { |
| 308 | return err |
| 309 | } |
| 310 | } |
| 311 | return nil |
| 312 | } |
| 313 | |
| 314 | // MergeFromNode merge ast.Node into ast.File. |
| 315 | func (p *Path) MergeFromNode(dst *ast.File, src ast.Node) error { |
| 316 | base, err := p.FilterFile(dst) |
| 317 | if err != nil { |
| 318 | return err |
| 319 | } |
| 320 | if err := ast.Merge(base, src); err != nil { |
| 321 | return err |
| 322 | } |
| 323 | return nil |
| 324 | } |
| 325 | |
| 326 | // ReplaceWithReader replace ast.File with io.Reader. |
| 327 | func (p *Path) ReplaceWithReader(dst *ast.File, src io.Reader) error { |
| 328 | var buf bytes.Buffer |
| 329 | if _, err := io.Copy(&buf, src); err != nil { |
| 330 | return err |
| 331 | } |
| 332 | file, err := parser.ParseBytes(buf.Bytes(), 0) |
| 333 | if err != nil { |
| 334 | return err |
| 335 | } |
| 336 | if err := p.ReplaceWithFile(dst, file); err != nil { |
| 337 | return err |
| 338 | } |
| 339 | return nil |
| 340 | } |
| 341 | |
| 342 | // ReplaceWithFile replace ast.File with ast.File. |
| 343 | func (p *Path) ReplaceWithFile(dst *ast.File, src *ast.File) error { |
| 344 | for _, doc := range src.Docs { |
| 345 | if err := p.ReplaceWithNode(dst, doc); err != nil { |
| 346 | return err |
| 347 | } |
| 348 | } |
| 349 | return nil |
| 350 | } |
| 351 | |
| 352 | // ReplaceNode replace ast.File with ast.Node. |
| 353 | func (p *Path) ReplaceWithNode(dst *ast.File, node ast.Node) error { |
| 354 | for _, doc := range dst.Docs { |
| 355 | if node.Type() == ast.DocumentType { |
| 356 | node = node.(*ast.DocumentNode).Body |
| 357 | } |
| 358 | if err := p.node.replace(doc.Body, node); err != nil { |
| 359 | return err |
| 360 | } |
| 361 | } |
| 362 | return nil |
| 363 | } |
| 364 | |
| 365 | // AnnotateSource add annotation to passed source ( see section 5.1 in README.md ). |
| 366 | func (p *Path) AnnotateSource(source []byte, colored bool) ([]byte, error) { |
| 367 | file, err := parser.ParseBytes([]byte(source), 0) |
| 368 | if err != nil { |
| 369 | return nil, err |
| 370 | } |
| 371 | node, err := p.FilterFile(file) |
| 372 | if err != nil { |
| 373 | return nil, err |
| 374 | } |
| 375 | var pp printer.Printer |
| 376 | return []byte(pp.PrintErrorToken(node.GetToken(), colored)), nil |
| 377 | } |
| 378 | |
| 379 | // PathBuilder represent builder for YAMLPath. |
| 380 | type PathBuilder struct { |
| 381 | root *rootNode |
| 382 | node pathNode |
| 383 | } |
| 384 | |
| 385 | // Root add '$' to current path. |
| 386 | func (b *PathBuilder) Root() *PathBuilder { |
| 387 | root := newRootNode() |
| 388 | return &PathBuilder{root: root, node: root} |
| 389 | } |
| 390 | |
| 391 | // IndexAll add '[*]' to current path. |
| 392 | func (b *PathBuilder) IndexAll() *PathBuilder { |
| 393 | b.node = b.node.chain(newIndexAllNode()) |
| 394 | return b |
| 395 | } |
| 396 | |
| 397 | // Recursive add '..selector' to current path. |
| 398 | func (b *PathBuilder) Recursive(selector string) *PathBuilder { |
| 399 | b.node = b.node.chain(newRecursiveNode(selector)) |
| 400 | return b |
| 401 | } |
| 402 | |
| 403 | func (b *PathBuilder) containsReservedPathCharacters(path string) bool { |
| 404 | if strings.Contains(path, ".") { |
| 405 | return true |
| 406 | } |
| 407 | if strings.Contains(path, "*") { |
| 408 | return true |
| 409 | } |
| 410 | return false |
| 411 | } |
| 412 | |
| 413 | func (b *PathBuilder) enclosedSingleQuote(name string) bool { |
| 414 | return strings.HasPrefix(name, "'") && strings.HasSuffix(name, "'") |
| 415 | } |
| 416 | |
| 417 | func (b *PathBuilder) normalizeSelectorName(name string) string { |
| 418 | if b.enclosedSingleQuote(name) { |
| 419 | // already escaped name |
| 420 | return name |
| 421 | } |
| 422 | if b.containsReservedPathCharacters(name) { |
| 423 | escapedName := strings.ReplaceAll(name, `'`, `\'`) |
| 424 | return "'" + escapedName + "'" |
| 425 | } |
| 426 | return name |
| 427 | } |
| 428 | |
| 429 | func (b *PathBuilder) child(name string) *PathBuilder { |
| 430 | b.node = b.node.chain(newSelectorNode(name)) |
| 431 | return b |
| 432 | } |
| 433 | |
| 434 | // Child add '.name' to current path. |
| 435 | func (b *PathBuilder) Child(name string) *PathBuilder { |
| 436 | return b.child(b.normalizeSelectorName(name)) |
| 437 | } |
| 438 | |
| 439 | // Index add '[idx]' to current path. |
| 440 | func (b *PathBuilder) Index(idx uint) *PathBuilder { |
| 441 | b.node = b.node.chain(newIndexNode(idx)) |
| 442 | return b |
| 443 | } |
| 444 | |
| 445 | // Build build YAMLPath. |
| 446 | func (b *PathBuilder) Build() *Path { |
| 447 | return &Path{node: b.root} |
| 448 | } |
| 449 | |
| 450 | type pathNode interface { |
| 451 | fmt.Stringer |
| 452 | chain(pathNode) pathNode |
| 453 | filter(ast.Node) (ast.Node, error) |
| 454 | replace(ast.Node, ast.Node) error |
| 455 | } |
| 456 | |
| 457 | type basePathNode struct { |
| 458 | child pathNode |
| 459 | } |
| 460 | |
| 461 | func (n *basePathNode) chain(node pathNode) pathNode { |
| 462 | n.child = node |
| 463 | return node |
| 464 | } |
| 465 | |
| 466 | type rootNode struct { |
| 467 | *basePathNode |
| 468 | } |
| 469 | |
| 470 | func newRootNode() *rootNode { |
| 471 | return &rootNode{basePathNode: &basePathNode{}} |
| 472 | } |
| 473 | |
| 474 | func (n *rootNode) String() string { |
| 475 | s := "$" |
| 476 | if n.child != nil { |
| 477 | s += n.child.String() |
| 478 | } |
| 479 | return s |
| 480 | } |
| 481 | |
| 482 | func (n *rootNode) filter(node ast.Node) (ast.Node, error) { |
| 483 | if n.child == nil { |
| 484 | return node, nil |
| 485 | } |
| 486 | filtered, err := n.child.filter(node) |
| 487 | if err != nil { |
| 488 | return nil, err |
| 489 | } |
| 490 | return filtered, nil |
| 491 | } |
| 492 | |
| 493 | func (n *rootNode) replace(node ast.Node, target ast.Node) error { |
| 494 | if n.child == nil { |
| 495 | return nil |
| 496 | } |
| 497 | if err := n.child.replace(node, target); err != nil { |
| 498 | return err |
| 499 | } |
| 500 | return nil |
| 501 | } |
| 502 | |
| 503 | type selectorNode struct { |
| 504 | *basePathNode |
| 505 | selector string |
| 506 | } |
| 507 | |
| 508 | func newSelectorNode(selector string) *selectorNode { |
| 509 | return &selectorNode{ |
| 510 | basePathNode: &basePathNode{}, |
| 511 | selector: selector, |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | func (n *selectorNode) filter(node ast.Node) (ast.Node, error) { |
| 516 | selector := n.selector |
| 517 | if len(selector) > 1 && selector[0] == '\'' && selector[len(selector)-1] == '\'' { |
| 518 | selector = selector[1 : len(selector)-1] |
| 519 | } |
| 520 | switch node.Type() { |
| 521 | case ast.MappingType: |
| 522 | for _, value := range node.(*ast.MappingNode).Values { |
| 523 | key := value.Key.GetToken().Value |
| 524 | if len(key) > 0 { |
| 525 | switch key[0] { |
| 526 | case '"': |
| 527 | var err error |
| 528 | key, err = strconv.Unquote(key) |
| 529 | if err != nil { |
| 530 | return nil, err |
| 531 | } |
| 532 | case '\'': |
| 533 | if len(key) > 1 && key[len(key)-1] == '\'' { |
| 534 | key = key[1 : len(key)-1] |
| 535 | } |
| 536 | } |
| 537 | } |
| 538 | if key == selector { |
| 539 | if n.child == nil { |
| 540 | return value.Value, nil |
| 541 | } |
| 542 | filtered, err := n.child.filter(value.Value) |
| 543 | if err != nil { |
| 544 | return nil, err |
| 545 | } |
| 546 | return filtered, nil |
| 547 | } |
| 548 | } |
| 549 | case ast.MappingValueType: |
| 550 | value, _ := node.(*ast.MappingValueNode) |
| 551 | key := value.Key.GetToken().Value |
| 552 | if key == selector { |
| 553 | if n.child == nil { |
| 554 | return value.Value, nil |
| 555 | } |
| 556 | filtered, err := n.child.filter(value.Value) |
| 557 | if err != nil { |
| 558 | return nil, err |
| 559 | } |
| 560 | return filtered, nil |
| 561 | } |
| 562 | default: |
| 563 | return nil, fmt.Errorf("expected node type is map or map value. but got %s: %w", node.Type(), ErrInvalidQuery) |
| 564 | } |
| 565 | return nil, nil |
| 566 | } |
| 567 | |
| 568 | func (n *selectorNode) replaceMapValue(value *ast.MappingValueNode, target ast.Node) error { |
| 569 | key := value.Key.GetToken().Value |
| 570 | if key != n.selector { |
| 571 | return nil |
| 572 | } |
| 573 | if n.child == nil { |
| 574 | if err := value.Replace(target); err != nil { |
| 575 | return err |
| 576 | } |
| 577 | } else { |
| 578 | if err := n.child.replace(value.Value, target); err != nil { |
| 579 | return err |
| 580 | } |
| 581 | } |
| 582 | return nil |
| 583 | } |
| 584 | |
| 585 | func (n *selectorNode) replace(node ast.Node, target ast.Node) error { |
| 586 | switch node.Type() { |
| 587 | case ast.MappingType: |
| 588 | for _, value := range node.(*ast.MappingNode).Values { |
| 589 | if err := n.replaceMapValue(value, target); err != nil { |
| 590 | return err |
| 591 | } |
| 592 | } |
| 593 | case ast.MappingValueType: |
| 594 | value, _ := node.(*ast.MappingValueNode) |
| 595 | if err := n.replaceMapValue(value, target); err != nil { |
| 596 | return err |
| 597 | } |
| 598 | default: |
| 599 | return fmt.Errorf("expected node type is map or map value. but got %s: %w", node.Type(), ErrInvalidQuery) |
| 600 | } |
| 601 | return nil |
| 602 | } |
| 603 | |
| 604 | func (n *selectorNode) String() string { |
| 605 | var builder PathBuilder |
| 606 | selector := builder.normalizeSelectorName(n.selector) |
| 607 | s := fmt.Sprintf(".%s", selector) |
| 608 | if n.child != nil { |
| 609 | s += n.child.String() |
| 610 | } |
| 611 | return s |
| 612 | } |
| 613 | |
| 614 | type indexNode struct { |
| 615 | *basePathNode |
| 616 | selector uint |
| 617 | } |
| 618 | |
| 619 | func newIndexNode(selector uint) *indexNode { |
| 620 | return &indexNode{ |
| 621 | basePathNode: &basePathNode{}, |
| 622 | selector: selector, |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | func (n *indexNode) filter(node ast.Node) (ast.Node, error) { |
| 627 | if node.Type() != ast.SequenceType { |
| 628 | return nil, fmt.Errorf("expected sequence type node. but got %s: %w", node.Type(), ErrInvalidQuery) |
| 629 | } |
| 630 | sequence, _ := node.(*ast.SequenceNode) |
| 631 | if n.selector >= uint(len(sequence.Values)) { |
| 632 | return nil, fmt.Errorf("expected index is %d. but got sequences has %d items: %w", n.selector, len(sequence.Values), ErrInvalidQuery) |
| 633 | } |
| 634 | value := sequence.Values[n.selector] |
| 635 | if n.child == nil { |
| 636 | return value, nil |
| 637 | } |
| 638 | filtered, err := n.child.filter(value) |
| 639 | if err != nil { |
| 640 | return nil, err |
| 641 | } |
| 642 | return filtered, nil |
| 643 | } |
| 644 | |
| 645 | func (n *indexNode) replace(node ast.Node, target ast.Node) error { |
| 646 | if node.Type() != ast.SequenceType { |
| 647 | return fmt.Errorf("expected sequence type node. but got %s: %w", node.Type(), ErrInvalidQuery) |
| 648 | } |
| 649 | sequence, _ := node.(*ast.SequenceNode) |
| 650 | if n.selector >= uint(len(sequence.Values)) { |
| 651 | return fmt.Errorf("expected index is %d. but got sequences has %d items: %w", n.selector, len(sequence.Values), ErrInvalidQuery) |
| 652 | } |
| 653 | if n.child == nil { |
| 654 | if err := sequence.Replace(int(n.selector), target); err != nil { |
| 655 | return err |
| 656 | } |
| 657 | return nil |
| 658 | } |
| 659 | if err := n.child.replace(sequence.Values[n.selector], target); err != nil { |
| 660 | return err |
| 661 | } |
| 662 | return nil |
| 663 | } |
| 664 | |
| 665 | func (n *indexNode) String() string { |
| 666 | s := fmt.Sprintf("[%d]", n.selector) |
| 667 | if n.child != nil { |
| 668 | s += n.child.String() |
| 669 | } |
| 670 | return s |
| 671 | } |
| 672 | |
| 673 | type indexAllNode struct { |
| 674 | *basePathNode |
| 675 | } |
| 676 | |
| 677 | func newIndexAllNode() *indexAllNode { |
| 678 | return &indexAllNode{ |
| 679 | basePathNode: &basePathNode{}, |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | func (n *indexAllNode) String() string { |
| 684 | s := "[*]" |
| 685 | if n.child != nil { |
| 686 | s += n.child.String() |
| 687 | } |
| 688 | return s |
| 689 | } |
| 690 | |
| 691 | func (n *indexAllNode) filter(node ast.Node) (ast.Node, error) { |
| 692 | if node.Type() != ast.SequenceType { |
| 693 | return nil, fmt.Errorf("expected sequence type node. but got %s: %w", node.Type(), ErrInvalidQuery) |
| 694 | } |
| 695 | sequence, _ := node.(*ast.SequenceNode) |
| 696 | if n.child == nil { |
| 697 | return sequence, nil |
| 698 | } |
| 699 | out := *sequence |
| 700 | out.Values = []ast.Node{} |
| 701 | for _, value := range sequence.Values { |
| 702 | filtered, err := n.child.filter(value) |
| 703 | if err != nil { |
| 704 | return nil, err |
| 705 | } |
| 706 | out.Values = append(out.Values, filtered) |
| 707 | } |
| 708 | return &out, nil |
| 709 | } |
| 710 | |
| 711 | func (n *indexAllNode) replace(node ast.Node, target ast.Node) error { |
| 712 | if node.Type() != ast.SequenceType { |
| 713 | return fmt.Errorf("expected sequence type node. but got %s: %w", node.Type(), ErrInvalidQuery) |
| 714 | } |
| 715 | sequence, _ := node.(*ast.SequenceNode) |
| 716 | if n.child == nil { |
| 717 | for idx := range sequence.Values { |
| 718 | if err := sequence.Replace(idx, target); err != nil { |
| 719 | return err |
| 720 | } |
| 721 | } |
| 722 | return nil |
| 723 | } |
| 724 | for _, value := range sequence.Values { |
| 725 | if err := n.child.replace(value, target); err != nil { |
| 726 | return err |
| 727 | } |
| 728 | } |
| 729 | return nil |
| 730 | } |
| 731 | |
| 732 | type recursiveNode struct { |
| 733 | *basePathNode |
| 734 | selector string |
| 735 | } |
| 736 | |
| 737 | func newRecursiveNode(selector string) *recursiveNode { |
| 738 | return &recursiveNode{ |
| 739 | basePathNode: &basePathNode{}, |
| 740 | selector: selector, |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | func (n *recursiveNode) String() string { |
| 745 | s := fmt.Sprintf("..%s", n.selector) |
| 746 | if n.child != nil { |
| 747 | s += n.child.String() |
| 748 | } |
| 749 | return s |
| 750 | } |
| 751 | |
| 752 | func (n *recursiveNode) filterNode(node ast.Node) (*ast.SequenceNode, error) { |
| 753 | sequence := &ast.SequenceNode{BaseNode: &ast.BaseNode{}} |
| 754 | switch typedNode := node.(type) { |
| 755 | case *ast.MappingNode: |
| 756 | for _, value := range typedNode.Values { |
| 757 | seq, err := n.filterNode(value) |
| 758 | if err != nil { |
| 759 | return nil, err |
| 760 | } |
| 761 | sequence.Values = append(sequence.Values, seq.Values...) |
| 762 | } |
| 763 | case *ast.MappingValueNode: |
| 764 | key := typedNode.Key.GetToken().Value |
| 765 | if n.selector == key { |
| 766 | sequence.Values = append(sequence.Values, typedNode.Value) |
| 767 | } |
| 768 | seq, err := n.filterNode(typedNode.Value) |
| 769 | if err != nil { |
| 770 | return nil, err |
| 771 | } |
| 772 | sequence.Values = append(sequence.Values, seq.Values...) |
| 773 | case *ast.SequenceNode: |
| 774 | for _, value := range typedNode.Values { |
| 775 | seq, err := n.filterNode(value) |
| 776 | if err != nil { |
| 777 | return nil, err |
| 778 | } |
| 779 | sequence.Values = append(sequence.Values, seq.Values...) |
| 780 | } |
| 781 | } |
| 782 | return sequence, nil |
| 783 | } |
| 784 | |
| 785 | func (n *recursiveNode) filter(node ast.Node) (ast.Node, error) { |
| 786 | sequence, err := n.filterNode(node) |
| 787 | if err != nil { |
| 788 | return nil, err |
| 789 | } |
| 790 | sequence.Start = node.GetToken() |
| 791 | return sequence, nil |
| 792 | } |
| 793 | |
| 794 | func (n *recursiveNode) replaceNode(node ast.Node, target ast.Node) error { |
| 795 | switch typedNode := node.(type) { |
| 796 | case *ast.MappingNode: |
| 797 | for _, value := range typedNode.Values { |
| 798 | if err := n.replaceNode(value, target); err != nil { |
| 799 | return err |
| 800 | } |
| 801 | } |
| 802 | case *ast.MappingValueNode: |
| 803 | key := typedNode.Key.GetToken().Value |
| 804 | if n.selector == key { |
| 805 | if err := typedNode.Replace(target); err != nil { |
| 806 | return err |
| 807 | } |
| 808 | } |
| 809 | if err := n.replaceNode(typedNode.Value, target); err != nil { |
| 810 | return err |
| 811 | } |
| 812 | case *ast.SequenceNode: |
| 813 | for _, value := range typedNode.Values { |
| 814 | if err := n.replaceNode(value, target); err != nil { |
| 815 | return err |
| 816 | } |
| 817 | } |
| 818 | } |
| 819 | return nil |
| 820 | } |
| 821 | |
| 822 | func (n *recursiveNode) replace(node ast.Node, target ast.Node) error { |
| 823 | if err := n.replaceNode(node, target); err != nil { |
| 824 | return err |
| 825 | } |
| 826 | return nil |
| 827 | } |