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

difftreelog

source

bindings/jsonnet/src/import.rs4.1 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};19use jrsonnet_parser::SourcePath;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;2829/// Resolves imports using callback30pub struct CallbackImportResolver {31	cb: JsonnetImportCallback,32	ctx: *mut c_void,33	out: RefCell<HashMap<SourcePath, Vec<u8>>>,34}35impl ImportResolver for CallbackImportResolver {36	fn resolve_file_relative(&self, from: &Path, path: &str) -> Result<SourcePath> {37		let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();38		let rel = CString::new(path).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 = SourcePath::Path(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)77	}78	fn load_file_contents(&self, resolved: &SourcePath) -> Result<Vec<u8>> {79		Ok(self.out.borrow().get(resolved).unwrap().clone())80	}8182	unsafe fn as_any(&self) -> &dyn Any {83		self84	}85}8687/// # Safety88#[no_mangle]89pub unsafe extern "C" fn jsonnet_import_callback(90	vm: &State,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}100101/// Standard FS import resolver102#[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_relative(&self, from: &Path, path: &str) -> Result<SourcePath> {113		let mut new_path = from.to_owned();114		new_path.push(path);115		if new_path.exists() {116			Ok(SourcePath::Path(new_path))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(SourcePath::Path(cloned));123				}124			}125			throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))126		}127	}128	fn load_file_contents(&self, id: &SourcePath) -> Result<Vec<u8>> {129		let path = match id {130			SourcePath::Path(path) => path,131			_ => unreachable!("NativeImportResolver::resolve_file may only return plain paths"),132		};133		let mut file = File::open(path).map_err(|_e| ResolvedFileNotFound(id.clone()))?;134		let mut out = Vec::new();135		file.read_to_end(&mut out)136			.map_err(|e| ImportIo(e.to_string()))?;137		Ok(out)138	}139	unsafe fn as_any(&self) -> &dyn Any {140		self141	}142}143144/// # Safety145///146/// This function is safe, if received v is a pointer to normal C string147#[no_mangle]148pub unsafe extern "C" fn jsonnet_jpath_add(vm: &State, v: *const c_char) {149	let cstr = CStr::from_ptr(v);150	let path = PathBuf::from(cstr.to_str().unwrap());151	let any_resolver = vm.import_resolver();152	let resolver = any_resolver153		.as_any()154		.downcast_ref::<NativeImportResolver>()155		.expect("jpaths are not compatible with callback imports!");156	resolver.add_jpath(path);157}