CertainLach / jrsonnet

Rust implementation of Jsonnet language
MIT License
290 stars 33 forks source link

Add quick start information in README #167

Open ppom0 opened 1 month ago

ppom0 commented 1 month ago

I spent a lot of time reading cmds/jrsonnet/src/main.rs and libraries source code to be able to make this quick start example, so I guess it would help other people as well to have a minimal example to start with!

I've written this code for 0.4.2.

Maybe this could be added to the README or somewhere in the doc?

use std::path::PathBuf;

use jrsonnet_evaluator::{error::LocError, EvaluationState, FileImportResolver};

pub fn from_path(path: &PathBuf) -> Result<String, String> {
    let state = EvaluationState::default();
    state.with_stdlib();
    state.set_import_resolver(Box::new(FileImportResolver::default()));

    match evaluate(path, &state) {
        Ok(val) => Ok(val),
        Err(err) => Err(state.stringify_err(&err)),
    }
}
fn evaluate(path: &PathBuf, state: &EvaluationState) -> Result<String, LocError> {
    let val = state.evaluate_file_raw(path)?;
    let result = state.manifest(val)?;
    Ok(result.to_string())
}
CertainLach commented 2 weeks ago

Usually, when I need to get examples on using the code, I look into tests, there is one for basic initialization and using std.native https://github.com/CertainLach/jrsonnet/blob/master/tests/tests/std_native.rs

But I agree tests are sometimes more complicated than it should be, I'll create a dedicated examples which are ran by cargo run --example basic