[英]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.