[英]Load .gitlab-ci.yml with pyyaml fails with could not determine constructor
Loading .gitlab-ci.yml
fails when I try to load it with yaml.load
.当我尝试使用
yaml.load
加载.gitlab-ci.yml
时失败。
yaml.constructor.ConstructorError: could not determine a constructor for the tag '!reference'
in "python.yml", line 9, column 7
That's the yaml I try to load.那是我尝试加载的 yaml。
.python:
before_script:
- pip install -r requirements.txt
script:
- echo "Hello Python!"
test:
before_script:
- !reference [.python, before_script]
script:
- pytest
Right now I'm not interested in those references.现在我对那些参考资料不感兴趣。 However, I'm modifying some parts of the yaml and then write it back to the filesystem.
但是,我正在修改 yaml 的某些部分,然后将其写回文件系统。 So, I don't want to strip these references.
所以,我不想删除这些引用。
gitlab-ci.yml
?gitlab-ci.yml
? I could not find any..reference [,python, before_script]
as String and keep it as is?.reference [,python, before_script]
视为 String 并保持原样?Upgrade to ruamel.yaml>=0.15.x升级到 ruamel.yaml>=0.15.x
yaml_str = """
.python:
before_script:
- pip install -r requirements.txt
script:
- echo "Hello Python!"
test:
before_script:
- !reference [.python, before_script]
script:
- pytest """
from ruamel.yaml import YAML
yaml = YAML()
yaml.preserve_quotes = True
data = yaml.load(yaml_str)
In the meantime, I have figured out how to add a constructor and representer to load and dump YAML with custom tags.与此同时,我已经想出了如何添加一个构造函数和表示器来加载和转储带有自定义标签的 YAML。
import yaml
class Reference:
yaml_tag = u'!reference'
def __init__(self, values):
self._values = values
def reference_constructor(loader: yaml.SafeLoader, node: yaml.nodes.CollectionNode) -> Reference:
return Reference(loader.construct_sequence(node))
def reference_representer(dumper: yaml.SafeDumper, ref: Reference) -> yaml.nodes.SequenceNode:
return dumper.represent_sequence(Reference.yaml_tag, ref._values)
def loader():
loader = yaml.SafeLoader
loader.add_constructor(Reference.yaml_tag, reference_constructor)
return loader
def dumper():
dumper = yaml.SafeDumper
dumper.add_representer(Reference, reference_representer)
return dumper
def rewrite(ci_file):
with open(ci_file) as f:
ci_yaml = yaml.load(f, Loader=loader())
print(ci_yaml)
with open(ci_file, "w") as f:
yaml.dump(ci_yaml, f, Dumper=dumper())
if __name__ == "__main__":
rewrite(".gitlab-ci.yml")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.