diff --git a/pkg/yqlib/doc/operators/comment-operators.md b/pkg/yqlib/doc/operators/comment-operators.md index 51dc17b3..e0bb5557 100644 --- a/pkg/yqlib/doc/operators/comment-operators.md +++ b/pkg/yqlib/doc/operators/comment-operators.md @@ -108,6 +108,23 @@ will output fc: "" ``` +## Retreive comment - map key example +From the previous example, we know that the comment is on the 'hello' _key_ as a lineComment + +Given a sample.yml file of: +```yaml +hello: # hello-world-comment + message: world +``` +then +```bash +yq '.hello | key | line_comment' sample.yml +``` +will output +```yaml +hello-world-comment +``` + ## Where is the comment - array example The underlying yaml parser can assign comments in a document to surprising nodes. Use an expression like this to find where you comment is. 'p' indicates the path, 'isKey' is if the node is a map key (as opposed to a map value). From this, you can see the 'under-name-comment' is actually on the first child @@ -146,6 +163,24 @@ will output fc: "" ``` +## Retreive comment - array example +From the previous example, we know that the comment is on the first child as a headComment + +Given a sample.yml file of: +```yaml +name: + # under-name-comment + - first-array-child +``` +then +```bash +yq '.name[0] | headComment' sample.yml +``` +will output +```yaml +under-name-comment +``` + ## Set head comment Given a sample.yml file of: ```yaml diff --git a/pkg/yqlib/operator_comments_test.go b/pkg/yqlib/operator_comments_test.go index 6b8dcb61..0f4c44ae 100644 --- a/pkg/yqlib/operator_comments_test.go +++ b/pkg/yqlib/operator_comments_test.go @@ -114,6 +114,15 @@ var commentOperatorScenarios = []expressionScenario{ expectedWhereIsMyCommentMapKey, }, }, + { + description: "Retreive comment - map key example", + subdescription: "From the previous example, we know that the comment is on the 'hello' _key_ as a lineComment", + document: "hello: # hello-world-comment\n message: world", + expression: `.hello | key | line_comment`, + expected: []string{ + "D0, P[hello], (!!str)::hello-world-comment\n", + }, + }, { description: "Where is the comment - array example", subdescription: "The underlying yaml parser can assign comments in a document to surprising nodes. Use an expression like this to find where you comment is. 'p' indicates the path, 'isKey' is if the node is a map key (as opposed to a map value).\nFrom this, you can see the 'under-name-comment' is actually on the first child", @@ -123,6 +132,15 @@ var commentOperatorScenarios = []expressionScenario{ expectedWhereIsMyCommentArray, }, }, + { + description: "Retreive comment - array example", + subdescription: "From the previous example, we know that the comment is on the first child as a headComment", + document: "name:\n # under-name-comment\n - first-array-child", + expression: `.name[0] | headComment`, + expected: []string{ + "D0, P[name 0], (!!str)::under-name-comment\n", + }, + }, { description: "Set head comment", document: `a: cat`,