Compare commits

..

16 Commits

Author SHA1 Message Date
2585e7ce34 Merge pull request 'Configure Renovate' (#1) from renovate/configure into master
Reviewed-on: https://git.front.kjuulh.io/kjuulh/rlua-searcher/pulls/1
2024-04-06 20:07:01 +00:00
158f4c7cb3 Add renovate.json 2023-08-02 10:59:51 +00:00
9073e924c6 feat: with publisable
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-08-02 12:48:38 +02:00
22672c76b0 docs: update readme
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-08-02 12:47:36 +02:00
ae42899727 feat: with iocat
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-08-02 12:45:56 +02:00
2b29a9d0e8 feat: update to rlua 19.5
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-07-02 11:29:04 +02:00
Andy Weidenbaum
c2c257e116 update license year to 2023 2023-01-01 06:27:05 +11:00
Andy Weidenbaum
38e3838a7c update io-cat dependency 2022-08-04 14:36:15 +10:00
atweiden
4d6d2a1697 lint 2022-06-27 13:47:33 +10:00
atweiden
f05e0966cb add CatSearcher 2022-06-27 13:38:18 +10:00
atweiden
c252048e2f impl From<Error> for rlua::Error 2022-06-23 10:42:35 +10:00
Andy Weidenbaum
357f2b6fdd format comments 2022-01-24 14:24:33 +11:00
Andy Weidenbaum
dd252db5c8 update rlua to 0.18 2022-01-22 21:28:10 +11:00
Andy Weidenbaum
57492ba18f specify rust 2021 edition 2022-01-22 20:53:53 +11:00
Andy Weidenbaum
3daf079207 s/’/' to be more tty friendly 2022-01-19 20:20:46 +11:00
Andy Weidenbaum
a2a801e69d 2022 2022-01-12 17:56:13 +11:00
10 changed files with 230 additions and 28 deletions

View File

@@ -1,14 +1,15 @@
[package] [package]
name = "rlua-searcher" name = "rlua-searcher"
version = "0.1.0" version = "0.1.0"
edition = "2018" edition = "2021"
authors = ["Andy Weidenbaum <atweiden@ioiojo.com>"] authors = ["Andy Weidenbaum <atweiden@ioiojo.com>", "Kasper J. Hermansen <contact@kjuulh.io>"]
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
keywords = ["lua"] keywords = ["lua"]
homepage = "https://git.sr.ht/~ioiojo/rlua-searcher" homepage = "https://git.front.kjuulh.io/kjuulh/rlua-searcher"
repository = "https://git.sr.ht/~ioiojo/rlua-searcher" repository = "https://git.front.kjuulh.io/kjuulh/rlua-searcher"
readme = "README.md" readme = "README.md"
description = "Require Lua modules by name" description = "Require Lua modules by name"
publishable = true
[dependencies] [dependencies]
rlua = "0.17" rlua = "0.19.5"

View File

@@ -1,6 +1,6 @@
The MIT License (MIT) 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 Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"), copy of this software and associated documentation files (the "Software"),

View File

@@ -2,6 +2,8 @@
`require` Lua modules by name `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 ## Description
Encode a Lua module as a `HashMap` of Lua strings indexed by module Encode a Lua module as a `HashMap` of Lua strings indexed by module

3
renovate.json Normal file
View File

@@ -0,0 +1,3 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json"
}

View File

@@ -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 { impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let res = match self { let res = match self {

100
src/io_cat.rs Normal file
View 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")
);
}
}

View File

@@ -1,4 +1,5 @@
mod error; mod error;
mod io_cat;
mod searcher; mod searcher;
mod types; mod types;

View File

@@ -5,7 +5,7 @@ use std::fs::File;
use std::io::Read; use std::io::Read;
use std::path::{Path, PathBuf}; 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 /// 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`. /// enable `require`ing the stored modules by name in an `rlua::Context`.
@@ -118,18 +118,18 @@ where
/// `rlua::Context` with Rust code. /// `rlua::Context` with Rust code.
/// ///
/// Enables exposing `UserData` types to an `rlua::Context`. /// Enables exposing `UserData` types to an `rlua::Context`.
pub struct ClosureSearcher { struct ClosureSearcher {
/// Closures must accept three parameters: /// Closures must accept three parameters:
/// ///
/// 1. An `rlua::Context`, which the closure can do what it wants with. /// 1. An `rlua::Context`, which the closure can do what it wants with.
/// ///
/// 2. An `rlua::Table` containing globals (i.e. Luas `_G`), which can be passed /// 2. An `rlua::Table` containing globals (i.e. Lua's `_G`), which can be passed to
/// to `Chunk.set_environment()`. /// `Chunk.set_environment()`.
/// ///
/// 3. The name of the module to be loaded (`&str`). /// 3. The name of the module to be loaded (`&str`).
/// ///
/// Closures must return an `rlua::Result`-wrapped `Function`. This `Function` /// Closures must return an `rlua::Result`-wrapped `Function`. This `Function` acts as
/// acts as the module loader. /// the module loader.
modules: HashMap< modules: HashMap<
Cow<'static, str>, Cow<'static, str>,
Box< Box<
@@ -142,7 +142,7 @@ pub struct ClosureSearcher {
} }
impl ClosureSearcher { impl ClosureSearcher {
pub fn new( fn new(
modules: HashMap< modules: HashMap<
Cow<'static, str>, Cow<'static, str>,
Box< Box<
@@ -178,22 +178,22 @@ impl UserData for ClosureSearcher {
} }
} }
/// Like `Searcher`, but with function pointers as `modules` values, to facilitate /// Like `Searcher`, but with function pointers as `modules` values, to facilitate setting
/// setting up an `rlua::Context` with Rust code. /// up an `rlua::Context` with Rust code.
/// ///
/// Enables exposing `UserData` types to an `rlua::Context`. /// Enables exposing `UserData` types to an `rlua::Context`.
pub struct FunctionSearcher { struct FunctionSearcher {
/// Functions must accept three parameters: /// Functions must accept three parameters:
/// ///
/// 1. An `rlua::Context`, which the function body can do what it wants with. /// 1. An `rlua::Context`, which the function body can do what it wants with.
/// ///
/// 2. An `rlua::Table` containing globals (i.e. Luas `_G`), which can be passed /// 2. An `rlua::Table` containing globals (i.e. Lua's `_G`), which can be passed to
/// to `Chunk.set_environment()`. /// `Chunk.set_environment()`.
/// ///
/// 3. The name of the module to be loaded (`&str`). /// 3. The name of the module to be loaded (`&str`).
/// ///
/// Functions must return an `rlua::Result`-wrapped `Function`. This `Function` /// Functions must return an `rlua::Result`-wrapped `Function`. This `Function` acts
/// acts as the module loader. /// as the module loader.
modules: HashMap< modules: HashMap<
Cow<'static, str>, Cow<'static, str>,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>, for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
@@ -203,7 +203,7 @@ pub struct FunctionSearcher {
} }
impl FunctionSearcher { impl FunctionSearcher {
pub fn new( fn new(
modules: HashMap< modules: HashMap<
Cow<'static, str>, Cow<'static, str>,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>, 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. /// Extend `rlua::Context` to support `require`ing Lua modules by name.
pub trait AddSearcher { pub trait AddSearcher {
/// Add a `HashMap` of Lua modules indexed by module name to Luas /// Add a `HashMap` of Lua modules indexed by module name to Lua's `package.searchers`
/// `package.searchers` table in an `rlua::Context`, with lookup functionality /// table in an `rlua::Context`, with lookup functionality provided by the
/// provided by the `rlua_searcher::Searcher` struct. /// `rlua_searcher::Searcher` struct.
fn add_searcher(&self, modules: HashMap<Cow<'static, str>, Cow<'static, str>>) -> Result<()>; 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 /// Like `add_searcher`, but with `modules` values given as paths to files containing
@@ -249,8 +288,8 @@ pub trait AddSearcher {
where where
P: 'static + AsRef<Path> + Send; P: 'static + AsRef<Path> + Send;
/// Like `add_path_searcher`, but with user-provided closure for transforming /// Like `add_path_searcher`, but with user-provided closure for transforming source
/// source code to Lua. /// code to Lua.
fn add_path_searcher_poly<P>( fn add_path_searcher_poly<P>(
&self, &self,
modules: HashMap<Cow<'static, str>, P>, 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>>, for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
>, >,
) -> Result<()>; ) -> 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> { impl<'a> AddSearcher for Context<'a> {
@@ -358,4 +401,14 @@ impl<'a> AddSearcher for Context<'a> {
.set(searchers.len()? + 1, searcher) .set(searchers.len()? + 1, searcher)
.map_err(|e| e.into()) .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())
}
} }

View File

@@ -1,3 +1,7 @@
use std::borrow::Cow;
use std::result;
use crate::error::Error; 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>;

View File

@@ -126,7 +126,7 @@ fn module_reloading_works() {
assert_eq!("hello lume", hello); assert_eq!("hello lume", hello);
// Remove lume module from Luas `package.loaded` cache to facilitate reload. // Remove lume module from Lua's `package.loaded` cache to facilitate reload.
lua.context::<_, rlua::Result<()>>(|lua_ctx| { lua.context::<_, rlua::Result<()>>(|lua_ctx| {
let globals = lua_ctx.globals(); let globals = lua_ctx.globals();
let loaded: Table = globals.get::<_, Table>("package")?.get("loaded")?; let loaded: Table = globals.get::<_, Table>("package")?.get("loaded")?;
@@ -330,3 +330,35 @@ fn cartridge_loader<'ctx>(
.set_environment(env)? .set_environment(env)?
.into_function()?) .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);
}