繁体   English   中英

有没有办法用 ruamel.yaml 在 dump() 上应用转换?

[英]Is there a way to apply transformations on dump() with ruamel.yaml?

语境

我正在使用ruamel.yaml (0.17.21) 自动将嵌套对象注入/更新到现有 YAML 文档的集合中。

所有这些文档的最大行长度为 120 个字符,由 linter 强制执行。 我希望能够通过在YAML实例上设置width属性来保留此格式化规则。 然而,在实践中,诸如 URL 之类的不可破解的单词最终会溢出 120 个字符的限制,同时被转储回 output stream。

例如,以下代码重新格式化输入,如下面的差异所示,尽管我没有对其进行任何修改:

from ruamel.yaml import YAML
import sys

yaml = YAML()
yaml.width = 120

input = yaml.load('''\
arn:
  description: ARN of the Log Group to source data from. The expected format is documented at
     https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatchlogs.html#amazoncloudwatchlogs-resources-for-iam-policies
''')

yaml.dump(input, sys.stdout)
 arn:
-  description: ARN of the Log Group to source data from. The expected format is documented at
-    https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatchlogs.html#amazoncloudwatchlogs-resources-for-iam-policies
+  description: ARN of the Log Group to source data from. The expected format is documented at https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatchlogs.html#amazoncloudwatchlogs-resources-for-iam-policies

问题

有没有一种方法可以在不实现我自己的Emitter的情况下影响dump()的结果,例如手动验证生成的行不会溢出所需的最大行长度,如果是这种情况,我自己将其包装?

普通标量的发射器发生了一些奇怪的事情,那是旧的(继承的)代码,所以可能需要一些时间来修复(不破坏其他东西。

我认为您可以使用传递给转换参数的以下WrapToLong class 以编程方式更正这些问题。 我在这里使用 class,因此您不需要使用一些全局变量来获取执行实际工作的例程的宽度:

from ruamel.yaml import YAML
import sys

yaml = YAML()
yaml.width = 120

input = yaml.load('''\
arn:
  description: ARN of the Log Group to source data from. The expected format is documented at
     https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatchlogs.html#amazoncloudwatchlogs-resources-for-iam-policies
''')

class WrapToLong:
    def __init__(self, width, indent=2):
        self._width = width
        self._indent = indent

    def __call__(self, s):
        res = []
        for line in s.splitlines():
            if len(line) > self._width and ' ' in line:
                idx = 0
                while line[idx] == ' ':
                    idx += 1
                line, rest = line.rsplit(' ', 1)
                res.append(line)
                res.append(' ' * (idx + self._indent) + rest)
                continue
            res.append(line)
        return '\n'.join(res) + '\n'

yaml.dump(input, sys.stdout, transform=WrapToLong(yaml.width))

这使:

arn:
  description: ARN of the Log Group to source data from. The expected format is documented at
    https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatchlogs.html#amazoncloudwatchlogs-resources-for-iam-policies

您可以使用折叠标量(使用>- ),它们将换行符保留在ruamel.yaml中的位置,但是您需要更新所有 YAML 文件(以编程方式),并且如果 URL 之前的文本,则无法轻松更新加载的字符串变化,因为这可以改变折叠字符串的位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM