| 1 |
Get line numbers of YAML elements: |
| 2 |
based on: strictyaml |
| 3 |
docs: howto/what-line |
| 4 |
description: | |
| 5 |
Line numbers, the text of an item and text of surrounding lines |
| 6 |
can be grabbed from returned YAML objects - using .start_line, |
| 7 |
.end_line, lines(), lines_before(x) and lines_after(x). |
| 8 |
given: |
| 9 |
yaml_snippet: | |
| 10 |
y: p |
| 11 |
# Some comment |
| 12 |
|
| 13 |
a: | |
| 14 |
x |
| 15 |
|
| 16 |
# Another comment |
| 17 |
b: y |
| 18 |
c: a |
| 19 |
|
| 20 |
d: b |
| 21 |
|
| 22 |
setup: | |
| 23 |
from strictyaml import Map, Str, YAMLValidationError, load |
| 24 |
from ensure import Ensure |
| 25 |
|
| 26 |
schema = Map({"y": Str(), "a": Str(), "b": Str(), "c": Str(), "d": Str()}) |
| 27 |
|
| 28 |
snippet = load(yaml_snippet, schema) |
| 29 |
|
| 30 |
variations: |
| 31 |
If there is preceding comment for an item the start line includes it: |
| 32 |
steps: |
| 33 |
- Run: |
| 34 |
code: | |
| 35 |
Ensure(snippet["a"].start_line).equals(3) |
| 36 |
Ensure(snippet["d"].start_line).equals(9) |
| 37 |
|
| 38 |
If there is a trailing comment the end line includes it: |
| 39 |
steps: |
| 40 |
- Run: |
| 41 |
code: | |
| 42 |
Ensure(snippet["a"].end_line).equals(6) |
| 43 |
Ensure(snippet["d"].end_line).equals(10) |
| 44 |
|
| 45 |
You can grab the start line of a key: |
| 46 |
steps: |
| 47 |
- Run: |
| 48 |
code: | |
| 49 |
Ensure(snippet.keys()[1].start_line).equals(3) |
| 50 |
|
| 51 |
Start line and end line of whole snippet: |
| 52 |
steps: |
| 53 |
- Run: |
| 54 |
code: | |
| 55 |
Ensure(snippet.start_line).equals(1) |
| 56 |
Ensure(snippet.end_line).equals(10) |
| 57 |
|
| 58 |
Grabbing a line before an item: |
| 59 |
steps: |
| 60 |
- Run: |
| 61 |
code: | |
| 62 |
Ensure(snippet['a'].lines_before(1)).equals("# Some comment") |
| 63 |
|
| 64 |
Grabbing a line after an item: |
| 65 |
steps: |
| 66 |
- Run: |
| 67 |
code: | |
| 68 |
Ensure(snippet['a'].lines_after(4)).equals("b: y\nc: a\n\nd: b") |
| 69 |
|
| 70 |
Grabbing the lines of an item including surrounding comments: |
| 71 |
steps: |
| 72 |
- Run: |
| 73 |
code: | |
| 74 |
print(load(yaml_snippet, schema)['a'].lines()) |
| 75 |
will output: |- |
| 76 |
a: | |
| 77 |
x |
| 78 |
|
| 79 |
# Another comment |
| 80 |
|
| 81 |
Start line of YAML with list: |
| 82 |
based on: strictyaml |
| 83 |
description: | |
| 84 |
Actually, this should probably be 6, not 4. This is likely a |
| 85 |
bug in ruamel.yaml however. |
| 86 |
|
| 87 |
TODO: Come back to this test. |
| 88 |
given: |
| 89 |
yaml_snippet: | |
| 90 |
a: |
| 91 |
b: |
| 92 |
- 1 |
| 93 |
# comment |
| 94 |
# second comment |
| 95 |
- 2 |
| 96 |
- 3 |
| 97 |
- 4 |
| 98 |
setup: | |
| 99 |
from strictyaml import load |
| 100 |
from ensure import Ensure |
| 101 |
steps: |
| 102 |
- Run: |
| 103 |
code: |- |
| 104 |
Ensure(load(yaml_snippet)['a']['b'][1].start_line).equals(4) |
| 105 |
Ensure(load(yaml_snippet)['a']['b'][1].end_line).equals(4) |