difftreelog
Merge pull request #146 from CertainLach/fix/tests
in: master
Fix failing CI for tests and lints
22 files changed
cmds/jrsonnet-fmt/src/comments.rsdiffbeforeafterboth--- a/cmds/jrsonnet-fmt/src/comments.rs
+++ b/cmds/jrsonnet-fmt/src/comments.rs
@@ -72,7 +72,7 @@
if matches!(loc, CommentLocation::ItemInline) {
p!(pi: str(" "));
}
- p!(pi: str("/* ") string(lines[0].trim().to_string()) str(" */"))
+ p!(pi: str("/* ") string(lines[0].trim().to_string()) str(" */") nl)
} else if !lines.is_empty() {
fn common_ws_prefix<'a>(a: &'a str, b: &str) -> &'a str {
let offset = a
cmds/jrsonnet-fmt/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet-fmt/src/main.rs
+++ b/cmds/jrsonnet-fmt/src/main.rs
@@ -372,8 +372,8 @@
return p!(new: str("{ }"));
}
let mut pi = p!(new: str("{") >i nl);
- for mem in children.into_iter() {
- if mem.should_start_with_newline {
+ for (i, mem) in children.into_iter().enumerate() {
+ if mem.should_start_with_newline && i != 0 {
p!(pi: nl);
}
p!(pi: items(format_comments(&mem.before_trivia, CommentLocation::AboveItem)));
crates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -6,7 +6,7 @@
};
use jrsonnet_stdlib::{TomlFormat, YamlFormat};
-#[derive(Clone, ValueEnum)]
+#[derive(Clone, Copy, ValueEnum)]
pub enum ManifestFormatName {
/// Expect string as output, and write them directly
String,
@@ -18,9 +18,11 @@
#[derive(Parser)]
#[clap(next_help_heading = "MANIFESTIFICATION OUTPUT")]
pub struct ManifestOpts {
- /// Output format, wraps resulting value to corresponding std.manifest call.
- #[clap(long, short = 'f', default_value = "json")]
- format: ManifestFormatName,
+ /// Output format, wraps resulting value to corresponding std.manifest call
+ ///
+ /// [default: json, yaml when -y is used]
+ #[clap(long, short = 'f')]
+ format: Option<ManifestFormatName>,
/// Expect plain string as output.
/// Mutually exclusive with `--format`
#[clap(long, short = 'S', conflicts_with = "format")]
@@ -29,7 +31,9 @@
#[clap(long, short = 'y', conflicts_with = "string")]
yaml_stream: bool,
/// Number of spaces to pad output manifest with.
- /// `0` for hard tabs, `-1` for single line output [default: 3 for json, 2 for yaml/toml]
+ /// `0` for hard tabs, `-1` for single line output
+ ///
+ /// [default: 3 for json, 2 for yaml/toml]
#[clap(long)]
line_padding: Option<usize>,
/// Preserve order in object manifestification
@@ -44,7 +48,12 @@
} else {
#[cfg(feature = "exp-preserve-order")]
let preserve_order = self.preserve_order;
- match self.format {
+ let format = match self.format {
+ Some(v) => v,
+ None if self.yaml_stream => ManifestFormatName::Yaml,
+ None => ManifestFormatName::Json,
+ };
+ match format {
ManifestFormatName::String => Box::new(ToStringFormat),
ManifestFormatName::Json => Box::new(JsonFormat::cli(
self.line_padding.unwrap_or(3),
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -372,7 +372,7 @@
pub fn new_inclusive(start: i32, end: i32) -> Self {
Self { start, end }
}
- fn range(&self) -> impl Iterator<Item = i32> + ExactSizeIterator + DoubleEndedIterator {
+ fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {
WithExactSize(
self.start..=self.end,
(self.end as usize)
@@ -461,7 +461,7 @@
ArrayThunk::Waiting(..) => {}
};
- let ArrayThunk::Waiting(_) =
+ let ArrayThunk::Waiting(()) =
replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)
else {
unreachable!()
@@ -508,7 +508,7 @@
match &self.cached.borrow()[index] {
ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
- ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}
+ ArrayThunk::Waiting(()) | ArrayThunk::Pending => {}
};
Some(Thunk::new(ArrayElement {
@@ -597,9 +597,7 @@
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- let Some(key) = self.keys.get(index) else {
- return None;
- };
+ let key = self.keys.get(index)?;
Some(self.obj.get_lazy_or_bail(key.clone()))
}
@@ -649,9 +647,7 @@
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- let Some(key) = self.keys.get(index) else {
- return None;
- };
+ let key = self.keys.get(index)?;
// Nothing can fail in the key part, yet value is still
// lazy-evaluated
Some(Thunk::evaluated(
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -89,7 +89,7 @@
specs: &[CompSpec],
callback: &mut impl FnMut(Context) -> Result<()>,
) -> Result<()> {
- match specs.get(0) {
+ match specs.first() {
None => callback(ctx)?,
Some(CompSpec::IfSpec(IfSpecData(cond))) => {
if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {
crates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -6,8 +6,8 @@
use super::{arglike::ArgsLike, parse::parse_builtin_call, CallLocation};
use crate::{gc::TraceBox, tb, Context, Result, Val};
-/// Can't have str | IStr, because constant BuiltinParam causes
-/// E0492: constant functions cannot refer to interior mutable data
+/// Can't have `str` | `IStr`, because constant `BuiltinParam` causes
+/// `E0492: constant functions cannot refer to interior mutable data`
#[derive(Clone, Trace)]
pub struct ParamName(Option<Cow<'static, str>>);
impl ParamName {
@@ -27,10 +27,9 @@
}
impl PartialEq<IStr> for ParamName {
fn eq(&self, other: &IStr) -> bool {
- match &self.0 {
- Some(s) => s.as_bytes() == other.as_bytes(),
- None => false,
- }
+ self.0
+ .as_ref()
+ .map_or(false, |s| s.as_bytes() == other.as_bytes())
}
}
@@ -87,7 +86,7 @@
params: params
.into_iter()
.map(|n| BuiltinParam {
- name: ParamName::new_dynamic(n.to_string()),
+ name: ParamName::new_dynamic(n),
has_default: false,
})
.collect(),
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -159,11 +159,11 @@
Val::Null => serializer.serialize_none(),
Val::Str(s) => serializer.serialize_str(&s.clone().into_flat()),
Val::Num(n) => {
- if n.fract() != 0.0 {
- serializer.serialize_f64(*n)
- } else {
+ if n.fract() == 0.0 {
let n = *n as i64;
serializer.serialize_i64(n)
+ } else {
+ serializer.serialize_f64(*n)
}
}
#[cfg(feature = "exp-bigint")]
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -41,10 +41,12 @@
clippy::missing_const_for_fn,
// too many false-positives with .expect() calls
clippy::missing_panics_doc,
- // false positive for IStr type. There is an configuration option for
- // such cases, but it doesn't work:
- // https://github.com/rust-lang/rust-clippy/issues/9801
- clippy::mutable_key_type,
+ // false positive for IStr type. There is an configuration option for
+ // such cases, but it doesn't work:
+ // https://github.com/rust-lang/rust-clippy/issues/9801
+ clippy::mutable_key_type,
+ // false positives
+ clippy::redundant_pub_crate,
)]
// For jrsonnet-macros
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -175,6 +175,8 @@
manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;
Ok(out)
}
+
+#[allow(clippy::too_many_lines)]
fn manifest_json_ex_buf(
val: &Val,
buf: &mut String,
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -171,7 +171,7 @@
// .field("assertions_ran", &self.assertions_ran)
.field("this_entries", &self.this_entries)
// .field("value_cache", &self.value_cache)
- .finish()
+ .finish_non_exhaustive()
}
}
@@ -347,7 +347,7 @@
out.with_super(self);
let mut member = out.field(key);
if value.flags.add() {
- member = member.add()
+ member = member.add();
}
if let Some(loc) = value.location {
member = member.with_location(loc);
@@ -395,7 +395,7 @@
pub fn get(&self, key: IStr) -> Result<Option<Val>> {
self.run_assertions()?;
- self.get_for(key, self.0.this().unwrap_or(self.clone()))
+ self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))
}
pub fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
@@ -474,7 +474,7 @@
type Output = Val;
fn get(self: Box<Self>) -> Result<Self::Output> {
- Ok(self.obj.get_or_bail(self.key)?)
+ self.obj.get_or_bail(self.key)
}
}
@@ -495,7 +495,7 @@
SuperDepth::default(),
&mut |depth, index, name, visibility| {
let new_sort_key = FieldSortKey::new(depth, index);
- let entry = out.entry(name.clone());
+ let entry = out.entry(name);
let (visible, _) = entry.or_insert((true, new_sort_key));
match visibility {
Visibility::Normal => {}
@@ -634,7 +634,7 @@
SuperDepth::default(),
&mut |depth, index, name, visibility| {
let new_sort_key = FieldSortKey::new(depth, index);
- let entry = out.entry(name.clone());
+ let entry = out.entry(name);
let (visible, _) = entry.or_insert((true, new_sort_key));
match visibility {
Visibility::Normal => {}
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -248,7 +248,7 @@
let (cflags, str) = try_parse_cflags(str)?;
let (width, str) = try_parse_field_width(str)?;
let (precision, str) = try_parse_precision(str)?;
- let (_, str) = try_parse_length_modifier(str)?;
+ let ((), str) = try_parse_length_modifier(str)?;
let (convtype, str) = parse_conversion_type(str)?;
Ok((
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -449,25 +449,21 @@
}
fn from_untyped(value: Val) -> Result<Self> {
- match &value {
- Val::Arr(a) => {
- if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
- return Ok(bytes.0.as_slice().into());
- };
- <Self as Typed>::TYPE.check(&value)?;
- // Any::downcast_ref::<ByteArray>(&a);
- let mut out = Vec::with_capacity(a.len());
- for e in a.iter() {
- let r = e?;
- out.push(u8::from_untyped(r)?);
- }
- Ok(out.as_slice().into())
- }
- _ => {
- <Self as Typed>::TYPE.check(&value)?;
- unreachable!()
- }
+ let Val::Arr(a) = &value else {
+ <Self as Typed>::TYPE.check(&value)?;
+ unreachable!()
+ };
+ if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
+ return Ok(bytes.0.as_slice().into());
+ };
+ <Self as Typed>::TYPE.check(&value)?;
+ // Any::downcast_ref::<ByteArray>(&a);
+ let mut out = Vec::with_capacity(a.len());
+ for e in a.iter() {
+ let r = e?;
+ out.push(u8::from_untyped(r)?);
}
+ Ok(out.as_slice().into())
}
}
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -90,7 +90,7 @@
item: impl Fn() -> Result<()>,
) -> Result<()> {
State::push_description(error_reason, || match item() {
- Ok(_) => Ok(()),
+ Ok(()) => Ok(()),
Err(mut e) => {
if let ErrorKind::TypeError(e) = &mut e.error_mut() {
(e.1).0.push(path());
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -351,6 +351,8 @@
}
}
impl PartialEq for StrValue {
+ // False positive, into_flat returns not StrValue, but IStr, thus no infinite recursion here.
+ #[allow(clippy::unconditional_recursion)]
fn eq(&self, other: &Self) -> bool {
let a = self.clone().into_flat();
let b = other.clone().into_flat();
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -6,7 +6,7 @@
#![warn(clippy::pedantic, clippy::nursery)]
#![allow(clippy::missing_const_for_fn)]
use std::{
- borrow::{Borrow, Cow},
+ borrow::Cow,
cell::RefCell,
fmt::{self, Display},
hash::{BuildHasherDefault, Hash, Hasher},
@@ -14,7 +14,7 @@
str,
};
-use hashbrown::HashMap;
+use hashbrown::{hash_map::RawEntryMut, HashMap};
use jrsonnet_gcmodule::Trace;
use rustc_hash::FxHasher;
@@ -57,17 +57,6 @@
}
}
-impl Borrow<str> for IStr {
- fn borrow(&self) -> &str {
- self.as_str()
- }
-}
-impl Borrow<[u8]> for IStr {
- fn borrow(&self) -> &[u8] {
- self.as_bytes()
- }
-}
-
impl PartialEq for IStr {
fn eq(&self, other: &Self) -> bool {
// all IStr should be inlined into same pool
@@ -142,12 +131,6 @@
type Target = [u8];
fn deref(&self) -> &Self::Target {
- self.0.as_slice()
- }
-}
-
-impl Borrow<[u8]> for IBytes {
- fn borrow(&self) -> &[u8] {
self.0.as_slice()
}
}
@@ -285,9 +268,9 @@
let mut pool = pool.borrow_mut();
let entry = pool.raw_entry_mut().from_key(bytes);
match entry {
- hashbrown::hash_map::RawEntryMut::Occupied(i) => IBytes(i.get_key_value().0.clone()),
- hashbrown::hash_map::RawEntryMut::Vacant(e) => {
- let (k, _) = e.insert(Inner::new_bytes(bytes), ());
+ RawEntryMut::Occupied(i) => IBytes(i.get_key_value().0.clone()),
+ RawEntryMut::Vacant(e) => {
+ let (k, ()) = e.insert(Inner::new_bytes(bytes), ());
IBytes(k.clone())
}
}
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -374,6 +374,7 @@
fn params(&self) -> &[BuiltinParam] {
PARAMS
}
+ #[allow(unused_variable)]
fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
let parsed = parse_builtin_call(ctx.clone(), &PARAMS, args, false)?;
crates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -39,5 +39,5 @@
let bytes = STANDARD
.decode(str.as_bytes())
.map_err(|e| runtime_error!("invalid base64: {e}"))?;
- Ok(String::from_utf8(bytes).map_err(|_| runtime_error!("bad utf8"))?)
+ String::from_utf8(bytes).map_err(|_| runtime_error!("bad utf8"))
}
crates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth1use std::{borrow::Cow, fmt::Write};23use jrsonnet_evaluator::{4 bail,5 manifest::{escape_string_json_buf, ManifestFormat},6 Result, Val,7};89pub struct YamlFormat<'s> {10 /// Padding before fields, i.e11 /// ```yaml12 /// a:13 /// b:14 /// ## <- this15 /// ```16 padding: Cow<'s, str>,17 /// Padding before array elements in objects18 /// ```yaml19 /// a:20 /// - 121 /// ## <- this22 /// ```23 arr_element_padding: Cow<'s, str>,24 /// Should yaml keys appear unescaped, when possible25 /// ```yaml26 /// "safe_key": 127 /// # vs28 /// safe_key: 129 /// ```30 quote_keys: bool,31 /// If true - then order of fields is preserved as written,32 /// instead of sorting alphabetically33 #[cfg(feature = "exp-preserve-order")]34 preserve_order: bool,35}36impl YamlFormat<'_> {37 pub fn cli(38 padding: usize,39 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,40 ) -> Self {41 let padding = " ".repeat(padding);42 Self {43 padding: Cow::Owned(padding.clone()),44 arr_element_padding: Cow::Owned(padding),45 quote_keys: false,46 #[cfg(feature = "exp-preserve-order")]47 preserve_order,48 }49 }50 pub fn std_to_yaml(51 indent_array_in_object: bool,52 quote_keys: bool,53 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,54 ) -> Self {55 Self {56 padding: Cow::Borrowed(" "),57 arr_element_padding: Cow::Borrowed(if indent_array_in_object { " " } else { "" }),58 quote_keys,59 #[cfg(feature = "exp-preserve-order")]60 preserve_order,61 }62 }63}64impl ManifestFormat for YamlFormat<'_> {65 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {66 manifest_yaml_ex_buf(&val, buf, &mut String::new(), self)67 }68}6970/// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>71/// With added date check72fn yaml_needs_quotes(string: &str) -> bool {73 fn need_quotes_spaces(string: &str) -> bool {74 string.starts_with(' ') || string.ends_with(' ')75 }7677 string.is_empty()78 || need_quotes_spaces(string)79 || string.starts_with(|c| matches!(c, '&' | '*' | '?' | '|' | '-' | '<' | '>' | '=' | '!' | '%' | '@'))80 || string.contains(|c| matches!(c, ':' | '{' | '}' | '[' | ']' | ',' | '#' | '`' | '\"' | '\'' | '\\' | '\0'..='\x06' | '\t' | '\n' | '\r' | '\x0e'..='\x1a' | '\x1c'..='\x1f'))81 || [82 // http://yaml.org/type/bool.html83 "yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",84 "on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html85 "null", "Null", "NULL", "~",86 // > Quoted in std.jsonnet, however, in serde_yaml they were quoted:87 // > Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse88 // > them as string, not booleans, although it is violating the YAML 1.1 specification.89 // > See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.90 "y", "Y", "n", "N",91 "-.inf", "+.inf", ".inf",92 "-", "---", ""93 ].contains(&string)94 || (string.chars().all(|c| matches!(c, '0'..='9' | '-'))95 && string.chars().filter(|c| *c == '-').count() == 2)96 || string.starts_with('.')97 || string.starts_with("0x")98 || string.parse::<i64>().is_ok()99 || string.parse::<f64>().is_ok()100}101102#[allow(dead_code)]103fn manifest_yaml_ex(val: &Val, options: &YamlFormat<'_>) -> Result<String> {104 let mut out = String::new();105 manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;106 Ok(out)107}108109#[allow(clippy::too_many_lines)]110fn manifest_yaml_ex_buf(111 val: &Val,112 buf: &mut String,113 cur_padding: &mut String,114 options: &YamlFormat<'_>,115) -> Result<()> {116 match val {117 Val::Bool(v) => {118 if *v {119 buf.push_str("true");120 } else {121 buf.push_str("false");122 }123 }124 Val::Null => buf.push_str("null"),125 Val::Str(s) => {126 let s = s.clone().into_flat();127 if s.is_empty() {128 buf.push_str("\"\"");129 } else if let Some(s) = s.strip_suffix('\n') {130 buf.push('|');131 for line in s.split('\n') {132 buf.push('\n');133 buf.push_str(cur_padding);134 buf.push_str(&options.padding);135 buf.push_str(line);136 }137 } else if !options.quote_keys && !yaml_needs_quotes(&s) {138 buf.push_str(&s);139 } else {140 escape_string_json_buf(&s, buf);141 }142 }143 Val::Num(n) => write!(buf, "{}", *n).unwrap(),144 #[cfg(feature = "exp-bigint")]145 Val::BigInt(n) => write!(buf, "{}", *n).unwrap(),146 Val::Arr(a) => {147 if a.is_empty() {148 buf.push_str("[]");149 } else {150 for (i, item) in a.iter().enumerate() {151 if i != 0 {152 buf.push('\n');153 buf.push_str(cur_padding);154 }155 let item = item?;156 buf.push('-');157 match &item {158 Val::Arr(a) if !a.is_empty() => {159 buf.push('\n');160 buf.push_str(cur_padding);161 buf.push_str(&options.padding);162 }163 _ => buf.push(' '),164 }165 let extra_padding = match &item {166 Val::Arr(a) => !a.is_empty(),167 Val::Obj(o) => !o.is_empty(),168 _ => false,169 };170 let prev_len = cur_padding.len();171 if extra_padding {172 cur_padding.push_str(&options.padding);173 }174 manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;175 cur_padding.truncate(prev_len);176 }177 }178 }179 Val::Obj(o) => {180 if o.is_empty() {181 buf.push_str("{}");182 } else {183 for (i, key) in o184 .fields(185 #[cfg(feature = "exp-preserve-order")]186 options.preserve_order,187 )188 .iter()189 .enumerate()190 {191 if i != 0 {192 buf.push('\n');193 buf.push_str(cur_padding);194 }195 if !options.quote_keys && !yaml_needs_quotes(key) {196 buf.push_str(key);197 } else {198 escape_string_json_buf(key, buf);199 }200 buf.push(':');201 let prev_len = cur_padding.len();202 let item = o.get(key.clone())?.expect("field exists");203 match &item {204 Val::Arr(a) if !a.is_empty() => {205 buf.push('\n');206 buf.push_str(cur_padding);207 buf.push_str(&options.arr_element_padding);208 cur_padding.push_str(&options.arr_element_padding);209 }210 Val::Obj(o) if !o.is_empty() => {211 buf.push('\n');212 buf.push_str(cur_padding);213 buf.push_str(&options.padding);214 cur_padding.push_str(&options.padding);215 }216 _ => buf.push(' '),217 }218 manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;219 cur_padding.truncate(prev_len);220 }221 }222 }223 Val::Func(_) => bail!("tried to manifest function"),224 }225 Ok(())226}1use std::{borrow::Cow, fmt::Write};23use jrsonnet_evaluator::{4 bail,5 manifest::{escape_string_json_buf, ManifestFormat},6 Result, Val,7};89pub struct YamlFormat<'s> {10 /// Padding before fields, i.e11 /// ```yaml12 /// a:13 /// b:14 /// ## <- this15 /// ```16 padding: Cow<'s, str>,17 /// Padding before array elements in objects18 /// ```yaml19 /// a:20 /// - 121 /// ## <- this22 /// ```23 arr_element_padding: Cow<'s, str>,24 /// Should yaml keys appear unescaped, when possible25 /// ```yaml26 /// "safe_key": 127 /// # vs28 /// safe_key: 129 /// ```30 quote_keys: bool,31 /// If true - then order of fields is preserved as written,32 /// instead of sorting alphabetically33 #[cfg(feature = "exp-preserve-order")]34 preserve_order: bool,35}36impl YamlFormat<'_> {37 pub fn cli(38 padding: usize,39 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,40 ) -> Self {41 let padding = " ".repeat(padding);42 Self {43 padding: Cow::Owned(padding.clone()),44 arr_element_padding: Cow::Owned(padding),45 quote_keys: false,46 #[cfg(feature = "exp-preserve-order")]47 preserve_order,48 }49 }50 pub fn std_to_yaml(51 indent_array_in_object: bool,52 quote_keys: bool,53 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,54 ) -> Self {55 Self {56 padding: Cow::Borrowed(" "),57 arr_element_padding: Cow::Borrowed(if indent_array_in_object { " " } else { "" }),58 quote_keys,59 #[cfg(feature = "exp-preserve-order")]60 preserve_order,61 }62 }63}64impl ManifestFormat for YamlFormat<'_> {65 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {66 manifest_yaml_ex_buf(&val, buf, &mut String::new(), self)67 }68}6970/// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>71/// With added date check72fn yaml_needs_quotes(string: &str) -> bool {73 fn need_quotes_spaces(string: &str) -> bool {74 string.starts_with(' ') || string.ends_with(' ')75 }7677 string.is_empty()78 || need_quotes_spaces(string)79 || string.starts_with(|c| matches!(c, '&' | '*' | '?' | '|' | '-' | '<' | '>' | '=' | '!' | '%' | '@'))80 || string.contains(|c| matches!(c, ':' | '{' | '}' | '[' | ']' | ',' | '#' | '`' | '\"' | '\'' | '\\' | '\0'..='\x06' | '\t' | '\n' | '\r' | '\x0e'..='\x1a' | '\x1c'..='\x1f'))81 || [82 // http://yaml.org/type/bool.html83 "yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",84 "on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html85 "null", "Null", "NULL", "~",86 // > Quoted in std.jsonnet, however, in serde_yaml they were quoted:87 // > Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse88 // > them as string, not booleans, although it is violating the YAML 1.1 specification.89 // > See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.90 "y", "Y", "n", "N",91 "-.inf", "+.inf", ".inf",92 "-", "---", ""93 ].contains(&string)94 || (string.chars().all(|c| matches!(c, '0'..='9' | '-'))95 && string.chars().filter(|c| *c == '-').count() == 2)96 || string.starts_with('.')97 || string.starts_with("0x")98 || string.parse::<i64>().is_ok()99 || string.parse::<f64>().is_ok()100}101102#[allow(dead_code)]103fn manifest_yaml_ex(val: &Val, options: &YamlFormat<'_>) -> Result<String> {104 let mut out = String::new();105 manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;106 Ok(out)107}108109#[allow(clippy::too_many_lines)]110fn manifest_yaml_ex_buf(111 val: &Val,112 buf: &mut String,113 cur_padding: &mut String,114 options: &YamlFormat<'_>,115) -> Result<()> {116 match val {117 Val::Bool(v) => {118 if *v {119 buf.push_str("true");120 } else {121 buf.push_str("false");122 }123 }124 Val::Null => buf.push_str("null"),125 Val::Str(s) => {126 let s = s.clone().into_flat();127 if s.is_empty() {128 buf.push_str("\"\"");129 } else if let Some(s) = s.strip_suffix('\n') {130 buf.push('|');131 for line in s.split('\n') {132 buf.push('\n');133 buf.push_str(cur_padding);134 buf.push_str(&options.padding);135 buf.push_str(line);136 }137 } else if s.contains('\n') {138 buf.push_str("|-");139 for line in s.split('\n') {140 buf.push('\n');141 buf.push_str(cur_padding);142 buf.push_str(&options.padding);143 buf.push_str(line);144 }145 } else if !options.quote_keys && !yaml_needs_quotes(&s) {146 buf.push_str(&s);147 } else {148 escape_string_json_buf(&s, buf);149 }150 }151 Val::Num(n) => write!(buf, "{}", *n).unwrap(),152 #[cfg(feature = "exp-bigint")]153 Val::BigInt(n) => write!(buf, "{}", *n).unwrap(),154 Val::Arr(a) => {155 if a.is_empty() {156 buf.push_str("[]");157 } else {158 for (i, item) in a.iter().enumerate() {159 if i != 0 {160 buf.push('\n');161 buf.push_str(cur_padding);162 }163 let item = item?;164 buf.push('-');165 match &item {166 Val::Arr(a) if !a.is_empty() => {167 buf.push('\n');168 buf.push_str(cur_padding);169 buf.push_str(&options.padding);170 }171 _ => buf.push(' '),172 }173 let extra_padding = match &item {174 Val::Arr(a) => !a.is_empty(),175 Val::Obj(o) => !o.is_empty(),176 _ => false,177 };178 let prev_len = cur_padding.len();179 if extra_padding {180 cur_padding.push_str(&options.padding);181 }182 manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;183 cur_padding.truncate(prev_len);184 }185 }186 }187 Val::Obj(o) => {188 if o.is_empty() {189 buf.push_str("{}");190 } else {191 for (i, key) in o192 .fields(193 #[cfg(feature = "exp-preserve-order")]194 options.preserve_order,195 )196 .iter()197 .enumerate()198 {199 if i != 0 {200 buf.push('\n');201 buf.push_str(cur_padding);202 }203 if !options.quote_keys && !yaml_needs_quotes(key) {204 buf.push_str(key);205 } else {206 escape_string_json_buf(key, buf);207 }208 buf.push(':');209 let prev_len = cur_padding.len();210 let item = o.get(key.clone())?.expect("field exists");211 match &item {212 Val::Arr(a) if !a.is_empty() => {213 buf.push('\n');214 buf.push_str(cur_padding);215 buf.push_str(&options.arr_element_padding);216 cur_padding.push_str(&options.arr_element_padding);217 }218 Val::Obj(o) if !o.is_empty() => {219 buf.push('\n');220 buf.push_str(cur_padding);221 buf.push_str(&options.padding);222 cur_padding.push_str(&options.padding);223 }224 _ => buf.push(' '),225 }226 manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;227 cur_padding.truncate(prev_len);228 }229 }230 }231 Val::Func(_) => bail!("tried to manifest function"),232 }233 Ok(())234}crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -47,7 +47,7 @@
.ext_natives
.get(&x)
.cloned()
- .map_or(Val::Null, |v| Val::Func(v))
+ .map_or(Val::Null, Val::Func)
}
#[builtin(fields(
flake.lockdiffbeforeafterboth--- a/flake.lock
+++ b/flake.lock
@@ -5,11 +5,11 @@
"systems": "systems"
},
"locked": {
- "lastModified": 1694529238,
- "narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
+ "lastModified": 1705309234,
+ "narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
"owner": "numtide",
"repo": "flake-utils",
- "rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
+ "rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
"type": "github"
},
"original": {
@@ -20,11 +20,11 @@
},
"nixpkgs": {
"locked": {
- "lastModified": 1701376520,
- "narHash": "sha256-U3iGiOZqgu7wvVzgfoQzGGFMqNsDj/q/6zPIjCy7ajg=",
+ "lastModified": 1705391267,
+ "narHash": "sha256-gGVm9QudiRtYTX8PN9cTTy7uuJcL4I2lRMoPx496kXk=",
"owner": "nixos",
"repo": "nixpkgs",
- "rev": "c74cc3c3db2ed5e68895953d75c397797d499133",
+ "rev": "41a9a7f170c740acb24f3390323877d11c69d5ee",
"type": "github"
},
"original": {
@@ -50,11 +50,11 @@
]
},
"locked": {
- "lastModified": 1701310566,
- "narHash": "sha256-CL9J3xUR2Ejni4LysrEGX0IdO+Y4BXCiH/By0lmF3eQ=",
+ "lastModified": 1705371439,
+ "narHash": "sha256-P1kulUXpYWkcrjiX3sV4j8ACJZh9XXSaaD+jDLBDLKo=",
"owner": "oxalica",
"repo": "rust-overlay",
- "rev": "6d3c6e185198b8bf7ad639f22404a75aa9a09bff",
+ "rev": "b21f3c0d5bf0f0179f5f0140e8e0cd099618bd04",
"type": "github"
},
"original": {
flake.nixdiffbeforeafterboth--- a/flake.nix
+++ b/flake.nix
@@ -25,14 +25,14 @@
lib = pkgs.lib;
rust =
(pkgs.rustChannelOf {
- date = "2023-10-28";
+ date = "2024-01-10";
channel = "nightly";
})
.default
.override {
extensions = ["rust-src" "miri" "rust-analyzer" "clippy"];
};
- in rec {
+ in {
packages = rec {
go-jsonnet = pkgs.callPackage ./nix/go-jsonnet.nix {};
sjsonnet = pkgs.callPackage ./nix/sjsonnet.nix {};
tests/suite/std_param_names.jsonnetdiffbeforeafterboth--- a/tests/suite/std_param_names.jsonnet
+++ b/tests/suite/std_param_names.jsonnet
@@ -103,6 +103,7 @@
asin: ['x'],
acos: ['x'],
atan: ['x'],
+ atan2: ['y', 'x'],
type: ['x'],
filter: ['func', 'arr'],
objectHasEx: ['obj', 'fname', 'hidden'],