Skip to content

Commit

Permalink
hooks: more rhai fs functions
Browse files Browse the repository at this point in the history
  • Loading branch information
BrettMayson committed Nov 2, 2023
1 parent 960f55b commit e34a46c
Show file tree
Hide file tree
Showing 8 changed files with 120 additions and 8 deletions.
2 changes: 1 addition & 1 deletion bin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ glob = "0.3.1"
num_cpus = "1.16.0"
rayon = "1.8.0"
reqwest = { version = "0.11.22", features = ["blocking", "json"] }
rhai = "1.16.3"
rhai = { version = "1.16.3" }
rust-embed = "8.0.0"
semver = "1.0.20"
serde = { workspace = true, features = ["derive"] }
Expand Down
13 changes: 11 additions & 2 deletions bin/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,21 @@ pub enum Error {
Walkdir(#[from] walkdir::Error),
#[error("Zip Error: {0}")]
Zip(#[from] zip::result::ZipError),
#[error("Rhai Error: {0}")]
Rhai(#[from] rhai::ParseError),
#[error("Rhai Parse Error: {0}")]
RhaiParse(#[from] rhai::ParseError),
#[error("Rhai Script Error: {0}")]
/// because of annyoing send + sync I don't care about
RhaiScript(String),
}

impl From<vfs::VfsError> for Error {
fn from(e: vfs::VfsError) -> Self {
Self::Vfs(Box::new(e))
}
}

impl From<Box<rhai::EvalAltResult>> for Error {
fn from(e: Box<rhai::EvalAltResult>) -> Self {
Self::RhaiScript(e.to_string())
}
}
10 changes: 10 additions & 0 deletions bin/src/modules/hook/libraries/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::context::Context;
pub struct RhaiProject {
name: String,
prefix: String,
mainprefix: String,
version: Version,
// addons: Vec<Addon>,
}
Expand All @@ -20,6 +21,10 @@ impl RhaiProject {
Self {
name: ctx.config().name().to_string(),
prefix: ctx.config().prefix().to_string(),
mainprefix: ctx.config().mainprefix().map_or_else(
String::new,
std::string::ToString::to_string,
),
version: ctx.config().version().get(ctx.workspace().vfs()).unwrap(),
// addons: ctx.addons().to_vec(),
}
Expand All @@ -41,6 +46,11 @@ pub mod project_functions {
project.prefix.clone()
}

#[rhai_fn(global, pure)]
pub fn mainprefix(project: &mut RhaiProject) -> String {
project.mainprefix.clone()
}

#[rhai_fn(global, pure)]
pub fn version(project: &mut RhaiProject) -> Version {
project.version.clone()
Expand Down
28 changes: 26 additions & 2 deletions bin/src/modules/hook/libraries/rfs/path.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use rhai::plugin::{
export_module, mem, Dynamic, FnAccess, FnNamespace, ImmutableString, Module, NativeCallContext,
export_module, mem, FnAccess, FnNamespace, ImmutableString, Module, NativeCallContext,
PluginFunction, RhaiResult, TypeId,
};

Expand All @@ -9,6 +9,8 @@ use rhai::plugin::{
pub mod path_functions {
use std::path::PathBuf;

use rhai::Dynamic;

#[rhai_fn(global, pure)]
pub fn join(path: &mut PathBuf, other: &str) -> PathBuf {
path.join(other)
Expand All @@ -29,9 +31,19 @@ pub mod path_functions {
path.is_file()
}

#[rhai_fn(global, pure)]
pub fn parent(path: &mut PathBuf) -> PathBuf {
path.parent().unwrap().to_path_buf()
}

#[rhai_fn(global, pure)]
pub fn file_name(path: &mut PathBuf) -> String {
path.file_name().unwrap().to_str().unwrap().to_string()
}

#[rhai_fn(global, name = "to_string", name = "to_debug", pure)]
pub fn to_string(path: &mut PathBuf) -> String {
path.display().to_string()
path.display().to_string().replace('\\', "/")
}

#[rhai_fn(global, name = "copy", pure)]
Expand All @@ -51,4 +63,16 @@ pub mod path_functions {
std::fs::rename(path, other).is_ok()
}
}

#[rhai_fn(global, pure)]
pub fn list(path: &mut PathBuf) -> rhai::Array {
let mut list = Vec::new();
if path.is_dir() {
for entry in std::fs::read_dir(path).expect("can't read dir") {
let entry = entry.expect("entry failed");
list.push(Dynamic::from(entry.path()));
}
}
list
}
}
25 changes: 23 additions & 2 deletions bin/src/modules/hook/libraries/vfs/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use rhai::plugin::{
#[allow(clippy::needless_pass_by_ref_mut)]
#[export_module]
pub mod path_functions {
use rhai::EvalAltResult;
use rhai::{EvalAltResult, Array};
use vfs::VfsPath;

#[rhai_fn(global, pure, return_raw)]
Expand All @@ -29,9 +29,19 @@ pub mod path_functions {
path.is_file().map_err(|e| e.to_string().into())
}

#[rhai_fn(global, pure)]
pub fn parent(path: &mut VfsPath) -> VfsPath {
path.parent()
}

#[rhai_fn(global, pure)]
pub fn file_name(path: &mut VfsPath) -> String {
path.filename()
}

#[rhai_fn(global, name = "to_string", name = "to_debug", pure)]
pub fn to_string(path: &mut VfsPath) -> String {
path.as_str().to_string()
path.as_str().to_string().replace('\\', "/")
}

#[rhai_fn(global, return_raw)]
Expand Down Expand Up @@ -61,4 +71,15 @@ pub mod path_functions {
};
res.map_or_else(|| Ok(true), Err)
}

#[rhai_fn(global, pure, return_raw)]
pub fn list(path: &mut VfsPath) -> Result<Array, Box<EvalAltResult>> {
let mut list = Vec::new();
if path.is_dir().map_err(|e| e.to_string())? {
for entry in path.read_dir().unwrap() {
list.push(Dynamic::from(entry));
}
}
Ok(list)
}
}
2 changes: 1 addition & 1 deletion bin/src/modules/hook/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ impl Hooks {
error!("[{inner_name}] {s}");
*inner_told_to_fail.lock().unwrap() = true;
});
engine.run_with_scope(&mut scope, script).unwrap();
engine.run_with_scope(&mut scope, script)?;
if *told_to_fail.lock().unwrap() {
return Err(Error::HookFatal(name));
}
Expand Down
20 changes: 20 additions & 0 deletions bin/tests/bravo/.hemtt/hooks/post_release/03_dirs.rhai
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
let found = 0;
for child in HEMTT_RFS.list() {
print(child);
if (child.file_name().ends_with("docs")) {
found += 1;
}
if (child.file_name().ends_with("releases")) {
found += 1;
}
if (child.file_name().ends_with("addons")) {
found += 1;
}
if (child.file_name().ends_with("include.txt")) {
found += 1;
}
}

if (found != 4) {
fatal(":skull:");
}
28 changes: 28 additions & 0 deletions book/rhai/library/filesystem.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,26 @@ HEMTT_VFS.join("addons").is_file(); // false
HEMTT_VFS.join(".hemtt").join("project.toml").is_file(); // true
```

## `parent()`

Returns the parent directory of the path.
Will panic if the path is root while using the real file system.
Will return the root path while using the virtual file system, if already at the root.

```ts
HEMTT_VFS.join("addons").parent(); // Points to ./
HEMTT_VFS.join(".hemtt").join("project.toml").parent(); // Points to ./.hemtt
```

## `file_name()`

Returns the file name of the path.

```ts
HEMTT_VFS.join("addons").file_name(); // addons
HEMTT_VFS.join(".hemtt").join("project.toml").file_name(); // project.toml
```

## `copy(path)`

Copies the file or directory to the given path.
Expand All @@ -121,6 +141,14 @@ Moves the file or directory to the given path.
HEMTT_VFS.join("docs").move(HEMTT_OUT.join("docs")); // Moves the docs folder to the build output
```

## `list(path)`

Lists the contents of the directory. If the path is a file, returns an empty array.

```ts
HEMTT_VFS.join("docs").list(); // Returns an array of paths of files and directories in the docs folder
```

## `open_file()`

Opens the file for reading.
Expand Down

0 comments on commit e34a46c

Please sign in to comment.