git.delta.rocks / jrsonnet / refs/commits / 4e0dbf427e61

difftreelog

style update rustfmt

Yaroslav Bolyukin2023-07-26parent: #f883d5e.patch.diff
in: master

9 files changed

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,11	error::{Error as JrError, ErrorKind},12	throw, 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 them instead of reading file41	#[clap(long, short = 'e')]42	pub exec: bool,4344	/// Path to the file to be compiled if `--evaluate` is unset, otherwise code itself45	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			throw!("value should be object for --multi manifest, got {}", val.value_type())212		};213		for (field, data) in obj.iter(214			#[cfg(feature = "exp-preserve-order")]215			opts.manifest.preserve_order,216		) {217			let data = data.with_description(|| format!("getting field {field} for manifest"))?;218219			let mut path = multi.clone();220			path.push(&field as &str);221			if opts.output.create_output_dirs {222				let mut dir = path.clone();223				dir.pop();224				create_dir_all(dir)?;225			}226			println!("{}", path.to_str().expect("path"));227			let mut file = File::create(path)?;228			write!(229				file,230				"{}",231				data.manifest(&manifest_format)232					.with_description(|| format!("manifesting {field}"))?,233			)?;234			if manifest_format.file_trailing_newline() {235				writeln!(file)?;236			}237			file.flush()?;238		}239	} else if let Some(path) = opts.output.output_file {240		if opts.output.create_output_dirs {241			let mut dir = path.clone();242			dir.pop();243			create_dir_all(dir)?;244		}245		let mut file = File::create(path)?;246		writeln!(file, "{}", val.manifest(manifest_format)?)?;247	} else {248		let output = val.manifest(manifest_format)?;249		if !output.is_empty() {250			println!("{output}");251		}252	}253254	Ok(())255}
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,11	error::{Error as JrError, ErrorKind},12	throw, 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 them instead of reading file41	#[clap(long, short = 'e')]42	pub exec: bool,4344	/// Path to the file to be compiled if `--evaluate` is unset, otherwise code itself45	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			throw!(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}
modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -178,7 +178,9 @@
 			ArrayThunk::Waiting(..) => {}
 		};
 
-		let ArrayThunk::Waiting(expr) = replace(&mut self.0.cached.borrow_mut()[index], ArrayThunk::Pending) else {
+		let ArrayThunk::Waiting(expr) =
+			replace(&mut self.0.cached.borrow_mut()[index], ArrayThunk::Pending)
+		else {
 			unreachable!()
 		};
 
@@ -489,7 +491,9 @@
 			ArrayThunk::Waiting(..) => {}
 		};
 
-		let ArrayThunk::Waiting(_) = replace(&mut self.0.cached.borrow_mut()[index], ArrayThunk::Pending) else {
+		let ArrayThunk::Waiting(_) =
+			replace(&mut self.0.cached.borrow_mut()[index], ArrayThunk::Pending)
+		else {
 			unreachable!()
 		};
 
modifiedcrates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -276,7 +276,10 @@
 impl ManifestFormat for StringFormat {
 	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
 		let Val::Str(s) = val else {
-			throw!("output should be string for string manifest format, got {}", val.value_type())
+			throw!(
+				"output should be string for string manifest format, got {}",
+				val.value_type()
+			)
 		};
 		write!(out, "{s}").unwrap();
 		Ok(())
@@ -290,7 +293,10 @@
 impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {
 	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
 		let Val::Arr(arr) = val else {
-			throw!("output should be array for yaml stream format, got {}", val.value_type())
+			throw!(
+				"output should be array for yaml stream format, got {}",
+				val.value_type()
+			)
 		};
 		if !arr.is_empty() {
 			for v in arr.iter() {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -72,7 +72,8 @@
 			ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),
 			ThunkInner::Waiting(..) => (),
 		};
-		let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending) else {
+		let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)
+		else {
 			unreachable!();
 		};
 		let new_value = match value.0.get() {
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -51,7 +51,7 @@
 
 fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {
 	let Some(args) = type_is_path(ty, "Option") else {
-		return Ok(None)
+		return Ok(None);
 	};
 	// It should have only on angle-bracketed param ("<String>"):
 	let PathArguments::AngleBracketed(params) = args else {
@@ -63,7 +63,7 @@
 		return Err(Error::new(
 			generic_arg.span(),
 			"option generic should be a type",
-		))
+		));
 	};
 	Ok(Some(ty))
 }
@@ -210,7 +210,7 @@
 		return Err(Error::new(
 			fun.sig.span(),
 			"builtin should return something",
-		))
+		));
 	};
 
 	let name = fun.sig.ident.to_string();
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -630,7 +630,7 @@
 					el!(
 						Apply(
 							el!(
-								Index{
+								Index {
 									indexable: el!(Var("std".into()), 1, 4),
 									index: el!(Str("deepJoin".into()), 5, 13),
 									#[cfg(feature = "exp-null-coaelse")]
modifiedcrates/jrsonnet-parser/src/source.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/source.rs
+++ b/crates/jrsonnet-parser/src/source.rs
@@ -33,7 +33,7 @@
 		}
 		fn dyn_eq(&self, other: &dyn $T) -> bool {
 			let Some(other) = other.as_any().downcast_ref::<Self>() else {
-				return false
+				return false;
 			};
 			let this = <Self as $T>::as_any(self)
 				.downcast_ref::<Self>()
modifiedflake.lockdiffbeforeafterboth
--- a/flake.lock
+++ b/flake.lock
@@ -20,11 +20,11 @@
     },
     "nixpkgs": {
       "locked": {
-        "lastModified": 1689162265,
-        "narHash": "sha256-kdW79sfwX2TTX8yFBNUsEYOG+gQuAOHU+WcUtxMUnlc=",
+        "lastModified": 1690394427,
+        "narHash": "sha256-ZT1ABAZVdJycCJMUHu533dvcMuxqUGDnp6N2zLcFrv4=",
         "owner": "nixos",
         "repo": "nixpkgs",
-        "rev": "1941c7d8f1219c615a1d6dae826e0d6fab89acca",
+        "rev": "78df3591ec67310b8cc4b753e1496999da2678cf",
         "type": "github"
       },
       "original": {
@@ -50,11 +50,11 @@
         ]
       },
       "locked": {
-        "lastModified": 1689129196,
-        "narHash": "sha256-/z/Al4sFcIh5oPQWA9MclQmJR9g3RO8UDiHGaj/T9R8=",
+        "lastModified": 1690338181,
+        "narHash": "sha256-Sz2oQ9aNS3MVncnCMndr0302G26UrFUfPynoH2iLjsg=",
         "owner": "oxalica",
         "repo": "rust-overlay",
-        "rev": "db8d909c9526d4406579ee7343bf2d7de3d15eac",
+        "rev": "b7f0b7b58b3c6f14a1377ec31a3d78b23ab843ec",
         "type": "github"
       },
       "original": {
modifiedflake.nixdiffbeforeafterboth
--- a/flake.nix
+++ b/flake.nix
@@ -16,7 +16,7 @@
           inherit system;
           overlays = [ rust-overlay.overlays.default ];
         };
-        rust = ((pkgs.rustChannelOf { date = "2023-06-26"; channel = "nightly"; }).default.override {
+        rust = ((pkgs.rustChannelOf { date = "2023-07-23"; channel = "nightly"; }).default.override {
           extensions = [ "rust-src" "miri" "rust-analyzer" ];
         });
       in