git.delta.rocks / jrsonnet / refs/commits / 4f4be44d138e

difftreelog

source

bindings/jsonnet/src/import.rs3.9 KiBsourcehistory
1//! Import resolution manipulation utilities23use jrsonnet_evaluator::{4	error::{Error::*, Result},5	throw, EvaluationState, IStr, ImportResolver,6};7use std::{8	any::Any,9	cell::RefCell,10	collections::HashMap,11	ffi::{c_void, CStr, CString},12	fs::File,13	io::Read,14	os::raw::{c_char, c_int},15	path::{Path, PathBuf},16	ptr::null_mut,17	rc::Rc,18};1920pub type JsonnetImportCallback = unsafe extern "C" fn(21	ctx: *mut c_void,22	base: *const c_char,23	rel: *const c_char,24	found_here: *mut *const c_char,25	success: &mut c_int,26) -> *mut c_char;2728/// Resolves imports using callback29pub struct CallbackImportResolver {30	cb: JsonnetImportCallback,31	ctx: *mut c_void,3233	out: RefCell<HashMap<PathBuf, IStr>>,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		// Release memory occipied by arguments passed51		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<IStr> {79		Ok(self.out.borrow().get(resolved).unwrap().clone())80	}81	unsafe fn as_any(&self) -> &dyn Any {82		self83	}84}8586/// # Safety87#[no_mangle]88pub unsafe extern "C" fn jsonnet_import_callback(89	vm: &EvaluationState,90	cb: JsonnetImportCallback,91	ctx: *mut c_void,92) {93	vm.set_import_resolver(Box::new(CallbackImportResolver {94		cb,95		ctx,96		out: RefCell::new(HashMap::new()),97	}))98}99100/// Standard FS import resolver101#[derive(Default)]102pub struct NativeImportResolver {103	library_paths: RefCell<Vec<PathBuf>>,104}105impl NativeImportResolver {106	fn add_jpath(&self, path: PathBuf) {107		self.library_paths.borrow_mut().push(path);108	}109}110impl ImportResolver for NativeImportResolver {111	fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {112		let mut new_path = from.to_owned();113		new_path.push(path);114		if new_path.exists() {115			Ok(new_path.into())116		} else {117			for library_path in self.library_paths.borrow().iter() {118				let mut cloned = library_path.clone();119				cloned.push(path);120				if cloned.exists() {121					return Ok(cloned.into());122				}123			}124			throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))125		}126	}127	fn load_file_contents(&self, id: &Path) -> Result<IStr> {128		let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;129		let mut out = String::new();130		file.read_to_string(&mut out)131			.map_err(|_e| ImportBadFileUtf8(id.to_owned()))?;132		Ok(out.into())133	}134	unsafe fn as_any(&self) -> &dyn Any {135		self136	}137}138139/// # Safety140///141/// This function is safe, if received v is a pointer to normal C string142#[no_mangle]143pub unsafe extern "C" fn jsonnet_jpath_add(vm: &EvaluationState, v: *const c_char) {144	let cstr = CStr::from_ptr(v);145	let path = PathBuf::from(cstr.to_str().unwrap());146	let any_resolver = &vm.settings().import_resolver;147	let resolver = any_resolver148		.as_any()149		.downcast_ref::<NativeImportResolver>()150		.expect("jpaths are not compatible with callback imports!");151	resolver.add_jpath(path);152}