Added comment operator examples

This commit is contained in:
Mike Farah 2022-09-30 11:26:36 +10:00
parent 2362451fda
commit 60f30f8a48
2 changed files with 53 additions and 0 deletions

View File

@ -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

View File

@ -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`,