implement PathSearcher

to facilitate module reloading
This commit is contained in:
Andy Weidenbaum
2021-02-26 19:57:13 +11:00
parent a331b2bf8b
commit cf3a90faca
5 changed files with 209 additions and 2 deletions

View File

@@ -1,6 +1,7 @@
mod error;
mod searcher;
mod types;
mod utils;
pub use crate::error::Error;
pub use crate::searcher::AddSearcher;

View File

@@ -1,7 +1,11 @@
use rlua::prelude::LuaError;
use rlua::{Context, MetaMethod, RegistryKey, Table, UserData, UserDataMethods, Value};
use std::collections::HashMap;
use std::io::Read;
use std::path::Path;
use crate::types::Result;
use crate::utils;
/// Stores Lua modules indexed by module name, and provides an `rlua::MetaMethod`
/// to enable `require`ing the stored modules by name in an `rlua::Context`.
@@ -53,7 +57,7 @@ impl StaticSearcher {
impl UserData for StaticSearcher {
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_meta_method(MetaMethod::Call, |lua_ctx, this, name: String| {
match this.modules.get(&name.as_str()) {
match this.modules.get(name.as_str()) {
Some(content) => Ok(Value::Function(
lua_ctx
.load(content)
@@ -67,6 +71,62 @@ impl UserData for StaticSearcher {
}
}
/// Like `Searcher`, but with `modules` values given as paths to files containing Lua
/// source code to facilitate module reloading.
struct PathSearcher<P>
where
P: 'static + AsRef<Path> + Send,
{
modules: HashMap<String, P>,
globals: RegistryKey,
}
impl<P> PathSearcher<P>
where
P: 'static + AsRef<Path> + Send,
{
fn new(modules: HashMap<String, P>, globals: RegistryKey) -> Self {
Self { modules, globals }
}
}
impl<P> UserData for PathSearcher<P>
where
P: 'static + AsRef<Path> + Send,
{
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_meta_method(MetaMethod::Call, |lua_ctx, this, name: String| {
match this.modules.get(&name) {
Some(ref path) => {
let path = path.as_ref();
// Ensure `module_path` is relative to `$CARGO_MANIFEST_DIR`.
let path = if path.is_relative() {
utils::runtime_root().join(path)
} else {
path.to_path_buf()
};
let mut content = String::new();
let mut file = std::fs::File::open(path)
.map_err(|e| LuaError::RuntimeError(format!("io error: {:#?}", e)))?;
file.read_to_string(&mut content)
.map_err(|e| LuaError::RuntimeError(format!("io error: {:#?}", e)))?;
Ok(Value::Function(
lua_ctx
.load(&content)
.set_name(&name)?
.set_environment(lua_ctx.registry_value::<Table>(&this.globals)?)?
.into_function()?,
))
}
None => Ok(Value::Nil),
}
});
}
}
/// Extend `rlua::Context` to support `require`ing Lua modules by name.
pub trait AddSearcher {
/// Add a `HashMap` of Lua modules indexed by module name to Luas
@@ -77,6 +137,12 @@ pub trait AddSearcher {
/// Like `add_searcher`, but with Fennel source code encoded as `&'static str`
/// to facilitate compile-time includes.
fn add_static_searcher(&self, modules: HashMap<&'static str, &'static str>) -> Result<()>;
/// Like `add_searcher`, but with `modules` values given as paths to files containing
/// Lua source code to facilitate module reloading.
fn add_path_searcher<P>(&self, modules: HashMap<String, P>) -> Result<()>
where
P: 'static + AsRef<Path> + Send;
}
impl<'a> AddSearcher for Context<'a> {
@@ -99,4 +165,17 @@ impl<'a> AddSearcher for Context<'a> {
.set(searchers.len()? + 1, searcher)
.map_err(|e| e.into())
}
fn add_path_searcher<P>(&self, modules: HashMap<String, P>) -> Result<()>
where
P: 'static + AsRef<Path> + Send,
{
let globals = self.globals();
let searchers: Table = globals.get::<_, Table>("package")?.get("searchers")?;
let registry_key = self.create_registry_value(globals)?;
let searcher = PathSearcher::new(modules, registry_key);
searchers
.set(searchers.len()? + 1, searcher)
.map_err(|e| e.into())
}
}

6
src/utils.rs Normal file
View File

@@ -0,0 +1,6 @@
use std::path::PathBuf;
/// Return the value of `$CARGO_MANIFEST_DIR` at runtime.
pub(crate) fn runtime_root() -> PathBuf {
PathBuf::new().join(std::env::var("CARGO_MANIFEST_DIR").unwrap())
}