git.delta.rocks / jrsonnet / refs/commits / 68c8ac05879f

difftreelog

source

bindings/jsonnet/src/import.rs3.8 KiBsourcehistory
1//! Import resolution manipulation utilities23use 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};1415use jrsonnet_evaluator::{16	error::{Error::*, Result},17	throw, ImportResolver, State,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,32	out: RefCell<HashMap<PathBuf, Vec<u8>>>,33}34impl ImportResolver for CallbackImportResolver {35	fn resolve_file(&self, from: &Path, path: &str) -> Result<PathBuf> {36		let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();37		let rel = CString::new(path).unwrap().into_raw();38		let found_here: *mut c_char = null_mut();39		let mut success: i32 = 0;40		let result_ptr = unsafe {41			(self.cb)(42				self.ctx,43				base,44				rel,45				&mut (found_here as *const _),46				&mut success,47			)48		};49		// Release memory occipied by arguments passed50		unsafe {51			let _ = CString::from_raw(base);52			let _ = CString::from_raw(rel);53		}54		let result_raw = unsafe { CStr::from_ptr(result_ptr) };55		let result_str = result_raw.to_str().unwrap();56		assert!(success == 0 || success == 1);57		if success == 0 {58			unsafe { CString::from_raw(result_ptr) };59			let result = result_str.to_owned();60			throw!(ImportCallbackError(result));61		}6263		let found_here_raw = unsafe { CStr::from_ptr(found_here) };64		let found_here_buf = PathBuf::from(found_here_raw.to_str().unwrap());65		unsafe {66			let _ = CString::from_raw(found_here);67		}6869		let mut out = self.out.borrow_mut();70		if !out.contains_key(&found_here_buf) {71			out.insert(found_here_buf.clone(), result_str.into());72			unsafe { CString::from_raw(result_ptr) };73		}7475		Ok(found_here_buf)76	}77	fn load_file_contents(&self, resolved: &Path) -> Result<Vec<u8>> {78		Ok(self.out.borrow().get(resolved).unwrap().clone())79	}8081	unsafe fn as_any(&self) -> &dyn Any {82		self83	}84}8586/// # Safety87#[no_mangle]88pub unsafe extern "C" fn jsonnet_import_callback(89	vm: &State,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: &str) -> Result<PathBuf> {112		let mut new_path = from.to_owned();113		new_path.push(path);114		if new_path.exists() {115			Ok(new_path)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);122				}123			}124			throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))125		}126	}127	fn load_file_contents(&self, id: &Path) -> Result<Vec<u8>> {128		let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;129		let mut out = Vec::new();130		file.read_to_end(&mut out)131			.map_err(|e| ImportIo(e.to_string()))?;132		Ok(out)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: &State, 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.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}