git.delta.rocks / jrsonnet / refs/commits / 7324ad9b219d

difftreelog

refactor jrsonnet cli should not depend on ir

kmmmlsnrYaroslav Bolyukin2026-05-06parent: #34f8ef7.patch.diff
in: master

3 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2459,7 +2459,6 @@
  "jrsonnet-cli",
  "jrsonnet-evaluator",
  "jrsonnet-gcmodule",
- "jrsonnet-ir",
  "mimallocator",
  "serde",
  "serde_json",
modifiedcmds/jrsonnet/Cargo.tomldiffbeforeafterboth
--- a/cmds/jrsonnet/Cargo.toml
+++ b/cmds/jrsonnet/Cargo.toml
@@ -40,7 +40,6 @@
 # obj?.field, obj?.['field']
 exp-null-coaelse = [
   "jrsonnet-evaluator/exp-null-coaelse",
-  "jrsonnet-ir/exp-null-coaelse",
   "jrsonnet-cli/exp-null-coaelse",
 ]
 # --exp-apply
@@ -48,7 +47,6 @@
 
 [dependencies]
 jrsonnet-evaluator.workspace = true
-jrsonnet-ir.workspace = true
 jrsonnet-cli.workspace = true
 jrsonnet-gcmodule.workspace = true
 
modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
after · cmds/jrsonnet/src/main.rs
1use std::{2	fs::{File, create_dir_all},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	ResultExt, SourceDefaultIgnoreJpath, SourcePath, State, Val, apply_tla, bail,11	error::{Error as JrError, ErrorKind},12};1314#[cfg(feature = "mimalloc")]15#[global_allocator]16static GLOBAL: mimallocator::Mimalloc = mimallocator::Mimalloc;1718#[derive(Parser)]19enum SubOpts {20	/// Generate completions for specified shell21	Generate {22		/// Target shell name23		shell: Shell,24	},25}2627#[derive(Parser)]28#[clap(next_help_heading = "DEBUG")]29struct DebugOpts {30	/// Required OS stack size.31	/// This shouldn't be changed unless jrsonnet is failing with stack overflow error.32	#[clap(long, name = "size")]33	pub os_stack: Option<usize>,34}3536#[derive(Parser)]37#[clap(next_help_heading = "INPUT")]38struct InputOpts {39	/// Treat input as code, evaluate it instead of reading file.40	#[clap(long, short = 'e')]41	pub exec: bool,4243	/// Path to the file to be compiled if `--exec` is unset, otherwise code itself.44	pub input: Option<String>,4546	/// After executing input, apply specified code.47	/// Output of the initial input will be accessible using `_`.48	#[cfg(feature = "exp-apply")]49	#[clap(long)]50	pub exp_apply: Vec<String>,51}5253/// Jsonnet commandline interpreter (Rust implementation)54#[derive(Parser)]55#[clap(56	args_conflicts_with_subcommands = true,57	disable_version_flag = true,58	version,59	author60)]61struct Opts {62	#[clap(subcommand)]63	sub: Option<SubOpts>,64	/// Print version65	#[clap(long)]66	version: bool,6768	#[clap(flatten)]69	input: InputOpts,70	#[clap(flatten)]71	misc: MiscOpts,72	#[clap(flatten)]73	tla: TlaOpts,74	#[clap(flatten)]75	std: StdOpts,76	#[clap(flatten)]77	gc: GcOpts,7879	#[clap(flatten)]80	trace: TraceOpts,81	#[clap(flatten)]82	manifest: ManifestOpts,83	#[clap(flatten)]84	output: OutputOpts,85	#[clap(flatten)]86	debug: DebugOpts,87}8889// TODO: Add unix_sigpipe = "sig_dfl"90fn 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 trace = opts.trace.trace_format();150	if let Err(e) = main_real(opts) {151		if let Error::Evaluation(e) = e {152			let mut out = String::new();153			trace.write_trace(&mut out, &e).expect("format error");154			eprintln!("{out}");155		} else {156			eprintln!("{e}");157		}158		return false;159	}160	true161}162163fn main_real(opts: Opts) -> Result<(), Error> {164	let _gc_leak_guard = opts.gc.leak_on_exit();165	let _gc_print_stats = opts.gc.stats_printer();166	let _stack_depth_override = opts.misc.stack_size_override();167168	let import_resolver = opts.misc.import_resolver();169	let std = opts.std.context_initializer()?;170171	let mut s = State::builder();172	s.import_resolver(import_resolver).context_initializer(std);173	let s = s.build();174	let _s = s.enter();175176	let input = opts.input.input.ok_or(Error::MissingInputArgument)?;177	let val = if opts.input.exec {178		s.evaluate_snippet("<cmdline>".to_owned(), &input as &str)?179	} else if input == "-" {180		let mut input = Vec::new();181		std::io::stdin().read_to_end(&mut input)?;182		let input_str = std::str::from_utf8(&input)?;183		s.evaluate_snippet("<stdin>".to_owned(), input_str)?184	} else {185		s.import_from(&SourcePath::new(SourceDefaultIgnoreJpath), input.as_str())?186	};187188	let tla = opts.tla.tla_opts()?;189	#[allow(190		// It is not redundant/unused in exp-apply191		unused_mut,192		clippy::redundant_clone,193	)]194	let mut val = apply_tla(&tla, val)?;195196	#[cfg(feature = "exp-apply")]197	for apply in opts.input.exp_apply {198		use jrsonnet_evaluator::{InitialUnderscore, Thunk};199		val = s.evaluate_snippet_with(200			"<exp_apply>".to_owned(),201			&apply,202			&InitialUnderscore(Thunk::evaluated(val)),203		)?;204	}205206	let manifest_format = opts.manifest.manifest_format();207	if let Some(multi) = opts.output.multi {208		if opts.output.create_output_dirs {209			let mut dir = multi.clone();210			dir.pop();211			create_dir_all(dir)?;212		}213		let Val::Obj(obj) = val else {214			bail!(215				"value should be object for --multi manifest, got {}",216				val.value_type()217			)218		};219		for (field, data) in obj.iter(220			#[cfg(feature = "exp-preserve-order")]221			opts.manifest.preserve_order,222		) {223			let data = data.with_description(|| format!("getting field {field} for manifest"))?;224225			let mut path = multi.clone();226			path.push(&field as &str);227			if opts.output.create_output_dirs {228				let mut dir = path.clone();229				dir.pop();230				create_dir_all(dir)?;231			}232			println!("{}", path.to_str().expect("path"));233			let mut file = File::create(path)?;234			write!(235				file,236				"{}",237				data.manifest(&manifest_format)238					.with_description(|| format!("manifesting {field}"))?,239			)?;240			if !opts.manifest.no_trailing_newline {241				writeln!(file)?;242			}243			file.flush()?;244		}245	} else if let Some(path) = opts.output.output_file {246		if opts.output.create_output_dirs {247			let mut dir = path.clone();248			dir.pop();249			create_dir_all(dir)?;250		}251		let mut file = File::create(path)?;252		writeln!(file, "{}", val.manifest(manifest_format)?)?;253	} else {254		let output = val.manifest(manifest_format)?;255		if !output.is_empty() {256			println!("{output}");257		}258	}259260	Ok(())261}