【发布时间】:2021-06-25 21:40:57
【问题描述】:
为了使复杂的 Azure DevOps 管道自记录,我尝试自动从 YAML 文件中读取 cmets。我决定使用ruamel.yaml python 库。
阅读cmets效果很好,但是我还没有找到如何区分行尾的cmets和全行的cmets:
- book # This is an end-of-the-line comment
# This is a full line comment
有谁知道我如何做到这一点?
代码示例,读取所有stage的stage级cmets,不包含stage的子实体的cmets:
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
运行它给了我:
*** 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'}
【问题讨论】:
标签: python-3.x azure-devops yaml ruamel.yaml