Skip to content

Commit

Permalink
Fixing with_entries context #1925
Browse files Browse the repository at this point in the history
Can now update key/value w.r.t each other
  • Loading branch information
mikefarah committed Feb 10, 2024
1 parent 8cde0c8 commit e81b600
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
15 changes: 9 additions & 6 deletions pkg/yqlib/operator_entries.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,18 @@ func withEntriesOperator(d *dataTreeNavigator, context Context, expressionNode *
return Context{}, err
}

result, err := d.GetMatchingNodes(splatted, expressionNode.RHS)
log.Debug("expressionNode.Rhs %v", expressionNode.RHS.Operation.OperationType)
log.Debug("result %v", result)
if err != nil {
return Context{}, err
newResults := list.New()

for itemEl := splatted.MatchingNodes.Front(); itemEl != nil; itemEl = itemEl.Next() {
result, err := d.GetMatchingNodes(splatted.SingleChildContext(itemEl.Value.(*CandidateNode)), expressionNode.RHS)
if err != nil {
return Context{}, err
}
newResults.PushBackList(result.MatchingNodes)
}

selfExpression := &ExpressionNode{Operation: &Operation{OperationType: selfReferenceOpType}}
collected, err := collectTogether(d, result, selfExpression)
collected, err := collectTogether(d, splatted.ChildContext(newResults), selfExpression)
if err != nil {
return Context{}, err
}
Expand Down
12 changes: 11 additions & 1 deletion pkg/yqlib/operator_entries_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,21 @@ var entriesOperatorScenarios = []expressionScenario{
{
description: "Use with_entries to update keys",
document: `{a: 1, b: 2}`,
expression: `with_entries(.key |= "KEY_" + .)`,
// expression: `to_entries | with(.[]; .key |= "KEY_" + .) | from_entries`,
expression: `with_entries(.key |= "KEY_" + .)`,
expected: []string{
"D0, P[], (!!map)::KEY_a: 1\nKEY_b: 2\n",
},
},
{
skipDoc: true,
description: "Use with_entries to update keys comment",
document: `{a: 1, b: 2}`,
expression: `with_entries(.key headComment= .value)`,
expected: []string{
"D0, P[], (!!map)::# 1\na: 1\n# 2\nb: 2\n",
},
},
{
description: "Custom sort map keys",
subdescription: "Use to_entries to convert to an array of key/value pairs, sort the array using sort/sort_by/etc, and convert it back.",
Expand Down

0 comments on commit e81b600

Please sign in to comment.