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

difftreelog

source

crates/jrsonnet-evaluator/src/import.rs4.7 KiBsourcehistory
1use std::{2	any::Any,3	cell::RefCell,4	env::current_dir,5	fs,6	io::{ErrorKind, Read},7	path::{Path, PathBuf},8};910use fs::File;11use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};1213use crate::{14	error::{15		Error::{self, *},16		Result,17	},18	throw,19};2021/// Implements file resolution logic for `import` and `importStr`22pub trait ImportResolver {23	/// Resolves file path, e.g. `(/home/user/manifests, b.libjsonnet)` can correspond24	/// both to `/home/user/manifests/b.libjsonnet` and to `/home/user/${vendor}/b.libjsonnet`25	/// where `${vendor}` is a library path.26	///27	/// `from` should only be returned from [`ImportResolver::resolve`], or from other defined file, any other value28	/// may result in panic29	fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {30		throw!(ImportNotSupported(from.clone(), path.into()))31	}32	fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {33		self.resolve_from(&SourcePath::default(), path)34	}35	/// Resolves absolute path, doesn't supports jpath and other fancy things36	fn resolve(&self, path: &Path) -> Result<SourcePath> {37		throw!(AbsoluteImportNotSupported(path.to_owned()))38	}3940	/// Load resolved file41	/// This should only be called with value returned from [`ImportResolver::resolve_file`]/[`ImportResolver::resolve`],42	/// this cannot be resolved using associated type, as evaluator uses object instead of generic for [`ImportResolver`]43	fn load_file_contents(&self, resolved: &SourcePath) -> Result<Vec<u8>>;4445	/// For downcasts46	fn as_any(&self) -> &dyn Any;47}4849/// Dummy resolver, can't resolve/load any file50pub struct DummyImportResolver;51impl ImportResolver for DummyImportResolver {52	fn load_file_contents(&self, _resolved: &SourcePath) -> Result<Vec<u8>> {53		panic!("dummy resolver can't load any file")54	}5556	fn as_any(&self) -> &dyn Any {57		self58	}59}60#[allow(clippy::use_self)]61impl Default for Box<dyn ImportResolver> {62	fn default() -> Self {63		Box::new(DummyImportResolver)64	}65}6667/// File resolver, can load file from both FS and library paths68#[derive(Default)]69pub struct FileImportResolver {70	/// Library directories to search for file.71	/// Referred to as `jpath` in original jsonnet implementation.72	library_paths: RefCell<Vec<PathBuf>>,73}74impl FileImportResolver {75	pub fn new(jpath: Vec<PathBuf>) -> Self {76		Self {77			library_paths: RefCell::new(jpath),78		}79	}80	/// Dynamically add new jpath, used by bindings81	pub fn add_jpath(&self, path: PathBuf) {82		self.library_paths.borrow_mut().push(path);83	}84}85impl ImportResolver for FileImportResolver {86	fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {87		let mut direct = if let Some(f) = from.downcast_ref::<SourceFile>() {88			let mut o = f.path().to_owned();89			o.pop();90			o91		} else if let Some(d) = from.downcast_ref::<SourceDirectory>() {92			d.path().to_owned()93		} else if from.is_default() {94			current_dir().map_err(|e| Error::ImportIo(e.to_string()))?95		} else {96			unreachable!("resolver can't return this path")97		};98		direct.push(path);99		if direct.is_file() {100			Ok(SourcePath::new(SourceFile::new(101				direct.canonicalize().map_err(|e| ImportIo(e.to_string()))?,102			)))103		} else {104			for library_path in self.library_paths.borrow().iter() {105				let mut cloned = library_path.clone();106				cloned.push(path);107				if cloned.exists() {108					return Ok(SourcePath::new(SourceFile::new(109						cloned.canonicalize().map_err(|e| ImportIo(e.to_string()))?,110					)));111				}112			}113			throw!(ImportFileNotFound(from.clone(), path.to_owned()))114		}115	}116	fn resolve(&self, path: &Path) -> Result<SourcePath> {117		let meta = match fs::metadata(path) {118			Ok(v) => v,119			Err(e) if e.kind() == ErrorKind::NotFound => {120				throw!(AbsoluteImportFileNotFound(path.to_owned()))121			}122			Err(e) => throw!(Error::ImportIo(e.to_string())),123		};124		if meta.is_file() {125			Ok(SourcePath::new(SourceFile::new(126				path.canonicalize().map_err(|e| ImportIo(e.to_string()))?,127			)))128		} else if meta.is_dir() {129			Ok(SourcePath::new(SourceDirectory::new(130				path.canonicalize().map_err(|e| ImportIo(e.to_string()))?,131			)))132		} else {133			unreachable!("this can't be a symlink")134		}135	}136137	fn load_file_contents(&self, id: &SourcePath) -> Result<Vec<u8>> {138		let path = if let Some(f) = id.downcast_ref::<SourceFile>() {139			f.path()140		} else if id.downcast_ref::<SourceDirectory>().is_some() || id.is_default() {141			throw!(Error::ImportIsADirectory(id.clone()))142		} else {143			unreachable!("other types are not supported in resolve");144		};145		let mut file = File::open(path).map_err(|_e| ResolvedFileNotFound(id.clone()))?;146		let mut out = Vec::new();147		file.read_to_end(&mut out)148			.map_err(|e| ImportIo(e.to_string()))?;149		Ok(out)150	}151152	fn as_any(&self) -> &dyn Any {153		self154	}155156	fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {157		self.resolve_from(&SourcePath::default(), path)158	}159}