簡體   English   中英

使用 pyyaml 的 Load.gitlab-ci.yml 失敗,無法確定構造函數

[英]Load .gitlab-ci.yml with pyyaml fails with could not determine constructor

當我嘗試使用yaml.load加載.gitlab-ci.yml時失敗。

yaml.constructor.ConstructorError: could not determine a constructor for the tag '!reference'
  in "python.yml", line 9, column 7

那是我嘗試加載的 yaml。

.python:
  before_script:
    - pip install -r requirements.txt
  script:
    - echo "Hello Python!"

test:
  before_script:
    - !reference [.python, before_script]
  script:
    - pytest

現在我對那些參考資料不感興趣。 但是,我正在修改 yaml 的某些部分,然后將其寫回文件系統。 所以,我不想刪除這些引用。

  • 是否有任何 GitLab 庫可以加載gitlab-ci.yml 我找不到任何。
  • 有沒有辦法將.reference [,python, before_script]視為 String 並保持原樣?

升級到 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)

與此同時,我已經想出了如何添加一個構造函數和表示器來加載和轉儲帶有自定義標簽的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM