git.delta.rocks / jrsonnet / refs/commits / 8db09e1bbe2e

difftreelog

source

cmds/jrsonnet/src/main.rs4.5 KiBsourcehistory
1use clap::{AppSettings, Clap, IntoApp};2use jrsonnet_cli::{ConfigureState, GcOpts, GeneralOpts, InputOpts, ManifestOpts, OutputOpts};3use jrsonnet_evaluator::{error::LocError, EvaluationState, ManifestFormat};4use std::{5	fs::{create_dir_all, File},6	io::Read,7	io::Write,8	path::PathBuf,9	str::FromStr,10};1112#[cfg(feature = "mimalloc")]13#[global_allocator]14static GLOBAL: mimallocator::Mimalloc = mimallocator::Mimalloc;1516#[derive(Clap)]17#[clap(help_heading = "DEBUG")]18struct DebugOpts {19	/// Required OS stack size.20	/// This shouldn't be changed unless jrsonnet is failing with stack overflow error.21	#[clap(long, name = "size")]22	pub os_stack: Option<usize>,23	/// Generate completions script24	#[clap(long)]25	generate: Option<GenerateTarget>,26}2728enum GenerateTarget {29	Bash,30	Zsh,31	Fish,32	PowerShell,33}34impl FromStr for GenerateTarget {35	type Err = &'static str;3637	fn from_str(s: &str) -> Result<Self, Self::Err> {38		match s {39			"bash" => Ok(Self::Bash),40			"zsh" => Ok(Self::Zsh),41			"fish" => Ok(Self::Fish),42			"powershell" => Ok(Self::PowerShell),43			_ => Err("unknown target"),44		}45	}46}4748#[derive(Clap)]49#[clap(50	global_setting = AppSettings::ColoredHelp,51	global_setting = AppSettings::DeriveDisplayOrder,52)]53struct Opts {54	#[clap(flatten)]55	input: InputOpts,56	#[clap(flatten)]57	general: GeneralOpts,58	#[clap(flatten)]59	manifest: ManifestOpts,60	#[clap(flatten)]61	output: OutputOpts,62	#[clap(flatten)]63	debug: DebugOpts,64	#[clap(flatten)]65	gc: GcOpts,66}6768fn main() {69	let opts: Opts = Opts::parse();7071	if let Some(target) = opts.debug.generate {72		use clap_generate::{generate, generators};73		use GenerateTarget::*;74		let app = &mut Opts::into_app();75		let buf = &mut std::io::stdout();76		let bin = "jrsonnet";77		match target {78			Bash => generate::<generators::Bash, _>(app, bin, buf),79			Zsh => generate::<generators::Zsh, _>(app, bin, buf),80			Fish => generate::<generators::Fish, _>(app, bin, buf),81			PowerShell => generate::<generators::PowerShell, _>(app, bin, buf),82		}83		std::process::exit(0);84	};8586	let success;87	if let Some(size) = opts.debug.os_stack {88		success = std::thread::Builder::new()89			.stack_size(size * 1024 * 1024)90			.spawn(|| main_catch(opts))91			.expect("new thread spawned")92			.join()93			.expect("thread finished successfully");94	} else {95		success = main_catch(opts)96	}97	if !success {98		std::process::exit(1);99	}100}101102#[derive(thiserror::Error, Debug)]103enum Error {104	// Handled differently105	#[error("evaluation error")]106	Evaluation(jrsonnet_evaluator::error::LocError),107	#[error("io error")]108	Io(#[from] std::io::Error),109	#[error("input is not utf8 encoded")]110	Utf8(#[from] std::str::Utf8Error),111}112impl From<LocError> for Error {113	fn from(e: LocError) -> Self {114		Self::Evaluation(e)115	}116}117118fn main_catch(opts: Opts) -> bool {119	let _printer = opts.gc.stats_printer();120	let state = EvaluationState::default();121	if let Err(e) = main_real(&state, opts) {122		if let Error::Evaluation(e) = e {123			eprintln!("{}", state.stringify_err(&e));124		} else {125			eprintln!("{}", e);126		}127		return false;128	}129	true130}131132fn main_real(state: &EvaluationState, opts: Opts) -> Result<(), Error> {133	opts.gc.configure_global();134	opts.general.configure(&state)?;135	opts.manifest.configure(&state)?;136137	let val = if opts.input.exec {138		state.set_manifest_format(ManifestFormat::ToString);139		state.evaluate_snippet_raw(140			PathBuf::from("args").into(),141			(&opts.input.input as &str).into(),142		)?143	} else if opts.input.input == "-" {144		let mut input = Vec::new();145		std::io::stdin().read_to_end(&mut input)?;146		let input_str = std::str::from_utf8(&input)?.into();147		state.evaluate_snippet_raw(PathBuf::from("<stdin>").into(), input_str)?148	} else {149		state.evaluate_file_raw(&PathBuf::from(opts.input.input))?150	};151152	let val = state.with_tla(val)?;153154	if let Some(multi) = opts.output.multi {155		if opts.output.create_output_dirs {156			let mut dir = multi.clone();157			dir.pop();158			create_dir_all(dir)?;159		}160		for (file, data) in state.manifest_multi(val)?.iter() {161			let mut path = multi.clone();162			path.push(&file as &str);163			if opts.output.create_output_dirs {164				let mut dir = path.clone();165				dir.pop();166				create_dir_all(dir)?;167			}168			println!("{}", path.to_str().expect("path"));169			let mut file = File::create(path)?;170			writeln!(file, "{}", data)?;171		}172	} else if let Some(path) = opts.output.output_file {173		if opts.output.create_output_dirs {174			let mut dir = path.clone();175			dir.pop();176			create_dir_all(dir)?;177		}178		let mut file = File::create(path)?;179		writeln!(file, "{}", state.manifest(val)?)?;180	} else {181		let output = state.manifest(val)?;182		if !output.is_empty() {183			println!("{}", output);184		}185	}186187	Ok(())188}