Compare commits
16 Commits
6f6c6be1da
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 2585e7ce34 | |||
| 158f4c7cb3 | |||
|
9073e924c6
|
|||
|
22672c76b0
|
|||
|
ae42899727
|
|||
|
2b29a9d0e8
|
|||
|
|
c2c257e116 | ||
|
|
38e3838a7c | ||
|
|
4d6d2a1697 | ||
|
|
f05e0966cb | ||
|
|
c252048e2f | ||
|
|
357f2b6fdd | ||
|
|
dd252db5c8 | ||
|
|
57492ba18f | ||
|
|
3daf079207 | ||
|
|
a2a801e69d |
11
Cargo.toml
11
Cargo.toml
@@ -1,14 +1,15 @@
|
||||
[package]
|
||||
name = "rlua-searcher"
|
||||
version = "0.1.0"
|
||||
edition = "2018"
|
||||
authors = ["Andy Weidenbaum <atweiden@ioiojo.com>"]
|
||||
edition = "2021"
|
||||
authors = ["Andy Weidenbaum <atweiden@ioiojo.com>", "Kasper J. Hermansen <contact@kjuulh.io>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
keywords = ["lua"]
|
||||
homepage = "https://git.sr.ht/~ioiojo/rlua-searcher"
|
||||
repository = "https://git.sr.ht/~ioiojo/rlua-searcher"
|
||||
homepage = "https://git.front.kjuulh.io/kjuulh/rlua-searcher"
|
||||
repository = "https://git.front.kjuulh.io/kjuulh/rlua-searcher"
|
||||
readme = "README.md"
|
||||
description = "Require Lua modules by name"
|
||||
publishable = true
|
||||
|
||||
[dependencies]
|
||||
rlua = "0.17"
|
||||
rlua = "0.19.5"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2021 Andy Weidenbaum
|
||||
Copyright (c) 2023 Andy Weidenbaum
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
`require` Lua modules by name
|
||||
|
||||
(This is a fork of https://git.sr.ht/~ioiojo/rlua-searcher, I don't maintain this code, I just need to available on crates.io for other dependent packages.)
|
||||
|
||||
## Description
|
||||
|
||||
Encode a Lua module as a `HashMap` of Lua strings indexed by module
|
||||
|
||||
3
renovate.json
Normal file
3
renovate.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json"
|
||||
}
|
||||
@@ -9,6 +9,12 @@ impl From<rlua::Error> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Error> for rlua::Error {
|
||||
fn from(error: Error) -> Self {
|
||||
rlua::Error::RuntimeError(format!("rlua-searcher error: {}", error))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let res = match self {
|
||||
|
||||
100
src/io_cat.rs
Normal file
100
src/io_cat.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::{BufReader, Cursor, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::string::String;
|
||||
|
||||
pub type CatBox = Box<dyn Cat + Send + Sync>;
|
||||
pub type CatMap<K> = HashMap<K, CatBox>;
|
||||
|
||||
pub trait Cat {
|
||||
fn cat(&self) -> io::Result<String>;
|
||||
}
|
||||
|
||||
impl Cat for PathBuf {
|
||||
fn cat(&self) -> io::Result<String> {
|
||||
self.as_path().cat()
|
||||
}
|
||||
}
|
||||
|
||||
impl Cat for &Path {
|
||||
fn cat(&self) -> io::Result<String> {
|
||||
let mut input = File::open(self)?;
|
||||
read_to_string(&mut input)
|
||||
}
|
||||
}
|
||||
|
||||
impl Cat for Cow<'_, Path> {
|
||||
fn cat(&self) -> io::Result<String> {
|
||||
self.as_ref().cat()
|
||||
}
|
||||
}
|
||||
|
||||
impl Cat for String {
|
||||
fn cat(&self) -> io::Result<String> {
|
||||
self.as_str().cat()
|
||||
}
|
||||
}
|
||||
|
||||
impl Cat for &str {
|
||||
fn cat(&self) -> io::Result<String> {
|
||||
let mut input = Cursor::new(self);
|
||||
read_to_string(&mut input)
|
||||
}
|
||||
}
|
||||
|
||||
impl Cat for Cow<'_, str> {
|
||||
fn cat(&self) -> io::Result<String> {
|
||||
self.as_ref().cat()
|
||||
}
|
||||
}
|
||||
|
||||
fn read_to_string<R>(input: &mut R) -> io::Result<String>
|
||||
where
|
||||
R: Read,
|
||||
{
|
||||
let mut text = String::new();
|
||||
let mut reader = BufReader::new(input);
|
||||
reader.read_to_string(&mut text)?;
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::borrow::Cow;
|
||||
use std::env;
|
||||
use std::path::Path;
|
||||
|
||||
use super::CatMap;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
const ENV_VAR_OS_CARGO_MANIFEST_DIR: &str =
|
||||
"Unexpectedly could not read `CARGO_MANIFEST_DIR` environment variable";
|
||||
let mut cat_map: CatMap<Cow<'static, str>> = CatMap::new();
|
||||
cat_map.insert(Cow::from("Apr"), Box::new("Showers"));
|
||||
cat_map.insert(
|
||||
Cow::from("May"),
|
||||
Box::new(
|
||||
Path::new(&env::var_os("CARGO_MANIFEST_DIR").expect(ENV_VAR_OS_CARGO_MANIFEST_DIR))
|
||||
.join("testdata")
|
||||
.join("may.txt"),
|
||||
),
|
||||
);
|
||||
assert_eq!(
|
||||
cat_map.get(&Cow::from("Apr")).unwrap().cat().unwrap(),
|
||||
String::from("Showers")
|
||||
);
|
||||
assert_eq!(
|
||||
cat_map
|
||||
.get(&Cow::from("May"))
|
||||
.unwrap()
|
||||
.cat()
|
||||
.unwrap()
|
||||
.trim_end(),
|
||||
String::from("Flowers")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
mod error;
|
||||
mod io_cat;
|
||||
mod searcher;
|
||||
mod types;
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::types::Result;
|
||||
use crate::types::{CatMap, Result};
|
||||
|
||||
/// 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`.
|
||||
@@ -118,18 +118,18 @@ where
|
||||
/// `rlua::Context` with Rust code.
|
||||
///
|
||||
/// Enables exposing `UserData` types to an `rlua::Context`.
|
||||
pub struct ClosureSearcher {
|
||||
struct ClosureSearcher {
|
||||
/// Closures must accept three parameters:
|
||||
///
|
||||
/// 1. An `rlua::Context`, which the closure can do what it wants with.
|
||||
///
|
||||
/// 2. An `rlua::Table` containing globals (i.e. Lua’s `_G`), which can be passed
|
||||
/// to `Chunk.set_environment()`.
|
||||
/// 2. An `rlua::Table` containing globals (i.e. Lua's `_G`), which can be passed to
|
||||
/// `Chunk.set_environment()`.
|
||||
///
|
||||
/// 3. The name of the module to be loaded (`&str`).
|
||||
///
|
||||
/// Closures must return an `rlua::Result`-wrapped `Function`. This `Function`
|
||||
/// acts as the module loader.
|
||||
/// Closures must return an `rlua::Result`-wrapped `Function`. This `Function` acts as
|
||||
/// the module loader.
|
||||
modules: HashMap<
|
||||
Cow<'static, str>,
|
||||
Box<
|
||||
@@ -142,7 +142,7 @@ pub struct ClosureSearcher {
|
||||
}
|
||||
|
||||
impl ClosureSearcher {
|
||||
pub fn new(
|
||||
fn new(
|
||||
modules: HashMap<
|
||||
Cow<'static, str>,
|
||||
Box<
|
||||
@@ -178,22 +178,22 @@ impl UserData for ClosureSearcher {
|
||||
}
|
||||
}
|
||||
|
||||
/// Like `Searcher`, but with function pointers as `modules` values, to facilitate
|
||||
/// setting up an `rlua::Context` with Rust code.
|
||||
/// Like `Searcher`, but with function pointers as `modules` values, to facilitate setting
|
||||
/// up an `rlua::Context` with Rust code.
|
||||
///
|
||||
/// Enables exposing `UserData` types to an `rlua::Context`.
|
||||
pub struct FunctionSearcher {
|
||||
struct FunctionSearcher {
|
||||
/// Functions must accept three parameters:
|
||||
///
|
||||
/// 1. An `rlua::Context`, which the function body can do what it wants with.
|
||||
///
|
||||
/// 2. An `rlua::Table` containing globals (i.e. Lua’s `_G`), which can be passed
|
||||
/// to `Chunk.set_environment()`.
|
||||
/// 2. An `rlua::Table` containing globals (i.e. Lua's `_G`), which can be passed to
|
||||
/// `Chunk.set_environment()`.
|
||||
///
|
||||
/// 3. The name of the module to be loaded (`&str`).
|
||||
///
|
||||
/// Functions must return an `rlua::Result`-wrapped `Function`. This `Function`
|
||||
/// acts as the module loader.
|
||||
/// Functions must return an `rlua::Result`-wrapped `Function`. This `Function` acts
|
||||
/// as the module loader.
|
||||
modules: HashMap<
|
||||
Cow<'static, str>,
|
||||
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
|
||||
@@ -203,7 +203,7 @@ pub struct FunctionSearcher {
|
||||
}
|
||||
|
||||
impl FunctionSearcher {
|
||||
pub fn new(
|
||||
fn new(
|
||||
modules: HashMap<
|
||||
Cow<'static, str>,
|
||||
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
|
||||
@@ -236,11 +236,50 @@ impl UserData for FunctionSearcher {
|
||||
}
|
||||
}
|
||||
|
||||
/// Like `Searcher`, but with `CatMap` to facilitate indexing heterogenous strings and paths -
|
||||
/// all presumed to resolve to Lua module content - by module names in `modules`.
|
||||
struct CatSearcher {
|
||||
modules: CatMap,
|
||||
globals: RegistryKey,
|
||||
}
|
||||
|
||||
impl CatSearcher {
|
||||
fn new(modules: CatMap, globals: RegistryKey) -> Self {
|
||||
Self { modules, globals }
|
||||
}
|
||||
}
|
||||
|
||||
impl UserData for CatSearcher {
|
||||
fn add_methods<'lua, M>(methods: &mut M)
|
||||
where
|
||||
M: UserDataMethods<'lua, Self>,
|
||||
{
|
||||
methods.add_meta_method(MetaMethod::Call, |lua_ctx, this, name: String| {
|
||||
let name = Cow::from(name);
|
||||
match this.modules.get(&name) {
|
||||
Some(content) => {
|
||||
let content = content
|
||||
.cat()
|
||||
.map_err(|e| rlua::Error::RuntimeError(format!("io error: {}", e)))?;
|
||||
Ok(Value::Function(
|
||||
lua_ctx
|
||||
.load(&content)
|
||||
.set_name(name.as_ref())?
|
||||
.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 Lua’s
|
||||
/// `package.searchers` table in an `rlua::Context`, with lookup functionality
|
||||
/// provided by the `rlua_searcher::Searcher` struct.
|
||||
/// Add a `HashMap` of Lua modules indexed by module name to Lua's `package.searchers`
|
||||
/// table in an `rlua::Context`, with lookup functionality provided by the
|
||||
/// `rlua_searcher::Searcher` struct.
|
||||
fn add_searcher(&self, modules: HashMap<Cow<'static, str>, Cow<'static, str>>) -> Result<()>;
|
||||
|
||||
/// Like `add_searcher`, but with `modules` values given as paths to files containing
|
||||
@@ -249,8 +288,8 @@ pub trait AddSearcher {
|
||||
where
|
||||
P: 'static + AsRef<Path> + Send;
|
||||
|
||||
/// Like `add_path_searcher`, but with user-provided closure for transforming
|
||||
/// source code to Lua.
|
||||
/// Like `add_path_searcher`, but with user-provided closure for transforming source
|
||||
/// code to Lua.
|
||||
fn add_path_searcher_poly<P>(
|
||||
&self,
|
||||
modules: HashMap<Cow<'static, str>, P>,
|
||||
@@ -279,6 +318,10 @@ pub trait AddSearcher {
|
||||
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
|
||||
>,
|
||||
) -> Result<()>;
|
||||
|
||||
/// Like `add_searcher`, except `modules` can contain heterogenous strings and paths
|
||||
/// indexed by module name.
|
||||
fn add_cat_searcher(&self, modules: CatMap) -> Result<()>;
|
||||
}
|
||||
|
||||
impl<'a> AddSearcher for Context<'a> {
|
||||
@@ -358,4 +401,14 @@ impl<'a> AddSearcher for Context<'a> {
|
||||
.set(searchers.len()? + 1, searcher)
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn add_cat_searcher(&self, modules: CatMap) -> Result<()> {
|
||||
let globals = self.globals();
|
||||
let searchers: Table = globals.get::<_, Table>("package")?.get("searchers")?;
|
||||
let registry_key = self.create_registry_value(globals)?;
|
||||
let searcher = CatSearcher::new(modules, registry_key);
|
||||
searchers
|
||||
.set(searchers.len()? + 1, searcher)
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
use std::borrow::Cow;
|
||||
use std::result;
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
pub type Result<A> = std::result::Result<A, Error>;
|
||||
pub(crate) type CatMap = crate::io_cat::CatMap<Cow<'static, str>>;
|
||||
pub type Result<A> = result::Result<A, Error>;
|
||||
|
||||
@@ -126,7 +126,7 @@ fn module_reloading_works() {
|
||||
|
||||
assert_eq!("hello lume", hello);
|
||||
|
||||
// Remove lume module from Lua’s `package.loaded` cache to facilitate reload.
|
||||
// Remove lume module from Lua's `package.loaded` cache to facilitate reload.
|
||||
lua.context::<_, rlua::Result<()>>(|lua_ctx| {
|
||||
let globals = lua_ctx.globals();
|
||||
let loaded: Table = globals.get::<_, Table>("package")?.get("loaded")?;
|
||||
@@ -330,3 +330,35 @@ fn cartridge_loader<'ctx>(
|
||||
.set_environment(env)?
|
||||
.into_function()?)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_cat_searcher_works() {
|
||||
let name = Cow::from("lume".to_string());
|
||||
let path = PathBuf::new()
|
||||
.join(std::env::var("CARGO_MANIFEST_DIR").unwrap())
|
||||
.join("tests")
|
||||
.join("data")
|
||||
.join("lume.lua");
|
||||
let mut map: CatMap<Cow<'static, str>> = CatMap::new();
|
||||
map.insert(name, Box::new(path));
|
||||
map.insert(Cow::from("loon"), Box::new(r#"return "hello loon""#));
|
||||
|
||||
let lua = Lua::new();
|
||||
|
||||
let hello = lua
|
||||
.context::<_, Result<String>>(|lua_ctx| {
|
||||
lua_ctx.add_cat_searcher(map)?;
|
||||
Ok(lua_ctx.load(r#"return require("lume")"#).eval()?)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!("hello lume", hello);
|
||||
|
||||
let hello = lua
|
||||
.context::<_, Result<String>>(|lua_ctx| {
|
||||
Ok(lua_ctx.load(r#"return require("loon")"#).eval()?)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!("hello loon", hello);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user