123use std::{4 any::Any,5 cell::RefCell,6 collections::HashMap,7 ffi::{c_void, CStr, CString},8 fs::File,9 io::Read,10 os::raw::{c_char, c_int},11 path::{Path, PathBuf},12 ptr::null_mut,13 rc::Rc,14};1516use jrsonnet_evaluator::{17 error::{Error::*, Result},18 throw, EvaluationState, ImportResolver,19};2021pub type JsonnetImportCallback = unsafe extern "C" fn(22 ctx: *mut c_void,23 base: *const c_char,24 rel: *const c_char,25 found_here: *mut *const c_char,26 success: &mut c_int,27) -> *mut c_char;282930pub struct CallbackImportResolver {31 cb: JsonnetImportCallback,32 ctx: *mut c_void,33 out: RefCell<HashMap<PathBuf, Vec<u8>>>,34}35impl ImportResolver for CallbackImportResolver {36 fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {37 let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();38 let rel = CString::new(path.to_str().unwrap()).unwrap().into_raw();39 let found_here: *mut c_char = null_mut();40 let mut success: i32 = 0;41 let result_ptr = unsafe {42 (self.cb)(43 self.ctx,44 base,45 rel,46 &mut (found_here as *const _),47 &mut success,48 )49 };50 51 unsafe {52 let _ = CString::from_raw(base);53 let _ = CString::from_raw(rel);54 }55 let result_raw = unsafe { CStr::from_ptr(result_ptr) };56 let result_str = result_raw.to_str().unwrap();57 assert!(success == 0 || success == 1);58 if success == 0 {59 unsafe { CString::from_raw(result_ptr) };60 let result = result_str.to_owned();61 throw!(ImportCallbackError(result));62 }6364 let found_here_raw = unsafe { CStr::from_ptr(found_here) };65 let found_here_buf = PathBuf::from(found_here_raw.to_str().unwrap());66 unsafe {67 let _ = CString::from_raw(found_here);68 }6970 let mut out = self.out.borrow_mut();71 if !out.contains_key(&found_here_buf) {72 out.insert(found_here_buf.clone(), result_str.into());73 unsafe { CString::from_raw(result_ptr) };74 }7576 Ok(found_here_buf.into())77 }78 fn load_file_contents(&self, resolved: &Path) -> Result<Vec<u8>> {79 Ok(self.out.borrow().get(resolved).unwrap().clone())80 }8182 unsafe fn as_any(&self) -> &dyn Any {83 self84 }85}868788#[no_mangle]89pub unsafe extern "C" fn jsonnet_import_callback(90 vm: &EvaluationState,91 cb: JsonnetImportCallback,92 ctx: *mut c_void,93) {94 vm.set_import_resolver(Box::new(CallbackImportResolver {95 cb,96 ctx,97 out: RefCell::new(HashMap::new()),98 }))99}100101102#[derive(Default)]103pub struct NativeImportResolver {104 library_paths: RefCell<Vec<PathBuf>>,105}106impl NativeImportResolver {107 fn add_jpath(&self, path: PathBuf) {108 self.library_paths.borrow_mut().push(path);109 }110}111impl ImportResolver for NativeImportResolver {112 fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {113 let mut new_path = from.to_owned();114 new_path.push(path);115 if new_path.exists() {116 Ok(new_path.into())117 } else {118 for library_path in self.library_paths.borrow().iter() {119 let mut cloned = library_path.clone();120 cloned.push(path);121 if cloned.exists() {122 return Ok(cloned.into());123 }124 }125 throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))126 }127 }128 fn load_file_contents(&self, id: &Path) -> Result<Vec<u8>> {129 let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;130 let mut out = Vec::new();131 file.read_to_end(&mut out)132 .map_err(|e| ImportIo(e.to_string()))?;133 Ok(out)134 }135 unsafe fn as_any(&self) -> &dyn Any {136 self137 }138}139140141142143#[no_mangle]144pub unsafe extern "C" fn jsonnet_jpath_add(vm: &EvaluationState, v: *const c_char) {145 let cstr = CStr::from_ptr(v);146 let path = PathBuf::from(cstr.to_str().unwrap());147 let any_resolver = &vm.settings().import_resolver;148 let resolver = any_resolver149 .as_any()150 .downcast_ref::<NativeImportResolver>()151 .expect("jpaths are not compatible with callback imports!");152 resolver.add_jpath(path);153}