git.delta.rocks / jrsonnet / refs/commits / 000d927bc641

difftreelog

test fix

Yaroslav Bolyukin2024-03-03parent: #0764805.patch.diff
in: master

6 files changed

modifiedcmds/jrsonnet-fmt/src/snapshots/jrsonnet_fmt__tests__complex_comments_snapshot.snapdiffbeforeafterboth
--- a/cmds/jrsonnet-fmt/src/snapshots/jrsonnet_fmt__tests__complex_comments_snapshot.snap
+++ b/cmds/jrsonnet-fmt/src/snapshots/jrsonnet_fmt__tests__complex_comments_snapshot.snap
@@ -3,51 +3,51 @@
 expression: "reformat(indoc!(\"{\n\t\t  comments: {\n\t\t\t_: '',\n\t\t\t//     Plain comment\n\t\t\ta: '',\n\n\t\t\t#    Plain comment with empty line before\n\t\t\tb: '',\n\t\t\t/*Single-line multiline comment\n\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/**Single-line multiline doc comment\n\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/**Multiline doc\n\t\t\tComment\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/*\n\n\tMulti-line\n\n\tcomment\n\t\t\t*/\n\t\t\td: '',\n\n\t\t\te: '', // Inline comment\n\n\t\t\tk: '',\n\n\t\t\t// Text after everything\n\t\t  },\n\t\t  comments2: {\n\t\t\tk: '',\n\t\t\t// Text after everything, but no newline above\n\t\t  },\n          spacing: {\n            a: '',\n\n            b: '',\n          },\n          noSpacing: {\n            a: '',\n            b: '',\n          },\n        }\"))"
 ---
 {
-  comments: {
-    _: '',
-    // Plain comment
-    a: '',
+	comments: {
+		_: '',
+		// Plain comment
+		a: '',
 
-    # Plain comment with empty line before
-    b: '',
-    /* Single-line multiline comment */
-    c: '',
+		# Plain comment with empty line before
+		b: '',
+		/* Single-line multiline comment */
+		c: '',
 
-    /**
-     * Single-line multiline doc comment
-     */
-    c: '',
+		/**
+		 * Single-line multiline doc comment
+		 */
+		c: '',
 
-    /**
-     * Multiline doc
-     * Comment
-     */
-    c: '',
+		/**
+		 * Multiline doc
+		 * Comment
+		 */
+		c: '',
 
-    /*
-    Multi-line
+		/*
+		Multi-line
 
-    comment
-    */
-    d: '',
+		comment
+		*/
+		d: '',
 
-    e: '', // Inline comment
+		e: '', // Inline comment
 
-    k: '',
+		k: '',
 
-    // Text after everything
-  },
-  comments2: {
-    k: '',
-    // Text after everything, but no newline above
-  },
-  spacing: {
-    a: '',
+		// Text after everything
+	},
+	comments2: {
+		k: '',
+		// Text after everything, but no newline above
+	},
+	spacing: {
+		a: '',
 
-    b: '',
-  },
-  noSpacing: {
-    a: '',
-    b: '',
-  },
+		b: '',
+	},
+	noSpacing: {
+		a: '',
+		b: '',
+	},
 }
modifiedcmds/jrsonnet-fmt/src/tests.rsdiffbeforeafterboth
--- a/cmds/jrsonnet-fmt/src/tests.rs
+++ b/cmds/jrsonnet-fmt/src/tests.rs
@@ -1,4 +1,4 @@
-use dprint_core::formatting::PrintOptions;
+use dprint_core::formatting::{PrintOptions, PrintItems};
 use indoc::indoc;
 
 use crate::Printable;
@@ -7,11 +7,15 @@
 	let (source, _) = jrsonnet_rowan_parser::parse(input);
 
 	dprint_core::formatting::format(
-		|| source.print(),
+		|| {
+			let mut out = PrintItems::new();
+			source.print(&mut out);
+			out
+		},
 		PrintOptions {
 			indent_width: 2,
 			max_width: 100,
-			use_tabs: false,
+			use_tabs: true,
 			new_line_text: "\n",
 		},
 	)
modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
before · cmds/jrsonnet/src/main.rs
1use std::{2	fs::{create_dir_all, File},3	io::{Read, Write},4};56use clap::{CommandFactory, Parser};7use clap_complete::Shell;8use jrsonnet_cli::{GcOpts, ManifestOpts, MiscOpts, OutputOpts, StdOpts, TlaOpts, TraceOpts};9use jrsonnet_evaluator::{10	apply_tla, bail,11	error::{Error as JrError, ErrorKind},12	ResultExt, State, Val,13};1415#[cfg(feature = "mimalloc")]16#[global_allocator]17static GLOBAL: mimallocator::Mimalloc = mimallocator::Mimalloc;1819#[derive(Parser)]20enum SubOpts {21	/// Generate completions for specified shell22	Generate {23		/// Target shell name24		shell: Shell,25	},26}2728#[derive(Parser)]29#[clap(next_help_heading = "DEBUG")]30struct DebugOpts {31	/// Required OS stack size.32	/// This shouldn't be changed unless jrsonnet is failing with stack overflow error.33	#[clap(long, name = "size")]34	pub os_stack: Option<usize>,35}3637#[derive(Parser)]38#[clap(next_help_heading = "INPUT")]39struct InputOpts {40	/// Treat input as code, evaluate it instead of reading file.41	#[clap(long, short = 'e')]42	pub exec: bool,4344	/// Path to the file to be compiled if `--exec` is unset, otherwise code itself.45	pub input: Option<String>,4647	/// After executing input, apply specified code.48	/// Output of the initial input will be accessible using `_`.49	#[cfg(feature = "exp-apply")]50	#[clap(long)]51	pub exp_apply: Vec<String>,52}5354/// Jsonnet commandline interpreter (Rust implementation)55#[derive(Parser)]56#[clap(57	args_conflicts_with_subcommands = true,58	disable_version_flag = true,59	version,60	author61)]62struct Opts {63	#[clap(subcommand)]64	sub: Option<SubOpts>,65	/// Print version66	#[clap(long)]67	version: bool,6869	#[clap(flatten)]70	input: InputOpts,71	#[clap(flatten)]72	misc: MiscOpts,73	#[clap(flatten)]74	tla: TlaOpts,75	#[clap(flatten)]76	std: StdOpts,77	#[clap(flatten)]78	gc: GcOpts,7980	#[clap(flatten)]81	trace: TraceOpts,82	#[clap(flatten)]83	manifest: ManifestOpts,84	#[clap(flatten)]85	output: OutputOpts,86	#[clap(flatten)]87	debug: DebugOpts,88}8990fn main() {91	let opts: Opts = Opts::parse();9293	if opts.version {94		print!("{}", Opts::command().render_version());95		std::process::exit(0)96	}9798	if let Some(sub) = opts.sub {99		match sub {100			SubOpts::Generate { shell } => {101				use clap_complete::generate;102				let app = &mut Opts::command();103				let buf = &mut std::io::stdout();104				generate(shell, app, "jrsonnet", buf);105				std::process::exit(0)106			}107		}108	}109110	let success = if let Some(size) = opts.debug.os_stack {111		std::thread::Builder::new()112			.stack_size(size * 1024 * 1024)113			.spawn(|| main_catch(opts))114			.expect("new thread spawned")115			.join()116			.expect("thread finished successfully")117	} else {118		main_catch(opts)119	};120	if !success {121		std::process::exit(1);122	}123}124125#[derive(thiserror::Error, Debug)]126enum Error {127	// Handled differently128	#[error("evaluation error")]129	Evaluation(JrError),130	#[error("io error")]131	Io(#[from] std::io::Error),132	#[error("input is not utf8 encoded")]133	Utf8(#[from] std::str::Utf8Error),134	#[error("missing input argument")]135	MissingInputArgument,136}137impl From<JrError> for Error {138	fn from(e: JrError) -> Self {139		Self::Evaluation(e)140	}141}142impl From<ErrorKind> for Error {143	fn from(e: ErrorKind) -> Self {144		Self::from(JrError::from(e))145	}146}147148fn main_catch(opts: Opts) -> bool {149	let s = State::default();150	let trace = opts.trace.trace_format();151	if let Err(e) = main_real(&s, opts) {152		if let Error::Evaluation(e) = e {153			let mut out = String::new();154			trace.write_trace(&mut out, &e).expect("format error");155			eprintln!("{out}")156		} else {157			eprintln!("{e}");158		}159		return false;160	}161	true162}163164fn main_real(s: &State, opts: Opts) -> Result<(), Error> {165	let _gc_leak_guard = opts.gc.leak_on_exit();166	let _gc_print_stats = opts.gc.stats_printer();167	let _stack_depth_override = opts.misc.stack_size_override();168169	let import_resolver = opts.misc.import_resolver();170	s.set_import_resolver(import_resolver);171172	let std = opts.std.context_initializer(s)?;173	if let Some(std) = std {174		s.set_context_initializer(std);175	}176177	let input = opts.input.input.ok_or(Error::MissingInputArgument)?;178	let val = if opts.input.exec {179		s.evaluate_snippet("<cmdline>".to_owned(), &input as &str)?180	} else if input == "-" {181		let mut input = Vec::new();182		std::io::stdin().read_to_end(&mut input)?;183		let input_str = std::str::from_utf8(&input)?;184		s.evaluate_snippet("<stdin>".to_owned(), input_str)?185	} else {186		s.import(&input)?187	};188189	let tla = opts.tla.tla_opts()?;190	#[allow(unused_mut)]191	let mut val = apply_tla(s.clone(), &tla, val)?;192193	#[cfg(feature = "exp-apply")]194	for apply in opts.input.exp_apply {195		use jrsonnet_evaluator::{InitialUnderscore, Thunk};196		val = s.evaluate_snippet_with(197			"<exp_apply>".to_owned(),198			&apply,199			InitialUnderscore(Thunk::evaluated(val)),200		)?;201	}202203	let manifest_format = opts.manifest.manifest_format();204	if let Some(multi) = opts.output.multi {205		if opts.output.create_output_dirs {206			let mut dir = multi.clone();207			dir.pop();208			create_dir_all(dir)?;209		}210		let Val::Obj(obj) = val else {211			bail!(212				"value should be object for --multi manifest, got {}",213				val.value_type()214			)215		};216		for (field, data) in obj.iter(217			#[cfg(feature = "exp-preserve-order")]218			opts.manifest.preserve_order,219		) {220			let data = data.with_description(|| format!("getting field {field} for manifest"))?;221222			let mut path = multi.clone();223			path.push(&field as &str);224			if opts.output.create_output_dirs {225				let mut dir = path.clone();226				dir.pop();227				create_dir_all(dir)?;228			}229			println!("{}", path.to_str().expect("path"));230			let mut file = File::create(path)?;231			write!(232				file,233				"{}",234				data.manifest(&manifest_format)235					.with_description(|| format!("manifesting {field}"))?,236			)?;237			if manifest_format.file_trailing_newline() {238				writeln!(file)?;239			}240			file.flush()?;241		}242	} else if let Some(path) = opts.output.output_file {243		if opts.output.create_output_dirs {244			let mut dir = path.clone();245			dir.pop();246			create_dir_all(dir)?;247		}248		let mut file = File::create(path)?;249		writeln!(file, "{}", val.manifest(manifest_format)?)?;250	} else {251		let output = val.manifest(manifest_format)?;252		if !output.is_empty() {253			println!("{output}");254		}255	}256257	Ok(())258}
after · cmds/jrsonnet/src/main.rs
1use std::{2	fs::{create_dir_all, File},3	io::{Read, Write},4};56use clap::{CommandFactory, Parser};7use clap_complete::Shell;8use jrsonnet_cli::{GcOpts, ManifestOpts, MiscOpts, OutputOpts, StdOpts, TlaOpts, TraceOpts};9use jrsonnet_evaluator::{10	apply_tla, bail,11	error::{Error as JrError, ErrorKind},12	ResultExt, State, Val,13};1415#[cfg(feature = "mimalloc")]16#[global_allocator]17static GLOBAL: mimallocator::Mimalloc = mimallocator::Mimalloc;1819#[derive(Parser)]20enum SubOpts {21	/// Generate completions for specified shell22	Generate {23		/// Target shell name24		shell: Shell,25	},26}2728#[derive(Parser)]29#[clap(next_help_heading = "DEBUG")]30struct DebugOpts {31	/// Required OS stack size.32	/// This shouldn't be changed unless jrsonnet is failing with stack overflow error.33	#[clap(long, name = "size")]34	pub os_stack: Option<usize>,35}3637#[derive(Parser)]38#[clap(next_help_heading = "INPUT")]39struct InputOpts {40	/// Treat input as code, evaluate it instead of reading file.41	#[clap(long, short = 'e')]42	pub exec: bool,4344	/// Path to the file to be compiled if `--exec` is unset, otherwise code itself.45	pub input: Option<String>,4647	/// After executing input, apply specified code.48	/// Output of the initial input will be accessible using `_`.49	#[cfg(feature = "exp-apply")]50	#[clap(long)]51	pub exp_apply: Vec<String>,52}5354/// Jsonnet commandline interpreter (Rust implementation)55#[derive(Parser)]56#[clap(57	args_conflicts_with_subcommands = true,58	disable_version_flag = true,59	version,60	author61)]62struct Opts {63	#[clap(subcommand)]64	sub: Option<SubOpts>,65	/// Print version66	#[clap(long)]67	version: bool,6869	#[clap(flatten)]70	input: InputOpts,71	#[clap(flatten)]72	misc: MiscOpts,73	#[clap(flatten)]74	tla: TlaOpts,75	#[clap(flatten)]76	std: StdOpts,77	#[clap(flatten)]78	gc: GcOpts,7980	#[clap(flatten)]81	trace: TraceOpts,82	#[clap(flatten)]83	manifest: ManifestOpts,84	#[clap(flatten)]85	output: OutputOpts,86	#[clap(flatten)]87	debug: DebugOpts,88}8990// TODO: Add unix_sigpipe = "sig_dfl"91fn main() {92	let opts: Opts = Opts::parse();9394	if opts.version {95		print!("{}", Opts::command().render_version());96		std::process::exit(0)97	}9899	if let Some(sub) = opts.sub {100		match sub {101			SubOpts::Generate { shell } => {102				use clap_complete::generate;103				let app = &mut Opts::command();104				let buf = &mut std::io::stdout();105				generate(shell, app, "jrsonnet", buf);106				std::process::exit(0)107			}108		}109	}110111	let success = if let Some(size) = opts.debug.os_stack {112		std::thread::Builder::new()113			.stack_size(size * 1024 * 1024)114			.spawn(|| main_catch(opts))115			.expect("new thread spawned")116			.join()117			.expect("thread finished successfully")118	} else {119		main_catch(opts)120	};121	if !success {122		std::process::exit(1);123	}124}125126#[derive(thiserror::Error, Debug)]127enum Error {128	// Handled differently129	#[error("evaluation error")]130	Evaluation(JrError),131	#[error("io error")]132	Io(#[from] std::io::Error),133	#[error("input is not utf8 encoded")]134	Utf8(#[from] std::str::Utf8Error),135	#[error("missing input argument")]136	MissingInputArgument,137}138impl From<JrError> for Error {139	fn from(e: JrError) -> Self {140		Self::Evaluation(e)141	}142}143impl From<ErrorKind> for Error {144	fn from(e: ErrorKind) -> Self {145		Self::from(JrError::from(e))146	}147}148149fn main_catch(opts: Opts) -> bool {150	let s = State::default();151	let trace = opts.trace.trace_format();152	if let Err(e) = main_real(&s, opts) {153		if let Error::Evaluation(e) = e {154			let mut out = String::new();155			trace.write_trace(&mut out, &e).expect("format error");156			eprintln!("{out}")157		} else {158			eprintln!("{e}");159		}160		return false;161	}162	true163}164165fn main_real(s: &State, opts: Opts) -> Result<(), Error> {166	let _gc_leak_guard = opts.gc.leak_on_exit();167	let _gc_print_stats = opts.gc.stats_printer();168	let _stack_depth_override = opts.misc.stack_size_override();169170	let import_resolver = opts.misc.import_resolver();171	s.set_import_resolver(import_resolver);172173	let std = opts.std.context_initializer(s)?;174	if let Some(std) = std {175		s.set_context_initializer(std);176	}177178	let input = opts.input.input.ok_or(Error::MissingInputArgument)?;179	let val = if opts.input.exec {180		s.evaluate_snippet("<cmdline>".to_owned(), &input as &str)?181	} else if input == "-" {182		let mut input = Vec::new();183		std::io::stdin().read_to_end(&mut input)?;184		let input_str = std::str::from_utf8(&input)?;185		s.evaluate_snippet("<stdin>".to_owned(), input_str)?186	} else {187		s.import(&input)?188	};189190	let tla = opts.tla.tla_opts()?;191	#[allow(unused_mut)]192	let mut val = apply_tla(s.clone(), &tla, val)?;193194	#[cfg(feature = "exp-apply")]195	for apply in opts.input.exp_apply {196		use jrsonnet_evaluator::{InitialUnderscore, Thunk};197		val = s.evaluate_snippet_with(198			"<exp_apply>".to_owned(),199			&apply,200			InitialUnderscore(Thunk::evaluated(val)),201		)?;202	}203204	let manifest_format = opts.manifest.manifest_format();205	if let Some(multi) = opts.output.multi {206		if opts.output.create_output_dirs {207			let mut dir = multi.clone();208			dir.pop();209			create_dir_all(dir)?;210		}211		let Val::Obj(obj) = val else {212			bail!(213				"value should be object for --multi manifest, got {}",214				val.value_type()215			)216		};217		for (field, data) in obj.iter(218			#[cfg(feature = "exp-preserve-order")]219			opts.manifest.preserve_order,220		) {221			let data = data.with_description(|| format!("getting field {field} for manifest"))?;222223			let mut path = multi.clone();224			path.push(&field as &str);225			if opts.output.create_output_dirs {226				let mut dir = path.clone();227				dir.pop();228				create_dir_all(dir)?;229			}230			println!("{}", path.to_str().expect("path"));231			let mut file = File::create(path)?;232			write!(233				file,234				"{}",235				data.manifest(&manifest_format)236					.with_description(|| format!("manifesting {field}"))?,237			)?;238			if manifest_format.file_trailing_newline() {239				writeln!(file)?;240			}241			file.flush()?;242		}243	} else if let Some(path) = opts.output.output_file {244		if opts.output.create_output_dirs {245			let mut dir = path.clone();246			dir.pop();247			create_dir_all(dir)?;248		}249		let mut file = File::create(path)?;250		writeln!(file, "{}", val.manifest(manifest_format)?)?;251	} else {252		let output = val.manifest(manifest_format)?;253		if !output.is_empty() {254			println!("{output}");255		}256	}257258	Ok(())259}
modifiedcrates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -88,13 +88,13 @@
 	}
 
 	#[test]
-	#[should_panic]
+	#[should_panic = "TruncatedFormatCode"]
 	fn parse_key_missing_start() {
 		try_parse_mapping_key("").unwrap();
 	}
 
 	#[test]
-	#[should_panic]
+	#[should_panic = "TruncatedFormatCode"]
 	fn parse_key_missing_end() {
 		try_parse_mapping_key("(   ").unwrap();
 	}
modifiedcrates/jrsonnet-rowan-parser/src/tests.rsdiffbeforeafterboth
--- a/crates/jrsonnet-rowan-parser/src/tests.rs
+++ b/crates/jrsonnet-rowan-parser/src/tests.rs
@@ -248,6 +248,7 @@
 fn eval_simple() {
 	let src = "local a = 1, b = 2; a + local c = 1; c";
 	let (node, errors) = parse(src);
+	assert!(errors.is_empty());
 
 	dbg!(node);
 }
modifiedtests/tests/common.rsdiffbeforeafterboth
--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -64,12 +64,12 @@
 		FuncVal::StaticBuiltin(b) => b
 			.params()
 			.iter()
-			.map(|p| p.name().as_str().unwrap_or(&"<unnamed>").to_string())
+			.map(|p| p.name().as_str().unwrap_or("<unnamed>").to_string())
 			.collect(),
 		FuncVal::Builtin(b) => b
 			.params()
 			.iter()
-			.map(|p| p.name().as_str().unwrap_or(&"<unnamed>").to_string())
+			.map(|p| p.name().as_str().unwrap_or("<unnamed>").to_string())
 			.collect(),
 	}
 }