├── .devcontainer └── devcontainer.json ├── .github └── workflows │ └── check.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE.txt ├── LICENSE-MIT.txt ├── README.md ├── build.rs ├── docs └── highlight.html ├── examples ├── hello.rs ├── hello.txt ├── sandbox.rs └── sandbox │ └── hello.txt ├── src ├── dir.rs ├── file.rs ├── lib.rs └── path.rs └── tests ├── dir.rs ├── file.rs ├── fixtures ├── bar │ └── foo.txt └── oof.txt └── path.rs /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "image": "mcr.microsoft.com/devcontainers/universal:2", 3 | "features": { 4 | "ghcr.io/devcontainers/features/rust:1": {} 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.github/workflows/check.yml: -------------------------------------------------------------------------------- 1 | name: Check 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | clippy: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v3 17 | - uses: dtolnay/rust-toolchain@master 18 | with: 19 | toolchain: stable 20 | components: clippy 21 | - uses: actions-rs/clippy-check@v1 22 | with: 23 | token: ${{ secrets.GITHUB_TOKEN }} 24 | args: --features metadata 25 | tests: 26 | runs-on: ${{ matrix.os }} 27 | strategy: 28 | matrix: 29 | os: [ubuntu-latest, windows-latest] 30 | steps: 31 | - uses: actions/checkout@v3 32 | - name: Build 33 | run: cargo build --verbose --features metadata 34 | - name: Run tests 35 | run: cargo test --verbose --features metadata 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | /.vscode -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rhai-fs" 3 | version = "0.1.3" 4 | edition = "2021" 5 | authors = ["Dan Killinger "] 6 | repository = "https://github.com/rhaiscript/rhai-fs" 7 | readme = "README.md" 8 | license = "MIT OR Apache-2.0" 9 | description = "Filesystem package for Rhai" 10 | keywords = ["scripting", "scripting-language", "embedded", "rhai", "filesystem"] 11 | categories = ["embedded"] 12 | 13 | [features] 14 | default = [] 15 | metadata = ["rhai/metadata"] # doc generation 16 | sync = ["rhai/sync"] # support `sync` builds of Rhai 17 | no_index = [] # support `no_index` builds of Rhai 18 | 19 | [dependencies] 20 | rhai = { version = ">=1.9" } 21 | 22 | [dev-dependencies] 23 | tempfile = "3" 24 | 25 | [build-dependencies] 26 | rhai = { version = ">=1.11" } 27 | serde_json = "1.0.82" 28 | serde = "1.0.140" 29 | 30 | # NOTE: Need to manually specify `metadata` feature for local `cargo doc`. 31 | [package.metadata.docs.rs] 32 | features = ["metadata"] 33 | -------------------------------------------------------------------------------- /LICENSE-APACHE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /LICENSE-MIT.txt: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # About `rhai-fs` 2 | 3 | [![License](https://img.shields.io/crates/l/rhai-fs)](https://github.com/license/rhaiscript/rhai-fs) 4 | [![crates.io](https://img.shields.io/crates/v/rhai-fs?logo=rust)](https://crates.io/crates/rhai-fs/) 5 | [![crates.io](https://img.shields.io/crates/d/rhai-fs?logo=rust)](https://crates.io/crates/rhai-fs/) 6 | [![API Docs](https://docs.rs/rhai-fs/badge.svg?logo=docs-rs)](https://docs.rs/rhai-fs/) 7 | 8 | This crate provides filesystem access for the [Rhai] scripting language. 9 | 10 | ## Usage 11 | 12 | ### `Cargo.toml` 13 | 14 | ```toml 15 | [dependencies] 16 | rhai-fs = "0.1.2" 17 | ``` 18 | 19 | ### [Rhai] script 20 | 21 | ```js 22 | // Create a file or open and truncate if file is already created 23 | let file = open_file("example.txt"); 24 | let blob_buf = file.read_blob(); 25 | print("file contents: " + blob_buf); 26 | blob_buf.write_utf8(0..=0x20, "foobar"); 27 | print("new file contents: " + blob_buf); 28 | file.write(blob_buf); 29 | ``` 30 | 31 | ### Rust source 32 | 33 | ```rust 34 | use rhai::{Engine, EvalAltResult}; 35 | use rhai::packages::Package; 36 | use rhai_fs::FilesystemPackage; 37 | 38 | fn main() -> Result<(), Box> { 39 | // Create Rhai scripting engine 40 | let mut engine = Engine::new(); 41 | 42 | // Create filesystem package and add the package into the engine 43 | let package = FilesystemPackage::new(); 44 | package.register_into_engine(&mut engine); 45 | 46 | // Print the contents of the file `Cargo.toml`. 47 | let contents = engine.eval::(r#"open_file("Cargo.toml", "r").read_string()"#)?; 48 | println!("{}", contents); 49 | 50 | Ok(()) 51 | } 52 | ``` 53 | 54 | ## Features 55 | 56 | | Feature | Default | Description | 57 | | :--------: | :------: | ---------------------------------------------------- | 58 | | `no_index` | disabled | Enables support for `no_index` builds of [Rhai] | 59 | | `sync` | disabled | Enables support for `sync` builds of [Rhai] | 60 | | `metadata` | disabled | Enables support for generating package documentation | 61 | 62 | [Rhai]: https://rhai.rs 63 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | // Adapted from https://github.com/rhaiscript/rhai-sci 2 | 3 | use std::fs::File; 4 | 5 | #[allow(unused)] 6 | fn main() { 7 | // Update if needed 8 | println!("cargo:rerun-if-changed=src"); 9 | println!("cargo:rerun-if-changed=build.rs"); 10 | 11 | // Make empty file for documentation 12 | let doc_file_path = std::env::var("OUT_DIR").unwrap() + "/rhai-fs-docs.md"; 13 | let mut doc_file = File::create(doc_file_path).expect("create doc file"); 14 | 15 | #[cfg(feature = "metadata")] 16 | doc_gen::generate_doc(&mut doc_file); 17 | } 18 | 19 | #[cfg(feature = "metadata")] 20 | mod doc_gen { 21 | use rhai::{plugin::*, Engine}; 22 | use serde::{Deserialize, Serialize}; 23 | use std::collections::HashMap; 24 | use std::io::Write; 25 | 26 | // Rhai modules in the `rhai-fs` package. 27 | mod pkg { 28 | include!("src/path.rs"); 29 | include!("src/file.rs"); 30 | include!("src/dir.rs"); 31 | } 32 | 33 | #[derive(Serialize, Deserialize, Debug, Clone)] 34 | struct Metadata { 35 | #[serde(default)] 36 | pub functions: Vec, 37 | } 38 | 39 | #[derive(Serialize, Deserialize, Debug, Clone)] 40 | #[allow(non_snake_case)] 41 | struct DocFunc { 42 | pub access: String, 43 | pub baseHash: u128, 44 | pub fullHash: u128, 45 | pub name: String, 46 | pub namespace: String, 47 | pub numParams: usize, 48 | pub params: Option>>, 49 | pub signature: String, 50 | pub returnType: Option, 51 | pub docComments: Option>, 52 | } 53 | 54 | impl DocFunc { 55 | pub fn fmt_signature(&self) -> String { 56 | self.signature 57 | .replace(" -> Result<", " -> ") 58 | .replace(", Box>", "") 59 | .replace("&mut ", "") 60 | .replace(" -> ()", "") 61 | .replace("ImmutableString", "String") 62 | } 63 | 64 | pub fn fmt_doc_comments(&self) -> Option { 65 | self.docComments.clone().map(|dc| { 66 | dc.join("\n") 67 | .replace("/// ", "") 68 | .replace("///", "") 69 | .replace("/**", "") 70 | .replace("**/", "") 71 | .replace("**/", "") 72 | }) 73 | } 74 | 75 | // pub fn fmt_operator_fn(&self) -> Option { 76 | // Some( 77 | // self.name 78 | // .chars() 79 | // .map_while(|c| match c { 80 | // '+' => Some("add"), 81 | // '*' => Some("multiply"), 82 | // '-' => Some("subtract"), 83 | // '/' => Some("divide"), 84 | // '%' => Some("remainder"), 85 | // '=' => Some("equal"), 86 | // '!' => Some("not"), 87 | // '>' => Some("greater"), 88 | // '<' => Some("less"), 89 | // '|' => Some("bitor"), 90 | // '^' => Some("bitxor"), 91 | // _ => None, 92 | // }) 93 | // .collect::(), 94 | // ) 95 | // .filter(|s| !s.is_empty()) 96 | // } 97 | } 98 | 99 | fn fmt_fn_name(mut name: &str, mut signature: String) -> (&str, &str, String) { 100 | let mut prefix = ""; 101 | 102 | if name.starts_with("get$") { 103 | signature.drain(0..4); 104 | name = &name[4..]; 105 | prefix = "property get "; 106 | } 107 | if name.starts_with("set$") { 108 | signature.drain(0..4); 109 | name = &name[4..]; 110 | prefix = "property set "; 111 | } 112 | if name == "index$get" { 113 | signature.drain(0..6); 114 | name = "get"; 115 | prefix = "indexer "; 116 | } 117 | if name == "index$set" { 118 | signature.drain(0..6); 119 | name = "set"; 120 | prefix = "indexer "; 121 | } 122 | 123 | (prefix, name, signature) 124 | } 125 | 126 | pub fn generate_doc(writer: &mut impl Write) { 127 | let mut engine = Engine::new(); 128 | let mut fs_module = Module::new(); 129 | combine_with_exported_module!(&mut fs_module, "rhai_fs_path", pkg::path_functions); 130 | combine_with_exported_module!(&mut fs_module, "rhai_file_path", pkg::file_functions); 131 | combine_with_exported_module!(&mut fs_module, "rhai_dir_path", pkg::dir_functions); 132 | engine.register_global_module(fs_module.into()); 133 | 134 | // Extract metadata 135 | let json_fns = engine.gen_fn_metadata_to_json(false).unwrap(); 136 | let v: Metadata = serde_json::from_str(&json_fns).unwrap(); 137 | let function_list = v.functions; 138 | 139 | // Write functions 140 | let mut indented = false; 141 | for (idx, function) in function_list.iter().enumerate() { 142 | // Pull out basic info 143 | let name: &str = &function.name; 144 | if !name.starts_with("anon$") { 145 | let signature = function.fmt_signature(); 146 | let comments = function.fmt_doc_comments().unwrap_or_default(); 147 | 148 | let (prefix, name, signature) = fmt_fn_name(name, signature); 149 | 150 | // Check if there are multiple arities, and if so add a header and indent 151 | if idx < function_list.len() - 1 { 152 | if name == function_list[idx + 1].name && !indented { 153 | writeln!(writer, "## {prefix}`{}`", name.to_owned()) 154 | .expect("Cannot write to {doc_file}"); 155 | indented = true; 156 | } 157 | } 158 | 159 | // Print definition with right level of indentation 160 | if indented { 161 | writeln!(writer, "### {prefix}`{signature}`\n\n{comments}") 162 | .expect("Cannot write to {doc_file}"); 163 | } else { 164 | writeln!(writer, "## {prefix}`{signature}`\n{comments}") 165 | .expect("Cannot write to {doc_file}"); 166 | } 167 | 168 | // End indentation when its time 169 | if idx != 0 && idx < function_list.len() - 1 { 170 | if name == function_list[idx - 1].name && name != function_list[idx + 1].name { 171 | indented = false; 172 | } 173 | } 174 | } 175 | } 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /docs/highlight.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /examples/hello.rs: -------------------------------------------------------------------------------- 1 | //! A simple example that prints the contents of a file. 2 | 3 | use std::path::Path; 4 | 5 | use rhai::{packages::Package, Engine, EvalAltResult}; 6 | use rhai_fs::FilesystemPackage; 7 | 8 | fn main() -> Result<(), Box> { 9 | let mut engine = Engine::new(); 10 | 11 | // Register our filesystem package. 12 | let package = FilesystemPackage::new(); 13 | package.register_into_engine_as(&mut engine, "fs"); 14 | 15 | std::env::set_current_dir(Path::new(env!("CARGO_MANIFEST_DIR")).join("examples")).unwrap(); 16 | 17 | engine.run( 18 | r#" 19 | let file = fs::open_file("hello.txt"); 20 | print(file.read_string())"#, 21 | )?; 22 | 23 | Ok(()) 24 | } 25 | -------------------------------------------------------------------------------- /examples/hello.txt: -------------------------------------------------------------------------------- 1 | hello, world! -------------------------------------------------------------------------------- /examples/sandbox.rs: -------------------------------------------------------------------------------- 1 | //! A sandboxed filesystem example. 2 | 3 | use std::path::{Path, PathBuf}; 4 | 5 | use rhai::{packages::Package, Engine, EvalAltResult}; 6 | use rhai_fs::FilesystemPackage; 7 | 8 | fn main() -> Result<(), Box> { 9 | let mut engine = Engine::new(); 10 | 11 | // Register our filesystem package. 12 | let package = FilesystemPackage::new(); 13 | package.register_into_engine(&mut engine); 14 | 15 | std::env::set_current_dir(Path::new(env!("CARGO_MANIFEST_DIR")).join("examples")).unwrap(); 16 | 17 | engine.register_fn("path", sandboxed_path); 18 | 19 | engine.run( 20 | r#" 21 | let abs_file = open_file(path("F:\\source\\rhai-fs\\examples\\sandbox\\hello.txt")); 22 | print("absolute: " + abs_file.read_string()); 23 | let rel_file = open_file(path("hello.txt")); 24 | print("relative: " + rel_file.read_string());"#, 25 | )?; 26 | 27 | Ok(()) 28 | } 29 | 30 | fn sandboxed_path(str_path: &str) -> Result> { 31 | let root_path = PathBuf::from("sandbox").canonicalize().unwrap(); 32 | let mut path = PathBuf::from(str_path); 33 | 34 | if path.is_relative() { 35 | path = root_path.join(path); 36 | } 37 | 38 | match path.canonicalize() { 39 | Ok(p) => p.starts_with(root_path).then(|| path), 40 | Err(e) => return Err(e.to_string().into()), 41 | } 42 | .ok_or_else(|| "Path out of bounds".into()) 43 | } 44 | -------------------------------------------------------------------------------- /examples/sandbox/hello.txt: -------------------------------------------------------------------------------- 1 | hello, sandbox! -------------------------------------------------------------------------------- /src/dir.rs: -------------------------------------------------------------------------------- 1 | #[allow(unused_imports)] 2 | use rhai::plugin::*; 3 | 4 | #[export_module] 5 | pub mod dir_functions { 6 | use std::path::PathBuf; 7 | 8 | /// Recursively create a directory and all of its parent components if they are missing. 9 | #[rhai_fn(return_raw)] 10 | pub fn create_dir(path: PathBuf) -> Result<(), Box> { 11 | std::fs::create_dir_all(path).map_err(|e| e.to_string().into()) 12 | } 13 | 14 | /// Helper function for `create_dir` that takes a string instead of `PathBuf`. 15 | #[rhai_fn(return_raw, name = "create_dir")] 16 | pub fn create_dir_str( 17 | ctx: NativeCallContext, 18 | path_raw: ImmutableString, 19 | ) -> Result<(), Box> { 20 | let path = ctx.call_native_fn::("path", (path_raw,))?; 21 | create_dir(path) 22 | } 23 | 24 | /// Removes an empty directory. 25 | /// 26 | /// Throws an exception when: 27 | /// - The provided path doesn't exist. 28 | /// - The provided path isn't a directory. 29 | /// - The process lacks permissions to remove the directory. 30 | /// - The directory isn't empty. 31 | #[rhai_fn(return_raw)] 32 | pub fn remove_dir(path: PathBuf) -> Result<(), Box> { 33 | std::fs::remove_dir(path).map_err(|e| e.to_string().into()) 34 | } 35 | 36 | /// Helper function for `remove_dir` that takes a string instead of `PathBuf`. 37 | #[rhai_fn(return_raw, name = "remove_dir")] 38 | pub fn remove_dir_str( 39 | ctx: NativeCallContext, 40 | path_raw: ImmutableString, 41 | ) -> Result<(), Box> { 42 | let path = ctx.call_native_fn::("path", (path_raw,))?; 43 | remove_dir(path) 44 | } 45 | 46 | /// Returns an array of paths in the directory. 47 | /// 48 | /// Throws an exception when: 49 | /// - The provided path doesn't exist. 50 | /// - The provided path isn't a directory. 51 | /// - The process lacks permissions to view the contents. 52 | #[rhai_fn(return_raw)] 53 | pub fn open_dir(path: PathBuf) -> Result> { 54 | match std::fs::read_dir(path) { 55 | Ok(read_dir) => Ok(read_dir 56 | .filter_map(|e| e.ok()) 57 | .map(|e| Dynamic::from(e.path())) 58 | .collect()), 59 | Err(e) => Err(format!("{}", &e).into()), 60 | } 61 | } 62 | 63 | /// Helper function for `open_dir` that takes a string instead of `PathBuf`. 64 | #[rhai_fn(return_raw, name = "open_dir")] 65 | pub fn open_dir_str( 66 | ctx: NativeCallContext, 67 | path_raw: ImmutableString, 68 | ) -> Result> { 69 | let path = ctx.call_native_fn::("path", (path_raw,))?; 70 | open_dir(path) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/file.rs: -------------------------------------------------------------------------------- 1 | #[allow(unused_imports)] 2 | use rhai::plugin::*; 3 | use rhai::{Locked, Shared}; 4 | 5 | use std::fs::{File, OpenOptions}; 6 | use std::io::prelude::*; 7 | use std::ops::DerefMut; 8 | use std::path::PathBuf; 9 | 10 | fn convert_to_int(val: impl TryInto) -> Result> { 11 | val.try_into() 12 | .map_err(|_| "Error converting number {new_pos} to rhai number type".into()) 13 | } 14 | 15 | #[inline(always)] 16 | fn borrow_mut(file: &Shared>) -> impl DerefMut + '_ { 17 | #[cfg(not(feature = "sync"))] 18 | return file.borrow_mut(); 19 | 20 | #[cfg(feature = "sync")] 21 | return file.write().unwrap(); 22 | } 23 | 24 | #[export_module] 25 | pub mod file_functions { 26 | pub type SharedFile = Shared>; 27 | 28 | /// Creates or opens a file for reading and writing. 29 | #[rhai_fn(return_raw)] 30 | pub fn open_file(path: PathBuf) -> Result> { 31 | open_file_with_opts(path, "w+") 32 | } 33 | 34 | /// Helper function for `open_file(path)` that takes a string instead of `PathBuf`. 35 | #[rhai_fn(return_raw, name = "open_file")] 36 | pub fn open_file_str( 37 | ctx: NativeCallContext, 38 | path_raw: ImmutableString, 39 | ) -> Result> { 40 | let path = ctx.call_native_fn::("path", (path_raw,))?; 41 | open_file(path) 42 | } 43 | 44 | /// Available options for opening a file. 45 | /// 46 | /// | Flag | Access | Creation | 47 | /// | :--: | ------------- | :------: | 48 | /// | r | Read only | No | 49 | /// | r+ | Read & write | No | 50 | /// | w | Write only | Yes | 51 | /// | wx | Write only | Required | 52 | /// | w+ | Read & write | Yes | 53 | /// | a | Append only | Yes | 54 | /// | ax | Append only | Required | 55 | /// | a+ | Read & append | Yes | 56 | /// | ax+ | Read & append | Required | 57 | /// 58 | #[rhai_fn(return_raw, name = "open_file")] 59 | pub fn open_file_with_opts( 60 | path: PathBuf, 61 | options: &str, 62 | ) -> Result> { 63 | let mut opts = OpenOptions::new(); 64 | let final_opts = match options { 65 | "r" => opts.read(true), 66 | "r+" => opts.read(true).write(true), 67 | "w" => opts.write(true).create(true), 68 | "wx" => opts.write(true).create_new(true), 69 | "w+" => opts.read(true).write(true).create(true), 70 | "a" => opts.append(true).create(true), 71 | "ax" => opts.append(true).create_new(true), 72 | "a+" => opts.read(true).append(true).create(true), 73 | "ax+" => opts.read(true).append(true).create_new(true), 74 | _ => &mut opts, 75 | }; 76 | match final_opts.open(path) { 77 | Ok(file) => Ok(Shared::new(Locked::new(file))), 78 | Err(e) => Err(format!("{}", &e).into()), 79 | } 80 | } 81 | 82 | /// Helper function for `open_file(path, options)` that takes a string instead of `PathBuf`. 83 | #[rhai_fn(return_raw, name = "open_file")] 84 | pub fn open_file_with_opts_str( 85 | ctx: NativeCallContext, 86 | path_raw: ImmutableString, 87 | options: &str, 88 | ) -> Result> { 89 | let path = ctx.call_native_fn::("path", (path_raw,))?; 90 | open_file_with_opts(path, options) 91 | } 92 | 93 | /// Remove a file at the given path. 94 | /// 95 | /// Throws an exception when: 96 | /// - The path points to a directory. 97 | /// - The file doesn't exist. 98 | /// - The user lacks permissions to remove the file. 99 | #[rhai_fn(return_raw)] 100 | pub fn remove_file(path: PathBuf) -> Result<(), Box> { 101 | std::fs::remove_file(path).map_err(|e| e.to_string().into()) 102 | } 103 | 104 | /// Helper function for `remove_file` that takes a string instead of `PathBuf`. 105 | #[rhai_fn(return_raw)] 106 | pub fn remove_file_str( 107 | ctx: NativeCallContext, 108 | path_raw: ImmutableString, 109 | ) -> Result<(), Box> { 110 | let path = ctx.call_native_fn::("path", (path_raw,))?; 111 | std::fs::remove_file(path).map_err(|e| e.to_string().into()) 112 | } 113 | 114 | /// Reads from the current stream position until EOF and returns it as a string, respects the engine's `max_string_size`. 115 | /// 116 | /// Throws an exception when: 117 | /// - The read function encounters an I/O error. 118 | #[rhai_fn(global, pure, return_raw, name = "read_string")] 119 | pub fn read_to_string( 120 | ctx: NativeCallContext, 121 | file: &mut SharedFile, 122 | ) -> Result> { 123 | read_to_string_with_len(ctx, file, 0) 124 | } 125 | 126 | /// Reads from the current stream position up to the passed `len` and returns it as a string, respects the engine's `max_string_size`. 127 | /// 128 | /// Throws an exception when: 129 | /// - The read function encounters an I/O error. 130 | #[rhai_fn(global, pure, return_raw, name = "read_string")] 131 | pub fn read_to_string_with_len( 132 | ctx: NativeCallContext, 133 | file: &mut SharedFile, 134 | len: rhai::INT, 135 | ) -> Result> { 136 | let mut buf: Vec = Vec::new(); 137 | 138 | let max_len = ctx.engine().max_string_size(); 139 | let res = match max_len { 140 | 0 if len == 0 => borrow_mut(file).read_to_end(&mut buf), 141 | 0 if len > 0 => { 142 | buf.resize(len as usize, 0); 143 | borrow_mut(file).read(&mut buf) 144 | } 145 | _ if len == 0 => { 146 | buf.resize(max_len, 0); 147 | borrow_mut(file).read(&mut buf) 148 | } 149 | _ => { 150 | buf.resize(max_len.min(len as usize), 0); 151 | borrow_mut(file).read(&mut buf) 152 | } 153 | }; 154 | 155 | match res { 156 | Ok(read_len) => { 157 | buf.truncate(read_len); 158 | String::from_utf8(buf).map_err(|e| e.to_string().into()) 159 | } 160 | Err(e) => Err(format!("{}", &e).into()), 161 | } 162 | } 163 | 164 | /// Writes the string into the file at the current stream position. 165 | /// 166 | /// Throws an exception when: 167 | /// - The write function encounters an I/O error. 168 | #[rhai_fn(global, pure, return_raw, name = "write")] 169 | pub fn write_with_string( 170 | file: &mut SharedFile, 171 | str: &str, 172 | ) -> Result> { 173 | match borrow_mut(file).write(str.as_bytes()) { 174 | Ok(len) => convert_to_int(len), 175 | Err(e) => Err(format!("{}", &e).into()), 176 | } 177 | } 178 | 179 | /// Sets the stream to the provided position, relative to the start of the file. 180 | /// 181 | /// Throws an exception when: 182 | /// - Seeking to a negative position. 183 | #[rhai_fn(global, pure, return_raw)] 184 | pub fn seek(file: &mut SharedFile, pos: rhai::INT) -> Result> { 185 | match borrow_mut(file).seek(std::io::SeekFrom::Start(pos as u64)) { 186 | Ok(new_pos) => convert_to_int(new_pos), 187 | Err(e) => Err(format!("{}", &e).into()), 188 | } 189 | } 190 | 191 | /// Returns the current stream position. 192 | #[rhai_fn(global, pure, return_raw)] 193 | pub fn position(file: &mut SharedFile) -> Result> { 194 | match borrow_mut(file).stream_position() { 195 | Ok(pos) => convert_to_int(pos), 196 | Err(e) => Err(format!("{}", &e).into()), 197 | } 198 | } 199 | 200 | /// Returns the size of the file, in bytes. 201 | #[rhai_fn(global, pure, return_raw)] 202 | pub fn bytes(file: &mut SharedFile) -> Result> { 203 | match borrow_mut(file).metadata() { 204 | Ok(md) => convert_to_int(md.len()), 205 | Err(e) => Err(format!("{}", &e).into()), 206 | } 207 | } 208 | 209 | #[cfg(not(feature = "no_index"))] 210 | pub mod blob_functions { 211 | use rhai::Blob; 212 | 213 | /// Reads from the current stream position until EOF and returns it as a `Blob`, respects the engine's `max_array_size`. 214 | #[rhai_fn(global, pure, return_raw, name = "read_blob")] 215 | pub fn read_to_blob( 216 | ctx: NativeCallContext, 217 | file: &mut SharedFile, 218 | ) -> Result> { 219 | read_to_blob_with_len(ctx, file, 0) 220 | } 221 | 222 | /// Reads from the current stream position up to the passed `len` and returns it as a `Blob`, respects the engine's `max_array_size`. 223 | #[rhai_fn(global, pure, return_raw, name = "read_blob")] 224 | pub fn read_to_blob_with_len( 225 | ctx: NativeCallContext, 226 | file: &mut SharedFile, 227 | len: rhai::INT, 228 | ) -> Result> { 229 | let mut buf: Vec = Vec::new(); 230 | 231 | let max_len = ctx.engine().max_array_size(); 232 | let res = match max_len { 233 | 0 if len == 0 => borrow_mut(file).read_to_end(&mut buf), 234 | 0 if len > 0 => { 235 | buf.resize(len as usize, 0); 236 | borrow_mut(file).read(&mut buf) 237 | } 238 | _ if len == 0 => { 239 | buf.resize(max_len, 0); 240 | borrow_mut(file).read(&mut buf) 241 | } 242 | _ => { 243 | buf.resize(max_len.min(len as usize), 0); 244 | borrow_mut(file).read(&mut buf) 245 | } 246 | }; 247 | 248 | match res { 249 | Ok(_) => Ok(buf), 250 | Err(e) => Err(format!("{}", &e).into()), 251 | } 252 | } 253 | 254 | /// Reads from the current stream position into the provided `Blob` with the read length being returned. 255 | #[rhai_fn(global, return_raw)] 256 | pub fn read_from_file( 257 | blob: &mut Blob, 258 | mut file: SharedFile, 259 | ) -> Result> { 260 | match borrow_mut(&mut file).read(blob) { 261 | Ok(len) => convert_to_int(len), 262 | Err(e) => Err(format!("{}", &e).into()), 263 | } 264 | } 265 | 266 | /// Writes the blob into the file at the current stream position. 267 | #[rhai_fn(global, pure, return_raw)] 268 | pub fn write_to_file( 269 | blob: &mut Blob, 270 | mut file: SharedFile, 271 | ) -> Result> { 272 | match borrow_mut(&mut file).write(blob) { 273 | Ok(len) => convert_to_int(len), 274 | Err(e) => Err(format!("{}", &e).into()), 275 | } 276 | } 277 | } 278 | } 279 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![warn(missing_docs)] 2 | #![warn(clippy::missing_docs_in_private_items)] 3 | #![deny(rustdoc::broken_intra_doc_links)] 4 | #![doc = include_str!("../README.md")] 5 | //! 6 | //! ## API 7 | //! 8 | //! The following functions are defined in this package: 9 | //! 10 | #![doc = include_str!(concat!(env!("OUT_DIR"), "/rhai-fs-docs.md"))] 11 | #![doc = include_str!("../docs/highlight.html")] 12 | 13 | use rhai::def_package; 14 | use rhai::plugin::*; 15 | 16 | pub(crate) mod dir; 17 | pub(crate) mod file; 18 | pub(crate) mod path; 19 | 20 | def_package! { 21 | /// Package for filesystem manipulation operations. 22 | pub FilesystemPackage(lib) { 23 | combine_with_exported_module!(lib, "rhai_fs_path", path::path_functions); 24 | combine_with_exported_module!(lib, "rhai_fs_file", file::file_functions); 25 | combine_with_exported_module!(lib, "rhai_fs_dir", dir::dir_functions); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/path.rs: -------------------------------------------------------------------------------- 1 | use rhai::plugin::*; 2 | 3 | #[export_module] 4 | #[allow(clippy::ptr_arg)] 5 | pub mod path_functions { 6 | use std::path::{Path, PathBuf}; 7 | 8 | /// Creates a path from the passed string. 9 | #[rhai_fn(global)] 10 | pub fn path(path: &str) -> PathBuf { 11 | PathBuf::from(path.to_string()) 12 | } 13 | 14 | /// Returns path to current working directory. 15 | /// 16 | /// Throws an exception when: 17 | /// - The current working directory does not exist. 18 | /// - The process lacks the permissions to access the current working directory. 19 | #[rhai_fn(return_raw)] 20 | pub fn cwd() -> Result> { 21 | std::env::current_dir().map_err(|e| e.to_string().into()) 22 | } 23 | 24 | /// Returns `true` if path points to something in the filesystem (a file or directory) so long as the current process can access it. 25 | #[rhai_fn(global, pure, get = "exists")] 26 | pub fn exists(path: &mut PathBuf) -> bool { 27 | path.exists() 28 | } 29 | 30 | /// Returns the canonical, absolute form of the path with all intermediate components normalized and symbolic links resolved. 31 | #[rhai_fn(global, pure, return_raw)] 32 | pub fn canonicalize(path: &mut PathBuf) -> Result> { 33 | path.canonicalize().map_err(|e| e.to_string().into()) 34 | } 35 | 36 | /// Returns true if the Path is absolute, i.e., if it is independent of the current directory. 37 | #[rhai_fn(global, pure, get = "is_absolute")] 38 | pub fn is_absolute(path: &mut PathBuf) -> bool { 39 | path.is_absolute() 40 | } 41 | 42 | /// Returns true if the path exists on disk and is pointing at a directory. 43 | #[rhai_fn(global, pure, get = "is_dir")] 44 | pub fn is_dir(path: &mut PathBuf) -> bool { 45 | path.is_dir() 46 | } 47 | 48 | /// Returns true if the path exists on disk and is pointing at a regular file. 49 | #[rhai_fn(global, pure, get = "is_file")] 50 | pub fn is_file(path: &mut PathBuf) -> bool { 51 | path.is_file() 52 | } 53 | 54 | /// Returns true if the Path is relative, i.e., not absolute. 55 | #[rhai_fn(global, pure, get = "is_relative")] 56 | pub fn is_relative(path: &mut PathBuf) -> bool { 57 | path.is_relative() 58 | } 59 | 60 | /// Returns true if the Path is relative, i.e., not absolute. 61 | #[rhai_fn(global, pure, get = "is_symlink")] 62 | pub fn is_symlink(path: &mut PathBuf) -> bool { 63 | path.is_symlink() 64 | } 65 | 66 | #[rhai_fn(global, name = "+", pure)] 67 | pub fn add(path1: &mut PathBuf, path2: PathBuf) -> PathBuf { 68 | path1.join(path2) 69 | } 70 | 71 | #[rhai_fn(global, name = "+", pure)] 72 | pub fn add_string(path: &mut PathBuf, str: &str) -> PathBuf { 73 | path.join(Path::new(str)) 74 | } 75 | 76 | #[rhai_fn(global, name = "+=", name = "append", name = "push")] 77 | pub fn append(path1: &mut PathBuf, path2: PathBuf) { 78 | path1.push(path2); 79 | } 80 | 81 | #[rhai_fn(global, name = "to_string", name = "to_debug", pure)] 82 | pub fn to_string(path: &mut PathBuf) -> String { 83 | path.to_str().unwrap_or_default().into() 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /tests/dir.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | 3 | use rhai::{packages::Package, Engine, EvalAltResult}; 4 | use rhai_fs::FilesystemPackage; 5 | 6 | #[test] 7 | fn test_dir() -> Result<(), Box> { 8 | let mut engine = Engine::new(); 9 | 10 | // Register our filesystem package. 11 | let package = FilesystemPackage::new(); 12 | package.register_into_engine(&mut engine); 13 | 14 | std::env::set_current_dir(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")) 15 | .unwrap(); 16 | 17 | // Retrieve number of paths from dir. 18 | assert_eq!(engine.eval::(r#"open_dir(cwd()).len"#)?, 2); 19 | 20 | Ok(()) 21 | } 22 | -------------------------------------------------------------------------------- /tests/file.rs: -------------------------------------------------------------------------------- 1 | use std::fs::File; 2 | use std::io::prelude::*; 3 | use std::io::SeekFrom; 4 | use std::ops::DerefMut; 5 | 6 | use rhai::{packages::Package, Engine, EvalAltResult, Locked, Scope, Shared}; 7 | use rhai_fs::FilesystemPackage; 8 | 9 | #[inline(always)] 10 | fn borrow_mut(file: &Shared>) -> impl DerefMut + '_ { 11 | #[cfg(not(feature = "sync"))] 12 | return file.borrow_mut(); 13 | 14 | #[cfg(feature = "sync")] 15 | return file.write().unwrap(); 16 | } 17 | 18 | #[test] 19 | fn test_reading_file() -> Result<(), Box> { 20 | let mut engine = Engine::new(); 21 | 22 | // Register our filesystem package. 23 | let package = FilesystemPackage::new(); 24 | package.register_into_engine(&mut engine); 25 | 26 | // Read a known good file. 27 | let mut scope = Scope::new(); 28 | 29 | let shared_file = Shared::new(Locked::new(tempfile::tempfile().unwrap())); 30 | let _ = borrow_mut(&shared_file).write(b"This is a test!").unwrap(); 31 | borrow_mut(&shared_file).seek(SeekFrom::Start(0)).unwrap(); 32 | scope.push_constant("FILE", shared_file); 33 | 34 | assert_eq!( 35 | engine.eval_with_scope::(&mut scope, r#"FILE.read_string()"#)?, 36 | "This is a test!" 37 | ); 38 | 39 | // Max string size is respected. 40 | assert_eq!( 41 | engine 42 | .set_max_string_size(4) 43 | .eval_with_scope::(&mut scope, r#"FILE.seek(0); FILE.read_string()"#)?, 44 | "This" 45 | ); 46 | 47 | // Lengths under max string size are respected. 48 | assert_eq!( 49 | engine 50 | .set_max_string_size(16) 51 | .eval_with_scope::(&mut scope, r#"FILE.seek(0); FILE.read_string().len"#)?, 52 | 15 53 | ); 54 | 55 | Ok(()) 56 | } 57 | 58 | #[test] 59 | fn test_writing_file() -> Result<(), Box> { 60 | let mut engine = Engine::new(); 61 | 62 | // Register our filesystem package. 63 | let package = FilesystemPackage::new(); 64 | package.register_into_engine(&mut engine); 65 | 66 | // Write to a known good file. 67 | let shared_file = Shared::new(Locked::new(tempfile::tempfile().unwrap())); 68 | let mut scope = Scope::new(); 69 | scope.push_constant("FILE", shared_file); 70 | 71 | assert_eq!( 72 | engine.eval_with_scope::(&mut scope, r#"FILE.write("This is a test!")"#)?, 73 | 15 74 | ); 75 | 76 | Ok(()) 77 | } 78 | 79 | #[test] 80 | fn test_seeking_file() -> Result<(), Box> { 81 | let mut engine = Engine::new(); 82 | 83 | // Register our filesystem package. 84 | let package = FilesystemPackage::new(); 85 | package.register_into_engine(&mut engine); 86 | 87 | // Seek off the start of a known good file. 88 | let shared_file = Shared::new(Locked::new(tempfile::tempfile().unwrap())); 89 | let _ = borrow_mut(&shared_file).write(b"0This is a test!").unwrap(); 90 | let mut scope = Scope::new(); 91 | scope.push_constant("FILE", shared_file); 92 | 93 | assert_eq!( 94 | engine.eval_with_scope::(&mut scope, r#"FILE.seek(1); FILE.read_string()"#)?, 95 | "This is a test!" 96 | ); 97 | 98 | Ok(()) 99 | } 100 | 101 | #[test] 102 | #[cfg(not(feature = "no_index"))] 103 | fn test_blob_file() -> Result<(), Box> { 104 | let mut engine = Engine::new(); 105 | 106 | // Register our filesystem package. 107 | let package = FilesystemPackage::new(); 108 | package.register_into_engine(&mut engine); 109 | 110 | // Read a known good file. 111 | let shared_file = Shared::new(Locked::new(tempfile::tempfile().unwrap())); 112 | let _ = borrow_mut(&shared_file) 113 | .write(&[1, 2, 3, 4, 5, 6, 7, 8, 9]) 114 | .unwrap(); 115 | borrow_mut(&shared_file).seek(SeekFrom::Start(0)).unwrap(); 116 | let mut scope = Scope::new(); 117 | scope.push_constant("FILE", shared_file); 118 | 119 | assert_eq!( 120 | engine.eval_with_scope::(&mut scope, r#"FILE.read_blob()"#)?, 121 | &[1, 2, 3, 4, 5, 6, 7, 8, 9] 122 | ); 123 | 124 | // Max array size is respected. 125 | assert_eq!( 126 | engine 127 | .set_max_array_size(4) 128 | .eval_with_scope::(&mut scope, r#"FILE.seek(0); FILE.read_blob()"#)?, 129 | &[1, 2, 3, 4] 130 | ); 131 | 132 | // Lengths under max string size are not respected. 133 | assert_eq!( 134 | engine 135 | .set_max_array_size(16) 136 | .eval_with_scope::(&mut scope, r#"FILE.seek(0); FILE.read_blob().len"#)?, 137 | 16 138 | ); 139 | 140 | // Blob from rhai to rust. 141 | assert_eq!( 142 | engine.eval_with_scope::( 143 | &mut scope, 144 | r#"FILE.seek(0); let x = blob(9); x.read_from_file(FILE); x"# 145 | )?, 146 | &[1, 2, 3, 4, 5, 6, 7, 8, 9] 147 | ); 148 | 149 | // Blob write to file. 150 | assert_eq!( 151 | engine.eval_with_scope::( 152 | &mut scope, 153 | r#"FILE.seek(0); let x = blob(8); x.write_utf8(0..8, "test"); x.write_to_file(FILE)"# 154 | )?, 155 | 8 156 | ); 157 | 158 | Ok(()) 159 | } 160 | -------------------------------------------------------------------------------- /tests/fixtures/bar/foo.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rhaiscript/rhai-fs/6b9bca22e4f184da072c5c205af42823e587f816/tests/fixtures/bar/foo.txt -------------------------------------------------------------------------------- /tests/fixtures/oof.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rhaiscript/rhai-fs/6b9bca22e4f184da072c5c205af42823e587f816/tests/fixtures/oof.txt -------------------------------------------------------------------------------- /tests/path.rs: -------------------------------------------------------------------------------- 1 | use std::env::current_dir; 2 | use std::path::{Path, PathBuf}; 3 | 4 | use rhai::{packages::Package, Engine, EvalAltResult, Scope}; 5 | use rhai_fs::FilesystemPackage; 6 | 7 | #[test] 8 | fn test_path() -> Result<(), Box> { 9 | let mut engine = Engine::new(); 10 | 11 | // Register our filesystem package. 12 | let package = FilesystemPackage::new(); 13 | package.register_into_engine(&mut engine); 14 | 15 | std::env::set_current_dir(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")) 16 | .unwrap(); 17 | 18 | // Add two paths. 19 | let path_one = PathBuf::from("bar"); 20 | let mut scope = Scope::new(); 21 | scope.push_constant("PATH_ONE", path_one); 22 | assert_eq!( 23 | engine.eval_with_scope::(&mut scope, r#"PATH_ONE + path("foo.txt")"#)?, 24 | PathBuf::from("bar/foo.txt") 25 | ); 26 | 27 | // Add string to path. 28 | let path_one = PathBuf::from("bar"); 29 | let mut scope = Scope::new(); 30 | scope.push_constant("PATH_ONE", path_one); 31 | assert_eq!( 32 | engine.eval_with_scope::(&mut scope, r#"PATH_ONE + "foo.txt""#)?, 33 | PathBuf::from("bar/foo.txt") 34 | ); 35 | 36 | // Canonicalize and add two paths. 37 | let path_one = PathBuf::from("bar/../bar"); 38 | let mut scope = Scope::new(); 39 | scope.push_constant("PATH_ONE", path_one); 40 | assert_eq!( 41 | engine.eval_with_scope::( 42 | &mut scope, 43 | r#"PATH_ONE.canonicalize() + path("foo.txt")"# 44 | )?, 45 | current_dir() 46 | .unwrap() 47 | .join("bar/foo.txt") 48 | .canonicalize() 49 | .unwrap() 50 | ); 51 | 52 | // Append a path. 53 | let path_one = PathBuf::from("bar"); 54 | let mut scope = Scope::new(); 55 | scope.push("PATH_ONE", path_one); 56 | assert_eq!( 57 | engine 58 | .eval_with_scope::(&mut scope, r#"PATH_ONE += path("foo.txt"); PATH_ONE"#)?, 59 | PathBuf::from("bar/foo.txt") 60 | ); 61 | 62 | // Append a path with a string. 63 | let path_one = PathBuf::from("bar"); 64 | let mut scope = Scope::new(); 65 | scope.push("PATH_ONE", path_one); 66 | assert_eq!( 67 | engine.eval_with_scope::(&mut scope, r#"PATH_ONE += "foo.txt"; PATH_ONE"#)?, 68 | PathBuf::from("bar/foo.txt") 69 | ); 70 | 71 | Ok(()) 72 | } 73 | --------------------------------------------------------------------------------