Skip to content

fix(unique): ignore comments when comparing array elements#2766

Open
maximilize wants to merge 1 commit into
mikefarah:masterfrom
maximilize:fix/unique-ignore-comments-2491
Open

fix(unique): ignore comments when comparing array elements#2766
maximilize wants to merge 1 commit into
mikefarah:masterfrom
maximilize:fix/unique-ignore-comments-2491

Conversation

@maximilize

Copy link
Copy Markdown

Generated by an AI agent (Claude) acting on the user's behalf, not the user personally.

Problem

yq 'unique' keeps duplicate objects when a comment sits between two equal
items:

# data1.yml
- id: 1001
# Comment
- id: 1001

yq 'unique' data1.yml returns both items instead of one. Scalars dedupe
correctly; the problem only affects non-scalar elements, and only when a
comment lands between the equal items.

Root cause

getUniqueKeyValue (pkg/yqlib/operator_unique.go) builds the dedup key for
non-scalar elements by encoding them to YAML:

keyValue, err = encodeToString(keyCandidate, encoderPreferences{YamlFormat, 0})

The encoded form includes the node's head/line/foot comments. The # Comment
attaches to one of the two equal nodes, so their encodings differ and they are
treated as distinct. Scalars use .Value directly, which is why they were
unaffected.

Fix

Encode a comment-free deep copy of the node for the key, so uniqueness depends
on the data only.

Test

Added a scenario to operator_unique_test.go for the comment-between-equal-items
case. It fails before the change (both items kept) and passes after (deduped to
one). go test ./pkg/yqlib -run TestUniqueOperatorScenarios, gofmt, go vet,
golangci-lint and scripts/spelling.sh are clean for the change.

Fixes #2491

The unique operator computed the dedup key for non-scalar elements by
encoding them to YAML, which includes their head/line/foot comments. A
comment sitting between two otherwise equal objects attaches to one of
them, changing its encoding, so the duplicates were wrongly kept. Encode
a comment-free copy of the node for the key so uniqueness depends on the
data only.

Fixes mikefarah#2491
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Comments affecting Unique operator behaviour

1 participant