在ruamel.yaml.cmd 中没有执行此操作的选项,但使用小型 python 程序并使用ruamel.yaml 执行此操作相当简单,方法是在往返模式下加载和转储(默认)。
您唯一需要做的就是确保数据结构上的流样式(即键 sasha_command_help 的值)设置为块样式(这就是我如何解释您对“美化 YAML”的定义"):
import sys
import ruamel.yaml
yaml_str = """\
sasha_commands:
# Sasha comment
sasha_command_help: {call: sublime.command_help, caption: 'Sasha Command: Command Help'}
"""
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
data = yaml.load(yaml_str)
data['sasha_commands']['sasha_command_help'].fa.set_block_style()
yaml.dump(data, sys.stdout)
这将完全给出您期望的输出。
可以在ruamel.yaml 源代码中的scalarstring.py 中找到递归数据结构walker,它适用于制作通用的“make-everything-block-style”例程:
import sys
import ruamel.yaml
def block_style(base):
"""
This routine walks over a simple, i.e. consisting of dicts, lists and
primitives, tree loaded from YAML. It recurses into dict values and list
items, and sets block-style on these.
"""
if isinstance(base, dict):
for k in base:
try:
base.fa.set_block_style()
except AttributeError:
pass
block_style(base[k])
elif isinstance(base, list):
for elem in base:
try:
base.fa.set_block_style()
except AttributeError:
pass
block_style(elem)
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
file_in = sys.argv[1]
file_out = sys.argv[2]
with open(file_in) as fp:
data = yaml.load(fp)
block_style(data)
with open(file_out, 'w') as fp:
yaml.dump(data, fp)
如果您将上述内容存储在prettifyyaml.py 中,您可以使用以下方式调用它:
python prettifyyaml.py SashaPrettifyYAML.yaml Prettified.yaml
由于您已经在嵌入空格的标量周围使用了单引号,因此如果您省略 yaml.preserve_quotes = True,您将不会看到任何变化。但是,如果您使用了双引号标量,那么该行将确保保留双引号。