git.delta.rocks / jrsonnet / refs/commits / d37d57f47273

difftreelog

source

cmds/jsonnet/src/main.rs2.5 KiBsourcehistory
1use clap::Clap;2use jsonnet_evaluator::Val;3use std::str::FromStr;45enum Format {6	None,7	Json,8}910impl FromStr for Format {11	type Err = &'static str;12	fn from_str(s: &str) -> Result<Self, Self::Err> {13		Ok(match s {14			"none" => Format::None,15			"json" => Format::Json,16			_ => return Err("no such format"),17		})18	}19}2021#[derive(Clap)]22#[clap(version = "0.1.0", author = "Lach <iam@lach.pw>")]23struct Opts {24	#[clap(about = "File to compile")]25	input: String,26	#[clap(long, about = "Disable global std variable")]27	no_stdlib: bool,28	#[clap(long, short = "f", default_value = "none", possible_values = &["none", "json"])]29	format: Format,30}3132fn main() {33	let opts: Opts = Opts::parse();34	let evaluator = jsonnet_evaluator::EvaluationState::default();35	if !opts.no_stdlib {36		evaluator.add_stdlib();37	}38	evaluator39		.add_file(40			opts.input.clone(),41			String::from_utf8(std::fs::read(opts.input.clone()).unwrap()).unwrap(),42		)43		.unwrap();44	let result = evaluator.evaluate_file(&opts.input);45	match result {46		Ok(mut v) => {47			if let Format::Json = opts.format {48				if opts.no_stdlib {49					evaluator.add_stdlib();50				}51				evaluator.add_global("__tmp__to_json__".to_owned(), v);52				v = evaluator53					.parse_evaluate_raw("std.manifestJson(__tmp__to_json__)")54					.expect("json serialization");55			}56			match v {57			Val::Str(s) => println!("{}", s),58			Val::Num(n) => println!("{}", n),59			_v => eprintln!(60				"jsonnet output is not a string.\nDid you forgot to set --format, or wrap your data with std.manifestJson?"61			),62		}63		}64		Err(err) => {65			println!("Error: {:?}", err.0);66			use annotate_snippets::{67				display_list::{DisplayList, FormatOptions},68				snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation},69			};70			for item in (err.1).0.iter() {71				let desc = &item.1;72				if (item.0).1.is_none() {73					continue;74				}75				let source = (item.0).1.clone().unwrap();76				let code = evaluator.get_source(&source.0);77				let snippet = Snippet {78					opt: FormatOptions {79						color: true,80						..Default::default()81					},82					title: Some(Annotation {83						label: Some(&item.1),84						id: None,85						annotation_type: AnnotationType::Error,86					}),87					footer: vec![],88					slices: vec![Slice {89						source: &code,90						line_start: 1,91						origin: Some(&source.0),92						fold: true,93						annotations: vec![SourceAnnotation {94							label: desc,95							annotation_type: AnnotationType::Error,96							range: (source.1, source.2),97						}],98					}],99				};100101				let dl = DisplayList::from(snippet);102				println!("{}", dl);103			}104		}105	}106}