Skip to content

Commit

Permalink
Can traverse straight from parent operator (parent.blah)
Browse files Browse the repository at this point in the history
  • Loading branch information
mikefarah committed Sep 6, 2024
1 parent dff0122 commit 1846006
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
19 changes: 19 additions & 0 deletions pkg/yqlib/doc/operators/parent.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,25 @@ fruit: banana
name: sam
```
## Get parent attribute
Given a sample.yml file of:
```yaml
a:
fruit: apple
name: bob
b:
fruit: banana
name: sam
```
then
```bash
yq '.. | select(. == "banana") | parent.name' sample.yml
```
will output
```yaml
sam
```

## N-th parent
You can optionally supply the number of levels to go up for the parent, the default being 1.

Expand Down
4 changes: 2 additions & 2 deletions pkg/yqlib/lexer_participle.go
Original file line number Diff line number Diff line change
Expand Up @@ -517,15 +517,15 @@ func parentWithLevel() yqAction {

prefs := parentOpPreferences{Level: level}
op := &Operation{OperationType: getParentOpType, Value: getParentOpType.Type, StringValue: value, Preferences: prefs}
return &token{TokenType: operationToken, Operation: op}, nil
return &token{TokenType: operationToken, Operation: op, CheckForPostTraverse: true}, nil
}
}

func parentWithDefaultLevel() yqAction {
return func(rawToken lexer.Token) (*token, error) {
prefs := parentOpPreferences{Level: 1}
op := &Operation{OperationType: getParentOpType, Value: getParentOpType.Type, StringValue: getParentOpType.Type, Preferences: prefs}
return &token{TokenType: operationToken, Operation: op}, nil
return &token{TokenType: operationToken, Operation: op, CheckForPostTraverse: true}, nil
}
}

Expand Down
8 changes: 8 additions & 0 deletions pkg/yqlib/operator_parent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ var parentOperatorScenarios = []expressionScenario{
"D0, P[b], (!!map)::{fruit: banana, name: sam}\n",
},
},
{
description: "Get parent attribute",
document: `{a: {fruit: apple, name: bob}, b: {fruit: banana, name: sam}}`,
expression: `.. | select(. == "banana") | parent.name`,
expected: []string{
"D0, P[b name], (!!str)::sam\n",
},
},
{
description: "N-th parent",
subdescription: "You can optionally supply the number of levels to go up for the parent, the default being 1.",
Expand Down

0 comments on commit 1846006

Please sign in to comment.