Add support for rendering Bytes values with YamlRenderer (#1276)

This commit is contained in:
Jen Basch
2025-10-30 15:53:43 -07:00
committed by GitHub
parent 10eccb100c
commit eab71229e7
11 changed files with 80 additions and 7 deletions

View File

@@ -153,8 +153,7 @@ final class YamlRenderer implements ValueRenderer {
@Override
public void visitBytes(byte[] value) {
throw new RendererException(
String.format("Values of type `Bytes` cannot be rendered as YAML. Value: %s", value));
emitter.emit(YamlUtils.bytesScalar(value));
}
@Override

View File

@@ -180,7 +180,8 @@ public final class YamlRendererNodes {
@Override
public void visitBytes(VmBytes value) {
cannotRenderTypeAddConverter(value);
if (!builder.isEmpty()) builder.append(' ');
emitter.emit(value.getBytes(), currIndent, false);
}
@Override

View File

@@ -15,6 +15,8 @@
*/
package org.pkl.core.util.yaml;
import java.util.Base64;
// Useful links:
// https://yaml-online-parser.appspot.com
// https://github.com/FasterXML/jackson-dataformats-text/pull/201
@@ -210,6 +212,11 @@ public abstract class YamlEmitter {
builder.append(value);
}
public final void emit(byte[] value, StringBuilder currIndent, boolean isKey) {
builder.append("!!binary ");
emit(Base64.getEncoder().encodeToString(value), currIndent, isKey);
}
public final void emitNull() {
builder.append("null");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2024-2025 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,6 +33,9 @@ public final class YamlUtils {
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private static final Optional<String> STRING_TAG = Optional.of(Tag.STR.toString());
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private static final Optional<String> BINARY_TAG = Optional.of(Tag.BINARY.toString());
private static final ImplicitTuple TUPLE = new ImplicitTuple(true, true);
private YamlUtils() {}
@@ -56,6 +59,13 @@ public final class YamlUtils {
return new ScalarEvent(Optional.empty(), STRING_TAG, tuple, value, scalarStyle);
}
/** Constructs a {@link ScalarEvent} for emitting the given value as YAML binary. */
public static ScalarEvent bytesScalar(byte[] value) {
var encoded = Base64.getEncoder().encodeToString(value);
return new ScalarEvent(
Optional.empty(), BINARY_TAG, new ImplicitTuple(false, false), encoded, ScalarStyle.PLAIN);
}
/** Constructs a {@link ScalarEvent} for emitting the given value in plain style. */
public static ScalarEvent plainScalar(String value, Tag tag) {
return new ScalarEvent(