In an attempt to make complex Azure DevOps pipelines self-documenting I am trying to read comments out of YAML files automatically. I have decided to use the ruamel.yaml python library.
Reading comments works well, but I have not found how to distinguish comments at the end of the line from full-line comments:
- book # This is an end-of-the-line comment
# This is a full line comment
Does anyone know how I could achieve this?
Code example, reading the stage-level comments of all stages, without comments of sub-entities of stages:
from ruamel.yaml import YAML
from ruamel.yaml.comments import CommentedMap, CommentedSeq
file_name = 'test.yaml'
yaml=YAML()
with open(file_name) as doc:
data = yaml.load(doc)
i = 0
for item in data['stages']:
i+=1
print("*** stage", i, item['stage'])
if isinstance(item, CommentedMap):
comment_token = item.ca.items.get('stage')
stage_help = {"stage_id": i}
current_key = "Comment"
if comment_token:
for tab in comment_token:
if tab:
vals = tab.value.split('\n')
for line in vals:
if line[1:1] == "#":
line = line[1:]
else:
line = line.strip()[1:].strip()
if len(line) == 0:
continue
if line[0:1] == "@":
current_key = line[1:line.index(':')]
content = line[line.index(':')+1:].strip()
else:
content = line
if current_key not in stage_help:
stage_help[current_key] = f"{content}"
else:
stage_help[current_key] = f"{stage_help[current_key]}\n{content}"
print(stage_help)
YAML:
stages:
- stage: TestA
# @Comment: I write what it does
# @Link: https://documentation
- stage: TestB # My favorite stage!
# @Comment: We can also write
# Multiline docs
# @Link: https://doc2
displayName: Test B # The displayName is shown in the pipeline's GUI
Running this gives me:
*** stage 1 TestA
{'stage_id': 1, 'Comment': 'I write what it does', 'Link': 'https://documentation'}
*** stage 2 TestB
{'stage_id': 2, 'Comment': 'My favorite stage!\nWe can also write\nMultiline docs', 'Link': 'https://doc2'}