|
5 | 5 | import java.util.LinkedHashMap;
|
6 | 6 | import java.util.List;
|
7 | 7 | import java.util.Map;
|
| 8 | +import org.yaml.snakeyaml.DumperOptions; |
8 | 9 | import org.yaml.snakeyaml.Yaml;
|
9 | 10 |
|
10 | 11 | public final class yaml_encode implements Function {
|
11 | 12 |
|
12 | 13 | @Override
|
13 | 14 | public Value execute(Value... args) {
|
14 |
| - Arguments.check(1, args.length); |
| 15 | + Arguments.checkOrOr(1, 2, args.length); |
15 | 16 | try {
|
16 | 17 | final Object root = process(args[0]);
|
17 |
| - final String yamlRaw = new Yaml().dump(root); |
| 18 | + final DumperOptions options = new DumperOptions(); |
| 19 | + if (args.length == 2 && args[1].type() == Types.MAP) { |
| 20 | + configure(options, ((MapValue) args[1])); |
| 21 | + } |
| 22 | + final String yamlRaw = new Yaml(options).dump(root); |
18 | 23 | return new StringValue(yamlRaw);
|
19 | 24 | } catch (Exception ex) {
|
20 | 25 | throw new RuntimeException("Error while creating yaml", ex);
|
21 | 26 | }
|
22 | 27 | }
|
| 28 | + |
| 29 | + private void configure(DumperOptions options, MapValue map) { |
| 30 | + map.ifPresent("allowReadOnlyProperties", value -> |
| 31 | + options.setAllowReadOnlyProperties(value.asInt() != 0)); |
| 32 | + map.ifPresent("allowUnicode", value -> |
| 33 | + options.setAllowUnicode(value.asInt() != 0)); |
| 34 | + map.ifPresent("canonical", value -> |
| 35 | + options.setCanonical(value.asInt() != 0)); |
| 36 | + map.ifPresent("defaultFlowStyle", value -> |
| 37 | + options.setDefaultFlowStyle(DumperOptions.FlowStyle.valueOf(value.asString()))); |
| 38 | + map.ifPresent("defaultScalarStyle", value -> |
| 39 | + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.valueOf(value.asString()))); |
| 40 | + map.ifPresent("explicitEnd", value -> |
| 41 | + options.setExplicitEnd(value.asInt() != 0)); |
| 42 | + map.ifPresent("explicitStart", value -> |
| 43 | + options.setExplicitStart(value.asInt() != 0)); |
| 44 | + map.ifPresent("indent", value -> |
| 45 | + options.setIndent(value.asInt())); |
| 46 | + map.ifPresent("indicatorIndent", value -> |
| 47 | + options.setIndicatorIndent(value.asInt())); |
| 48 | + map.ifPresent("lineBreak", value -> |
| 49 | + options.setLineBreak(DumperOptions.LineBreak.valueOf(value.asString()))); |
| 50 | + map.ifPresent("prettyFlow", value -> |
| 51 | + options.setPrettyFlow(value.asInt() != 0)); |
| 52 | + map.ifPresent("splitLines", value -> |
| 53 | + options.setSplitLines(value.asInt() != 0)); |
| 54 | + map.ifPresent("width", value -> |
| 55 | + options.setWidth(value.asInt())); |
| 56 | + } |
23 | 57 |
|
24 | 58 | private Object process(Value val) {
|
25 | 59 | switch (val.type()) {
|
|
0 commit comments