feat!: use an Error userdata instead of a plain error code for I/O errors (#1939)

This commit is contained in:
三咲雅 · Misaki Masa 2024-11-23 18:30:17 +08:00 committed by GitHub
parent 99d6c81fbb
commit 805597268a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 102 additions and 78 deletions

View file

@ -9,7 +9,7 @@ function M:peek()
return ya.preview_widgets(self, {
ui.Text(
code == 2 and "File list in this archive is encrypted"
or "Starting both `7z` and `7zz` failed. Do you have 7-zip installed?"
or "Failed to start both `7z` and `7zz`. Do you have 7-zip installed?"
):area(self.area),
})
end
@ -46,12 +46,12 @@ end
function M:seek(units) require("code").seek(self, units) end
function M.spawn_7z(args)
local last_error = nil
local last_err = nil
local try = function(name)
local stdout = args[1] == "l" and Command.PIPED or Command.NULL
local child, code = Command(name):args(args):stdout(stdout):stderr(Command.PIPED):spawn()
local child, err = Command(name):args(args):stdout(stdout):stderr(Command.PIPED):spawn()
if not child then
last_error = code
last_err = err
end
return child
end
@ -64,9 +64,9 @@ function M.spawn_7z(args)
end
if not child then
return ya.err("Starting both `7z` and `7zz` failed, error code: " .. tostring(last_error))
return ya.err("Failed to start both `7z` and `7zz`, error: " .. last_err)
end
return child, last_error
return child, last_err
end
---List files in an archive

View file

@ -48,9 +48,9 @@ function M:try_with(from, pwd, to)
end
local archive = require("archive")
local child, code = archive.spawn_7z { "x", "-aou", "-sccUTF-8", "-p" .. pwd, "-o" .. tostring(tmp), tostring(from) }
local child, err = archive.spawn_7z { "x", "-aou", "-sccUTF-8", "-p" .. pwd, "-o" .. tostring(tmp), tostring(from) }
if not child then
fail("Starting both `7z` and `7zz` failed, error code %s. Do you have 7-zip installed?", code)
fail("Failed to start both `7z` and `7zz`, error: " .. err)
end
local output, err = child:wait_with_output()
@ -61,7 +61,7 @@ function M:try_with(from, pwd, to)
self:tidy(from, to, tmp)
if not output then
fail("7zip failed to output when extracting '%s', error code %s", err, from)
fail("7zip failed to output when extracting '%s', error: %s", from, err)
elseif output.status.code ~= 0 then
fail("7zip exited when extracting '%s', error code %s", from, output.status.code)
end

View file

@ -2,13 +2,13 @@ local M = {}
function M:peek()
local cmd = os.getenv("YAZI_FILE_ONE") or "file"
local output, code = Command(cmd):args({ "-bL", "--", tostring(self.file.url) }):stdout(Command.PIPED):output()
local output, err = Command(cmd):args({ "-bL", "--", tostring(self.file.url) }):stdout(Command.PIPED):output()
local text
if output then
text = ui.Text.parse("----- File Type Classification -----\n\n" .. output.stdout)
else
text = ui.Text(string.format("Starting `%s` failed with error code %s. Do you have file(1) installed?", cmd, code))
text = ui.Text(string.format("Failed to start `%s`, error: %s", cmd, err))
end
ya.preview_widgets(self, { text:area(self.area):wrap(ui.Text.WRAP) })

View file

@ -21,7 +21,7 @@ function M:preload()
return 1
end
local child, code = Command("magick"):args({
local child, err = Command("magick"):args({
"-size",
"800x560",
"-gravity",
@ -40,7 +40,7 @@ function M:preload()
}):spawn()
if not child then
ya.err(string.format("Starting `magick` failed with error code %s", code))
ya.err("Failed to start `magick`, error: " .. err)
return 0
end

View file

@ -10,12 +10,12 @@ local function entry()
Command("fzf"):cwd(cwd):stdin(Command.INHERIT):stdout(Command.PIPED):stderr(Command.INHERIT):spawn()
if not child then
return fail("Starting `fzf` failed with error code %s. Do you have it installed?", err)
return fail("Failed to start `fzf`, error: " .. err)
end
local output, err = child:wait_with_output()
if not output then
return fail("Cannot read `fzf` output, error code %s", err)
return fail("Cannot read `fzf` output, error: " .. err)
elseif not output.status.success and output.status.code ~= 130 then
return fail("`fzf` exited with error code %s", output.status.code)
end

View file

@ -19,7 +19,7 @@ function M:preload()
return 1
end
local child, code = Command("magick"):args({
local child, err = Command("magick"):args({
"-density",
"200",
tostring(self.file.url),
@ -33,7 +33,7 @@ function M:preload()
}):spawn()
if not child then
ya.err(string.format("Starting `magick` failed with error code %s", code))
ya.err("Failed to start `magick`, error: " .. err)
return 0
end

View file

@ -16,9 +16,9 @@ function M:fetch(job)
end
local cmd = os.getenv("YAZI_FILE_ONE") or "file"
local child, code = Command(cmd):args({ "-bL", "--mime-type", "--" }):args(urls):stdout(Command.PIPED):spawn()
local child, err = Command(cmd):args({ "-bL", "--mime-type", "--" }):args(urls):stdout(Command.PIPED):spawn()
if not child then
ya.err(string.format("Starting `%s` failed with error code %s", cmd, code))
ya.err(string.format("Failed to start `%s`, error: %s", cmd, err))
return 0
end

View file

@ -49,7 +49,7 @@ function M:preload()
local ss = math.floor(meta.format.duration * percent / 100)
local qv = 31 - math.floor(PREVIEW.image_quality * 0.3)
-- stylua: ignore
local child, code = Command("ffmpeg"):args({
local child, err = Command("ffmpeg"):args({
"-v", "quiet", "-hwaccel", "auto",
"-skip_frame", "nokey", "-ss", ss,
"-an", "-sn", "-dn",
@ -62,7 +62,7 @@ function M:preload()
}):spawn()
if not child then
ya.err("Starting `ffmpeg` failed with error code " .. tostring(code))
ya.err("Failed to start `ffmpeg`, error: " .. err)
return 0
end
@ -116,14 +116,14 @@ function M.list_meta(url, entries)
local output, err =
Command("ffprobe"):args({ "-v", "quiet", "-show_entries", entries, "-of", "json=c=1", tostring(url) }):output()
if not output then
return nil, Err("Spawn `ffprobe` process returns %s", err)
return nil, Err("Failed to start `ffprobe`, error: " .. err)
end
local t = ya.json_decode(output.stdout)
if not t then
return nil, Err("Failed to decode `ffprobe` output: %s", output.stdout)
return nil, Err("Failed to decode `ffprobe` output: " .. output.stdout)
elseif type(t) ~= "table" then
return nil, Err("Invalid `ffprobe` output: %s", output.stdout)
return nil, Err("Invalid `ffprobe` output: " .. output.stdout)
end
t.format = t.format or {}

View file

@ -101,12 +101,12 @@ local function entry()
:spawn()
if not child then
return fail("Starting `zoxide` failed with error code %s. Do you have it installed?", err)
return fail("Failed to start `zoxide`, error: " .. err)
end
local output, err = child:wait_with_output()
if not output then
return fail("Cannot read `zoxide` output, error code %s", err)
return fail("Cannot read `zoxide` output, error: " .. err)
elseif not output.status.success and output.status.code ~= 130 then
return fail("`zoxide` exited with error code %s", output.status.code)
end

View file

@ -1,4 +1,4 @@
use mlua::{IntoLua, Lua, LuaSerdeExt, SerializeOptions, Table, Value};
use mlua::{IntoLua, Lua, LuaSerdeExt, MetaMethod, SerializeOptions, Table, Value};
use yazi_boot::BOOT;
use yazi_config::{MANAGER, PREVIEW, THEME};
@ -50,7 +50,7 @@ impl<'a> Config<'a> {
})?;
let fetcher = self.lua.create_table()?;
fetcher.set_metatable(Some(self.lua.create_table_from([("__index", index)])?));
fetcher.set_metatable(Some(self.lua.create_table_from([(MetaMethod::Index.name(), index)])?));
self.lua.globals().raw_set("PLUGIN", fetcher)?;
Ok(self)

View file

@ -1,4 +1,4 @@
use mlua::{AnyUserData, IntoLua, Lua, Table, Value};
use mlua::{AnyUserData, IntoLua, Lua, MetaMethod, Table, Value};
use tracing::error;
use super::Renderable;
@ -34,7 +34,7 @@ pub fn compose(lua: &Lua) -> mlua::Result<Table> {
})?;
let ui = lua.create_table_with_capacity(0, 20)?;
ui.set_metatable(Some(lua.create_table_from([("__index", index)])?));
ui.set_metatable(Some(lua.create_table_from([(MetaMethod::Index.name(), index)])?));
Ok(ui)
}

View file

@ -1,6 +1,6 @@
use std::time::Duration;
use mlua::{FromLua, Lua, MultiValue, Table, Value};
use mlua::{FromLua, Lua, MetaMethod, MultiValue, Table, Value};
use super::Rect;
use crate::RtRef;
@ -34,7 +34,7 @@ impl Paragraph {
pub fn compose(lua: &Lua) -> mlua::Result<Table> {
let mt = lua.create_table_from([
(
"__call",
MetaMethod::Call.name(),
lua.create_function(|lua, (_, area, lines): (Table, Rect, Value)| {
warn_deprecated(lua.named_registry_value::<RtRef>("rt")?.current());
lua
@ -45,7 +45,7 @@ impl Paragraph {
})?,
),
(
"__index",
MetaMethod::Index.name(),
lua.create_function(|lua, (_, key): (Table, mlua::String)| {
warn_deprecated(lua.named_registry_value::<RtRef>("rt")?.current());
lua

View file

@ -1,6 +1,9 @@
use mlua::{Lua, MetaMethod, UserData, UserDataMethods};
use std::borrow::Cow;
use mlua::{ExternalError, Lua, MetaMethod, UserData, UserDataFields, UserDataMethods, Value};
pub enum Error {
Io(std::io::Error),
Serde(serde_json::Error),
Custom(String),
}
@ -11,15 +14,42 @@ impl Error {
lua.globals().raw_set("Error", lua.create_table_from([("custom", new)])?)
}
fn to_string(&self) -> Cow<str> {
match self {
Error::Io(e) => Cow::Owned(e.to_string()),
Error::Serde(e) => Cow::Owned(e.to_string()),
Error::Custom(s) => Cow::Borrowed(s),
}
}
}
impl UserData for Error {
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_meta_method(MetaMethod::ToString, |_, me, ()| {
fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
fields.add_field_method_get("code", |_, me| {
Ok(match me {
Error::Serde(e) => e.to_string(),
Error::Custom(s) => s.clone(),
Error::Io(e) => e.raw_os_error(),
_ => None,
})
});
}
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_meta_method(MetaMethod::ToString, |lua, me, ()| {
lua.create_string(me.to_string().as_ref())
});
methods.add_meta_function(MetaMethod::Concat, |lua, (lhs, rhs): (Value, Value)| {
match (lhs, rhs) {
(Value::String(l), Value::UserData(r)) => {
let r = r.borrow::<Self>()?;
lua.create_string([l.as_bytes().as_ref(), r.to_string().as_bytes()].concat())
}
(Value::UserData(l), Value::String(r)) => {
let l = l.borrow::<Self>()?;
lua.create_string([l.to_string().as_bytes(), r.as_bytes().as_ref()].concat())
}
_ => Err("only string can be concatenated with Error".into_lua_err()),
}
});
}
}

View file

@ -1,9 +1,9 @@
use globset::GlobBuilder;
use mlua::{ExternalError, ExternalResult, Function, IntoLua, IntoLuaMulti, Lua, Table, Value};
use mlua::{ExternalError, ExternalResult, Function, IntoLua, IntoLuaMulti, Lua, MetaMethod, Table, Value};
use tokio::fs;
use yazi_shared::fs::remove_dir_clean;
use crate::{bindings::{Cast, Cha}, file::File, url::{Url, UrlRef}};
use crate::{Error, bindings::{Cast, Cha}, file::File, url::{Url, UrlRef}};
pub fn compose(lua: &Lua) -> mlua::Result<Table> {
let index = lua.create_function(|lua, (ts, key): (Table, mlua::String)| {
@ -22,7 +22,7 @@ pub fn compose(lua: &Lua) -> mlua::Result<Table> {
})?;
let fs = lua.create_table_with_capacity(0, 10)?;
fs.set_metatable(Some(lua.create_table_from([("__index", index)])?));
fs.set_metatable(Some(lua.create_table_from([(MetaMethod::Index.name(), index)])?));
Ok(fs)
}
@ -37,7 +37,7 @@ fn cha(lua: &Lua) -> mlua::Result<Function> {
match meta {
Ok(m) => (Cha::from(m), Value::Nil).into_lua_multi(&lua),
Err(e) => (Value::Nil, e.raw_os_error()).into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
}
})
}
@ -46,24 +46,24 @@ fn write(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (url, data): (UrlRef, mlua::String)| async move {
match fs::write(&*url, data.as_bytes()).await {
Ok(_) => (true, Value::Nil).into_lua_multi(&lua),
Err(e) => (false, e.raw_os_error()).into_lua_multi(&lua),
Err(e) => (false, Error::Io(e)).into_lua_multi(&lua),
}
})
}
fn remove(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (type_, url): (mlua::String, UrlRef)| async move {
let result = match &*type_.to_str()? {
"file" => fs::remove_file(&*url).await,
"dir" => fs::remove_dir(&*url).await,
"dir_all" => fs::remove_dir_all(&*url).await,
"dir_clean" => Ok(remove_dir_clean(&url).await),
let result = match type_.as_bytes().as_ref() {
b"file" => fs::remove_file(&*url).await,
b"dir" => fs::remove_dir(&*url).await,
b"dir_all" => fs::remove_dir_all(&*url).await,
b"dir_clean" => Ok(remove_dir_clean(&url).await),
_ => Err("Removal type must be 'file', 'dir', 'dir_all', or 'dir_clean'".into_lua_err())?,
};
match result {
Ok(_) => (true, Value::Nil).into_lua_multi(&lua),
Err(e) => (false, e.raw_os_error()).into_lua_multi(&lua),
Err(e) => (false, Error::Io(e)).into_lua_multi(&lua),
}
})
}
@ -90,7 +90,7 @@ fn read_dir(lua: &Lua) -> mlua::Result<Function> {
let mut it = match fs::read_dir(&*dir).await {
Ok(it) => it,
Err(e) => return (Value::Nil, e.raw_os_error()).into_lua_multi(&lua),
Err(e) => return (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
};
let mut files = vec![];
@ -128,7 +128,7 @@ fn unique_name(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, url: UrlRef| async move {
match yazi_shared::fs::unique_name(url.clone(), async { false }).await {
Ok(u) => (Url::cast(&lua, u)?, Value::Nil).into_lua_multi(&lua),
Err(e) => (Value::Nil, e.raw_os_error()).into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
}
})
}

View file

@ -1,6 +1,6 @@
use std::sync::Arc;
use mlua::{ExternalResult, Function, IntoLua, Lua, MultiValue, ObjectLike, Table, Value};
use mlua::{ExternalResult, Function, IntoLua, Lua, MetaMethod, MultiValue, ObjectLike, Table, Value};
use super::LOADER;
use crate::RtRef;
@ -44,7 +44,7 @@ impl Require {
let id: Arc<str> = Arc::from(id);
let mt = lua.create_table_from([
(
"__index",
MetaMethod::Index.name(),
lua.create_function(move |lua, (ts, key): (Table, mlua::String)| {
match ts.raw_get::<Table>("__mod")?.raw_get::<Value>(&key)? {
Value::Function(_) => {
@ -55,7 +55,7 @@ impl Require {
})?,
),
(
"__newindex",
MetaMethod::NewIndex.name(),
lua.create_function(move |_, (ts, key, value): (Table, mlua::String, Value)| {
ts.raw_get::<Table>("__mod")?.raw_set(key, value)
})?,

View file

@ -5,7 +5,7 @@ use mlua::{AnyUserData, ExternalError, IntoLua, IntoLuaMulti, Table, UserData, V
use tokio::{io::{self, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, BufWriter}, process::{ChildStderr, ChildStdin, ChildStdout}, select};
use super::Status;
use crate::process::Output;
use crate::{Error, process::Output};
pub struct Child {
inner: tokio::process::Child,
@ -83,7 +83,7 @@ impl UserData for Child {
};
match stdin.write_all(&src.as_bytes()).await {
Ok(()) => (true, Value::Nil).into_lua_multi(&lua),
Err(e) => (false, e.raw_os_error()).into_lua_multi(&lua),
Err(e) => (false, Error::Io(e)).into_lua_multi(&lua),
}
});
methods.add_async_method_mut("flush", |lua, mut me, ()| async move {
@ -92,7 +92,7 @@ impl UserData for Child {
};
match stdin.flush().await {
Ok(()) => (true, Value::Nil).into_lua_multi(&lua),
Err(e) => (false, e.raw_os_error()).into_lua_multi(&lua),
Err(e) => (false, Error::Io(e)).into_lua_multi(&lua),
}
});
@ -100,7 +100,7 @@ impl UserData for Child {
drop(me.stdin.take());
match me.inner.wait().await {
Ok(status) => (Status::new(status), Value::Nil).into_lua_multi(&lua),
Err(e) => (Value::Nil, e.raw_os_error()).into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
}
});
methods.add_async_function("wait_with_output", |lua, ud: AnyUserData| async move {
@ -129,12 +129,12 @@ impl UserData for Child {
(Output::new(std::process::Output { status, stdout, stderr }), Value::Nil)
.into_lua_multi(&lua)
}
Err(e) => (Value::Nil, e.raw_os_error()).into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
}
});
methods.add_method_mut("start_kill", |lua, me, ()| match me.inner.start_kill() {
Ok(_) => (true, Value::Nil).into_lua_multi(lua),
Err(e) => (false, e.raw_os_error()).into_lua_multi(lua),
Err(e) => (false, Error::Io(e)).into_lua_multi(lua),
});
methods.add_method_mut("take_stdin", |lua, me, ()| match me.stdin.take() {

View file

@ -4,7 +4,7 @@ use mlua::{AnyUserData, ExternalError, IntoLuaMulti, Lua, Table, UserData, Value
use tokio::process::{ChildStderr, ChildStdin, ChildStdout};
use super::{Child, output::Output};
use crate::process::Status;
use crate::{Error, process::Status};
pub struct Command {
inner: tokio::process::Command,
@ -103,18 +103,18 @@ impl UserData for Command {
});
methods.add_method_mut("spawn", |lua, me, ()| match me.inner.spawn() {
Ok(child) => (Child::new(child), Value::Nil).into_lua_multi(lua),
Err(e) => (Value::Nil, e.raw_os_error()).into_lua_multi(lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(lua),
});
methods.add_async_method_mut("output", |lua, mut me, ()| async move {
match me.inner.output().await {
Ok(output) => (Output::new(output), Value::Nil).into_lua_multi(&lua),
Err(e) => (Value::Nil, e.raw_os_error()).into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
}
});
methods.add_async_method_mut("status", |lua, mut me, ()| async move {
match me.inner.status().await {
Ok(status) => (Status::new(status), Value::Nil).into_lua_multi(&lua),
Err(e) => (Value::Nil, e.raw_os_error()).into_lua_multi(&lua),
Err(e) => (Value::Nil, Error::Io(e)).into_lua_multi(&lua),
}
});
}

View file

@ -1,6 +1,6 @@
#![allow(clippy::module_inception)]
use mlua::{IntoLua, Lua, Table, Value};
use mlua::{IntoLua, Lua, MetaMethod, Table, Value};
yazi_macro::mod_flat!(pubsub);
@ -22,7 +22,7 @@ pub(super) fn compose(lua: &Lua) -> mlua::Result<Table> {
})?;
let ps = lua.create_table_with_capacity(0, 10)?;
ps.set_metatable(Some(lua.create_table_from([("__index", index)])?));
ps.set_metatable(Some(lua.create_table_from([(MetaMethod::Index.name(), index)])?));
Ok(ps)
}

View file

@ -62,14 +62,8 @@ impl Url {
reg.add_meta_method(MetaMethod::ToString, |lua, me, ()| {
lua.create_string(me.as_os_str().as_encoded_bytes())
});
reg.add_meta_method(MetaMethod::Concat, |lua, me, other: mlua::String| {
let me = me.as_os_str().as_encoded_bytes();
let other = other.as_bytes();
let mut out = Vec::with_capacity(me.len() + other.len());
out.extend_from_slice(me);
out.extend_from_slice(&other);
lua.create_string(out)
reg.add_meta_method(MetaMethod::Concat, |lua, lhs, rhs: mlua::String| {
lua.create_string([lhs.as_os_str().as_encoded_bytes(), rhs.as_bytes().as_ref()].concat())
});
})
}

View file

@ -1,4 +1,4 @@
use mlua::{IntoLua, Lua, Table, Value};
use mlua::{IntoLua, Lua, MetaMethod, Table, Value};
pub(super) struct Utils;
@ -83,7 +83,7 @@ pub fn compose(lua: &Lua, isolate: bool) -> mlua::Result<Table> {
})?;
let ya = lua.create_table_with_capacity(0, 40)?;
ya.set_metatable(Some(lua.create_table_from([("__index", index)])?));
ya.set_metatable(Some(lua.create_table_from([(MetaMethod::Index.name(), index)])?));
Ok(ya)
}

View file

@ -18,7 +18,7 @@ pub async fn maybe_exists(p: impl AsRef<Path>) -> bool {
#[inline]
pub async fn must_be_dir(p: impl AsRef<Path>) -> bool {
fs::metadata(p).await.map_or(false, |m| m.is_dir())
fs::metadata(p).await.is_ok_and(|m| m.is_dir())
}
#[inline]

View file

@ -16,7 +16,7 @@ impl Urn {
#[cfg(unix)]
#[inline]
pub fn is_hidden(&self) -> bool {
self.name().map_or(false, |s| s.as_encoded_bytes().starts_with(b"."))
self.name().is_some_and(|s| s.as_encoded_bytes().starts_with(b"."))
}
}