difftreelog
feat yaml stream output
in: master
5 files changed
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -54,7 +54,7 @@
#[no_mangle]
pub extern "C" fn jsonnet_string_output(vm: &EvaluationState, v: c_int) {
match v {
- 1 => vm.set_manifest_format(ManifestFormat::None),
+ 1 => vm.set_manifest_format(ManifestFormat::String),
0 => vm.set_manifest_format(ManifestFormat::Json(4)),
_ => panic!("incorrect output format"),
}
crates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -5,7 +5,7 @@
pub enum ManifestFormatName {
/// Expect string as output, and write them directly
- None,
+ String,
Json,
Yaml,
}
@@ -14,7 +14,7 @@
type Err = &'static str;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(match s {
- "none" => ManifestFormatName::None,
+ "string" => ManifestFormatName::String,
"json" => ManifestFormatName::Json,
"yaml" => ManifestFormatName::Yaml,
_ => return Err("no such format"),
@@ -27,14 +27,17 @@
// #[clap(group = clap::ArgGroup::new("output_format"), help_heading = "MANIFESTIFICATION OUTPUT")]
pub struct ManifestOpts {
/// Output format, wraps resulting value to corresponding std.manifest call.
- /// If none - then jsonnet file is expected to return plain string value, otherwise
+ /// If string - then jsonnet file is expected to return plain string value, otherwise
/// output will be serialized to specified format
- #[clap(long, short = 'f', default_value = "json", possible_values = &["none", "json", "yaml"]/*, group = "output_format"*/)]
+ #[clap(long, short = 'f', default_value = "json", possible_values = &["string", "json", "yaml"]/*, group = "output_format"*/)]
format: ManifestFormatName,
/// Expect string as output, and write them directly.
- /// Shortcut for --format=none, and can't be set with format together
+ /// Shortcut for --format=string, and can't be set with format together
#[clap(long, short = 'S'/*, group = "output_format"*/)]
string: bool,
+ /// Write output as YAML stream, can be used with --format json/yaml
+ #[clap(long, short = 'y')]
+ yaml_stream: bool,
/// Numbed of spaces to pad output manifest with.
/// 0 for hard tabs, -1 for single line output
#[clap(long, default_value = "3")]
@@ -43,10 +46,10 @@
impl ConfigureState for ManifestOpts {
fn configure(&self, state: &EvaluationState) -> Result<()> {
if self.string {
- state.set_manifest_format(ManifestFormat::None);
+ state.set_manifest_format(ManifestFormat::String);
} else {
match self.format {
- ManifestFormatName::None => state.set_manifest_format(ManifestFormat::None),
+ ManifestFormatName::String => state.set_manifest_format(ManifestFormat::String),
ManifestFormatName::Json => {
state.set_manifest_format(ManifestFormat::Json(self.line_padding))
}
@@ -55,6 +58,11 @@
}
}
}
+ if self.yaml_stream {
+ state.set_manifest_format(ManifestFormat::YamlStream(Box::new(
+ state.manifest_format(),
+ )))
+ }
Ok(())
}
}
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth1use crate::{builtin::format::FormatError, Val, ValType};2use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};3use std::{path::PathBuf, rc::Rc};45#[derive(Debug, Clone)]6pub enum Error {7 IntristicNotFound(Rc<str>, Rc<str>),8 IntristicArgumentReorderingIsNotSupportedYet,910 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),11 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),1213 NoTopLevelObjectFound,14 CantUseSelfOutsideOfObject,15 CantUseSuperOutsideOfObject,1617 InComprehensionCanOnlyIterateOverArray,1819 ArrayBoundsError(usize, usize),2021 AssertionFailed(Val),2223 VariableIsNotDefined(String),24 TypeMismatch(&'static str, Vec<ValType>, ValType),25 NoSuchField(Rc<str>),2627 UnknownVariable(Rc<str>),2829 OnlyFunctionsCanBeCalledGot(ValType),30 UnknownFunctionParameter(String),31 BindingParameterASecondTime(Rc<str>),32 TooManyArgsFunctionHas(usize),33 FunctionParameterNotBoundInCall(Rc<str>),3435 UndefinedExternalVariable(Rc<str>),3637 FieldMustBeStringGot(ValType),3839 AttemptedIndexAnArrayWithString(Rc<str>),40 ValueIndexMustBeTypeGot(ValType, ValType, ValType),41 CantIndexInto(ValType),4243 StandaloneSuper,4445 ImportFileNotFound(PathBuf, PathBuf),46 ResolvedFileNotFound(PathBuf),47 ImportBadFileUtf8(PathBuf),48 ImportNotSupported(PathBuf, PathBuf),49 ImportSyntaxError {50 path: Rc<PathBuf>,51 source_code: Rc<str>,52 error: jrsonnet_parser::ParseError,53 },5455 RuntimeError(Rc<str>),56 StackOverflow,57 FractionalIndex,58 DivisionByZero,5960 StringManifestOutputIsNotAString,6162 ImportCallbackError(String),63 InvalidUnicodeCodepointGot(u32),6465 Format(FormatError),66}67impl From<Error> for LocError {68 fn from(e: Error) -> Self {69 Self(e, StackTrace(vec![]))70 }71}7273#[derive(Clone, Debug)]74pub struct StackTraceElement {75 pub location: ExprLocation,76 pub desc: String,77}78#[derive(Debug, Clone)]79pub struct StackTrace(pub Vec<StackTraceElement>);8081#[derive(Debug, Clone)]82pub struct LocError(pub Error, pub StackTrace);83impl LocError {84 pub fn new(e: Error) -> Self {85 Self(e, StackTrace(vec![]))86 }87}8889pub type Result<V> = std::result::Result<V, LocError>;9091#[macro_export]92macro_rules! throw {93 ($e: expr) => {94 return Err($e.into());95 };96}crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -53,13 +53,6 @@
}
}
-#[derive(Clone)]
-pub enum ManifestFormat {
- Yaml(usize),
- Json(usize),
- None,
-}
-
pub struct EvaluationSettings {
/// Limits recursion by limiting stack frames
pub max_stack: usize,
@@ -321,16 +314,7 @@
}
pub fn manifest(&self, val: Val) -> Result<Rc<str>> {
- self.run_in_state(|| {
- Ok(match self.manifest_format() {
- ManifestFormat::Yaml(padding) => val.into_yaml(padding)?,
- ManifestFormat::Json(padding) => val.into_json(padding)?,
- ManifestFormat::None => match val {
- Val::Str(s) => s,
- _ => throw!(StringManifestOutputIsNotAString),
- },
- })
- })
+ self.run_in_state(|| val.manifest(&self.manifest_format()))
}
/// If passed value is function - call with set TLA
@@ -521,7 +505,7 @@
evaluator
.evaluate_snippet_raw(Rc::new(PathBuf::from("raw.jsonnet")), $str.into())
.unwrap()
- .into_json(0)
+ .to_json(0)
.unwrap()
.replace("\n", "")
})
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -131,6 +131,14 @@
}
}
+#[derive(Clone)]
+pub enum ManifestFormat {
+ YamlStream(Box<ManifestFormat>),
+ Yaml(usize),
+ Json(usize),
+ String,
+}
+
#[derive(Debug, Clone)]
pub enum Val {
Bool(bool),
@@ -221,10 +229,46 @@
})
}
+
+ pub fn manifest(&self, ty: &ManifestFormat) -> Result<Rc<str>> {
+ Ok(match ty {
+ ManifestFormat::YamlStream(format) => {
+ let arr = match self {
+ Val::Arr(a) => a,
+ _ => throw!(StreamManifestOutputIsNotAArray),
+ };
+ let mut out = String::new();
+
+ match format as &ManifestFormat {
+ ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),
+ ManifestFormat::String => throw!(StreamManifestCannotNestString),
+ _ => {}
+ };
+
+ if !arr.is_empty() {
+ for v in arr.iter() {
+ out.push_str("---\n");
+ out.push_str(&v.manifest(format)?);
+ out.push_str("\n");
+ }
+ out.push_str("...");
+ }
+
+ out.into()
+ }
+ ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,
+ ManifestFormat::Json(padding) => self.to_json(*padding)?,
+ ManifestFormat::String => match self {
+ Val::Str(s) => s.clone(),
+ _ => throw!(StringManifestOutputIsNotAString),
+ },
+ })
+ }
+
/// For manifestification
- pub fn into_json(self, padding: usize) -> Result<Rc<str>> {
+ pub fn to_json(&self, padding: usize) -> Result<Rc<str>> {
manifest_json_ex(
- &self,
+ self,
&ManifestJsonOptions {
padding: &" ".repeat(padding),
mtype: if padding == 0 {
@@ -239,7 +283,7 @@
/// Calls std.manifestJson
#[cfg(feature = "faster")]
- pub fn into_std_json(self, padding: usize) -> Result<Rc<str>> {
+ pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {
manifest_json_ex(
&self,
&ManifestJsonOptions {
@@ -252,11 +296,11 @@
/// Calls std.manifestJson
#[cfg(not(feature = "faster"))]
- pub fn into_std_json(self, padding: usize) -> Result<Rc<str>> {
+ pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {
with_state(|s| {
let ctx = s
.create_default_context()?
- .with_var("__tmp__to_json__".into(), self)?;
+ .with_var("__tmp__to_json__".into(), self.clone())?;
Ok(evaluate(
ctx,
&el!(Expr::Apply(
@@ -274,11 +318,11 @@
.try_cast_str("to json")?)
})
}
- pub fn into_yaml(self, padding: usize) -> Result<Rc<str>> {
+ pub fn to_yaml(&self, padding: usize) -> Result<Rc<str>> {
with_state(|s| {
let ctx = s
.create_default_context()?
- .with_var("__tmp__to_json__".into(), self);
+ .with_var("__tmp__to_json__".into(), self.clone());
Ok(evaluate(
ctx,
&el!(Expr::Apply(