在 中没有选项可以执行此操作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)
这将完全给出您期望的输出。
可以scalarstring.py
在ruamel.yaml
源代码中找到递归数据结构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
. 但是,如果您使用了双引号标量,那么该行将确保保留双引号。