Add tempdir support
This commit is contained in:
@@ -9,7 +9,7 @@ repository.workspace = true
|
||||
|
||||
[features]
|
||||
task = ["tokio/rt", "tokio/time"]
|
||||
fs = ["tokio/fs", "dep:walkdir", "dep:globset"]
|
||||
fs = ["tokio/fs", "dep:walkdir", "dep:globset", "dep:tempfile"]
|
||||
net = ["tokio/net"]
|
||||
|
||||
[dependencies]
|
||||
@@ -18,6 +18,7 @@ globset = { version = "0.4.16", optional = true }
|
||||
luaffi = { path = "../luaffi" }
|
||||
luajit = { path = "../luajit" }
|
||||
sysexits = "0.9.0"
|
||||
tempfile = { version = "3.20.0", optional = true }
|
||||
thiserror = "2.0.12"
|
||||
tokio = { version = "1.45.1" }
|
||||
walkdir = { version = "2.5.0", optional = true }
|
||||
|
||||
@@ -98,6 +98,14 @@ impl lb_fslib {
|
||||
prefix,
|
||||
})
|
||||
}
|
||||
|
||||
pub extern "Lua-C" fn temp_dir(&self) -> Result<lb_temp_dir> {
|
||||
Ok(tempfile::tempdir()?.into())
|
||||
}
|
||||
|
||||
pub extern "Lua-C" fn temp_dir_in(&self, path: &str) -> Result<lb_temp_dir> {
|
||||
Ok(tempfile::tempdir_in(path)?.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator over the entries in a directory.
|
||||
@@ -401,3 +409,20 @@ impl lb_glob_dir {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Directory in the filesystem that is automatically deleted when it is garbage-collected.
|
||||
#[derive(Debug, From)]
|
||||
#[cdef]
|
||||
pub struct lb_temp_dir(#[opaque] tempfile::TempDir);
|
||||
|
||||
#[metatype]
|
||||
impl lb_temp_dir {
|
||||
pub extern "Lua-C" fn path(&self) -> String {
|
||||
self.0.path().to_string_lossy().into()
|
||||
}
|
||||
|
||||
#[tostring]
|
||||
pub extern "Lua" fn tostring(&self) -> String {
|
||||
self.path()
|
||||
}
|
||||
}
|
||||
|
||||
17
crates/lb/tests/fs.lua
Normal file
17
crates/lb/tests/fs.lua
Normal file
@@ -0,0 +1,17 @@
|
||||
local ok, fs = pcall(require, "lb:fs")
|
||||
if not ok then return end
|
||||
|
||||
describe("temp files", function()
|
||||
test("temp_dir cleans itself", function()
|
||||
local path
|
||||
do
|
||||
local dir = fs:temp_dir()
|
||||
path = dir:path()
|
||||
assert(path and path ~= "")
|
||||
fs:write(path .. "/test.txt", "test file")
|
||||
assert(fs:read(path .. "/test.txt") == "test file")
|
||||
end
|
||||
collectgarbage()
|
||||
assert(not pcall(fs.read, fs, path .. "/test.txt"))
|
||||
end)
|
||||
end)
|
||||
Reference in New Issue
Block a user