feat: add YAZI_ID environment variable (#895)

This commit is contained in:
三咲雅 · Misaki Masa 2024-04-11 23:57:47 +08:00 committed by GitHub
parent 38813413ec
commit 23c38ebae0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 43 additions and 43 deletions

3
Cargo.lock generated
View file

@ -2747,6 +2747,7 @@ dependencies = [
"parking_lot", "parking_lot",
"ratatui", "ratatui",
"regex", "regex",
"scopeguard",
"serde", "serde",
"tokio", "tokio",
"tokio-stream", "tokio-stream",
@ -2793,6 +2794,7 @@ dependencies = [
"libc", "libc",
"mlua", "mlua",
"ratatui", "ratatui",
"scopeguard",
"signal-hook-tokio", "signal-hook-tokio",
"syntect", "syntect",
"tikv-jemallocator", "tikv-jemallocator",
@ -2874,6 +2876,7 @@ dependencies = [
"libc", "libc",
"parking_lot", "parking_lot",
"regex", "regex",
"scopeguard",
"tokio", "tokio",
"tokio-stream", "tokio-stream",
"tracing", "tracing",

View file

@ -1 +1 @@
{"version":"0.2","words":["Punct","KEYMAP","splitn","crossterm","YAZI","unar","peekable","ratatui","syntect","pbpaste","pbcopy","ffmpegthumbnailer","oneshot","Posix","Lsar","XADDOS","zoxide","cands","Deque","precache","imageops","IFBLK","IFCHR","IFDIR","IFIFO","IFLNK","IFMT","IFSOCK","IRGRP","IROTH","IRUSR","ISGID","ISUID","ISVTX","IWGRP","IWOTH","IWUSR","IXGRP","IXOTH","IXUSR","libc","winsize","TIOCGWINSZ","xpixel","ypixel","ioerr","appender","Catppuccin","macchiato","gitmodules","Dotfiles","bashprofile","vimrc","flac","webp","exiftool","mediainfo","ripgrep","nvim","indexmap","indexmap","unwatch","canonicalize","serde","fsevent","Ueberzug","iterm","wezterm","sixel","chafa","ueberzugpp"," Überzug"," Überzug","Konsole","Alacritty","Überzug","pkgs","paru","unarchiver","pdftoppm","poppler","prebuild","singlefile","jpegopt","EXIF","rustfmt","mktemp","nanos","xclip","xsel","natord","Mintty","nixos","nixpkgs","SIGTSTP","SIGCONT","SIGCONT","mlua","nonstatic","userdata","metatable","natsort","backstack","luajit","Succ","Succ","cand","fileencoding","foldmethod","lightgreen","darkgray","lightred","lightyellow","lightcyan","nushell","msvc","aarch","linemode","sxyazi","rsplit","ZELLIJ","bitflags","bitflags","USERPROFILE","Neovim","vergen","gitcl","Renderable","preloaders","prec","imagesize","Upserting","prio","Ghostty","Catmull","Lanczos","cmds","unyank","scrolloff","headsup","unsub","uzers"],"language":"en","flagWords":[]} {"language":"en","flagWords":[],"words":["Punct","KEYMAP","splitn","crossterm","YAZI","unar","peekable","ratatui","syntect","pbpaste","pbcopy","ffmpegthumbnailer","oneshot","Posix","Lsar","XADDOS","zoxide","cands","Deque","precache","imageops","IFBLK","IFCHR","IFDIR","IFIFO","IFLNK","IFMT","IFSOCK","IRGRP","IROTH","IRUSR","ISGID","ISUID","ISVTX","IWGRP","IWOTH","IWUSR","IXGRP","IXOTH","IXUSR","libc","winsize","TIOCGWINSZ","xpixel","ypixel","ioerr","appender","Catppuccin","macchiato","gitmodules","Dotfiles","bashprofile","vimrc","flac","webp","exiftool","mediainfo","ripgrep","nvim","indexmap","indexmap","unwatch","canonicalize","serde","fsevent","Ueberzug","iterm","wezterm","sixel","chafa","ueberzugpp"," Überzug"," Überzug","Konsole","Alacritty","Überzug","pkgs","paru","unarchiver","pdftoppm","poppler","prebuild","singlefile","jpegopt","EXIF","rustfmt","mktemp","nanos","xclip","xsel","natord","Mintty","nixos","nixpkgs","SIGTSTP","SIGCONT","SIGCONT","mlua","nonstatic","userdata","metatable","natsort","backstack","luajit","Succ","Succ","cand","fileencoding","foldmethod","lightgreen","darkgray","lightred","lightyellow","lightcyan","nushell","msvc","aarch","linemode","sxyazi","rsplit","ZELLIJ","bitflags","bitflags","USERPROFILE","Neovim","vergen","gitcl","Renderable","preloaders","prec","imagesize","Upserting","prio","Ghostty","Catmull","Lanczos","cmds","unyank","scrolloff","headsup","unsub","uzers","scopeguard","SPDLOG"],"version":"0.2"}

View file

@ -74,6 +74,7 @@ impl Ueberzug {
// TODO: demon // TODO: demon
let result = Command::new("ueberzugpp") let result = Command::new("ueberzugpp")
.args(["layer", "-so", &adaptor.to_string()]) .args(["layer", "-so", &adaptor.to_string()])
.env("SPDLOG_LEVEL", if cfg!(debug_assertions) { "debug" } else { "" })
.kill_on_drop(true) .kill_on_drop(true)
.stdin(Stdio::piped()) .stdin(Stdio::piped())
.stderr(Stdio::null()) .stderr(Stdio::null())

View file

@ -29,6 +29,7 @@ notify = { version = "6.1.1", default-features = false, features = [ "mac
parking_lot = "0.12.1" parking_lot = "0.12.1"
ratatui = "0.26.1" ratatui = "0.26.1"
regex = "1.10.4" regex = "1.10.4"
scopeguard = "1.2.0"
serde = "1.0.197" serde = "1.0.197"
tokio = { version = "1.37.0", features = [ "full" ] } tokio = { version = "1.37.0", features = [ "full" ] }
tokio-stream = "0.1.15" tokio-stream = "0.1.15"

View file

@ -1,10 +1,11 @@
use std::{borrow::Cow, collections::HashMap, ffi::{OsStr, OsString}, io::{stderr, BufWriter, Write}, path::PathBuf}; use std::{borrow::Cow, collections::HashMap, ffi::{OsStr, OsString}, io::{stderr, BufWriter, Write}, path::PathBuf};
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use scopeguard::defer;
use tokio::{fs::{self, OpenOptions}, io::{stdin, AsyncReadExt, AsyncWriteExt}}; use tokio::{fs::{self, OpenOptions}, io::{stdin, AsyncReadExt, AsyncWriteExt}};
use yazi_config::{OPEN, PREVIEW}; use yazi_config::{OPEN, PREVIEW};
use yazi_proxy::{AppProxy, TasksProxy, HIDER, WATCHER}; use yazi_proxy::{AppProxy, TasksProxy, HIDER, WATCHER};
use yazi_shared::{fs::{accessible, max_common_root, File, FilesOp, Url}, term::Term, Defer}; use yazi_shared::{fs::{accessible, max_common_root, File, FilesOp, Url}, term::Term};
use crate::manager::Manager; use crate::manager::Manager;
@ -31,12 +32,12 @@ impl Manager {
.write_all(s.as_encoded_bytes()) .write_all(s.as_encoded_bytes())
.await?; .await?;
let _defer1 = Defer::new(|| tokio::spawn(fs::remove_file(tmp.clone()))); defer! { tokio::spawn(fs::remove_file(tmp.clone())); }
TasksProxy::process_exec(vec![OsString::new(), tmp.to_owned().into()], Cow::Borrowed(opener)) TasksProxy::process_exec(vec![OsString::new(), tmp.to_owned().into()], Cow::Borrowed(opener))
.await; .await;
let _permit = HIDER.acquire().await.unwrap(); let _permit = HIDER.acquire().await.unwrap();
let _defer2 = Defer::new(AppProxy::resume); defer!(AppProxy::resume());
AppProxy::stop().await; AppProxy::stop().await;
let new: Vec<_> = fs::read_to_string(&tmp).await?.lines().map(PathBuf::from).collect(); let new: Vec<_> = fs::read_to_string(&tmp).await?.lines().map(PathBuf::from).collect();

View file

@ -1,9 +1,10 @@
use std::{io::{stderr, BufWriter, LineWriter, Write}, mem}; use std::{io::{stderr, BufWriter, LineWriter, Write}, mem};
use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use scopeguard::defer;
use tokio::{io::{stdin, AsyncReadExt}, select, sync::mpsc, time}; use tokio::{io::{stdin, AsyncReadExt}, select, sync::mpsc, time};
use yazi_proxy::{AppProxy, HIDER}; use yazi_proxy::{AppProxy, HIDER};
use yazi_shared::{event::Cmd, term::Term, Defer}; use yazi_shared::{event::Cmd, term::Term};
use crate::tasks::Tasks; use crate::tasks::Tasks;
@ -26,14 +27,13 @@ impl Tasks {
task.logs.clone() task.logs.clone()
}; };
defer!(AppProxy::resume());
AppProxy::stop().await; AppProxy::stop().await;
let _defer = Defer::new(|| {
disable_raw_mode().ok();
AppProxy::resume();
});
Term::clear(&mut stderr()).ok(); Term::clear(&mut stderr()).ok();
BufWriter::new(stderr().lock()).write_all(mem::take(&mut buffered).as_bytes()).ok(); BufWriter::new(stderr().lock()).write_all(mem::take(&mut buffered).as_bytes()).ok();
defer! { disable_raw_mode().ok(); }
enable_raw_mode().ok(); enable_raw_mode().ok();
let mut stdin = stdin(); let mut stdin = stdin();

View file

@ -40,7 +40,7 @@ impl<'a> Body<'a> {
pub fn from_lua(kind: &str, value: Value) -> Result<Self> { pub fn from_lua(kind: &str, value: Value) -> Result<Self> {
Ok(match kind { Ok(match kind {
"hi" | "hey" | "cd" | "hover" | "rename" | "bulk" | "yank" => { "hi" | "hey" | "cd" | "hover" | "rename" | "bulk" | "yank" | "move" | "trash" | "delete" => {
Err("Cannot construct system event from Lua").into_lua_err()? Err("Cannot construct system event from Lua").into_lua_err()?
} }
_ if !kind.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') => { _ if !kind.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') => {

View file

@ -27,10 +27,10 @@ impl<'a> From<BodyDelete<'a>> for Body<'a> {
impl IntoLua<'_> for BodyDelete<'static> { impl IntoLua<'_> for BodyDelete<'static> {
fn into_lua(self, lua: &Lua) -> mlua::Result<Value<'_>> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value<'_>> {
let t = lua.create_table_with_capacity(self.urls.len(), 0)?; let urls = lua.create_table_with_capacity(self.urls.len(), 0)?;
for (i, url) in self.urls.into_owned().into_iter().enumerate() { for (i, url) in self.urls.into_owned().into_iter().enumerate() {
t.raw_set(i + 1, lua.create_any_userdata(url)?)?; urls.raw_set(i + 1, lua.create_any_userdata(url)?)?;
} }
t.into_lua(lua) lua.create_table_from([("urls", urls)])?.into_lua(lua)
} }
} }

View file

@ -30,7 +30,9 @@ impl<'a> From<BodyMove<'a>> for Body<'a> {
} }
impl IntoLua<'_> for BodyMove<'static> { impl IntoLua<'_> for BodyMove<'static> {
fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { self.items.into_owned().into_lua(lua) } fn into_lua(self, lua: &Lua) -> mlua::Result<Value> {
lua.create_table_from([("items", self.items.into_owned())])?.into_lua(lua)
}
} }
// --- Item // --- Item

View file

@ -27,10 +27,10 @@ impl<'a> From<BodyTrash<'a>> for Body<'a> {
impl IntoLua<'_> for BodyTrash<'static> { impl IntoLua<'_> for BodyTrash<'static> {
fn into_lua(self, lua: &Lua) -> mlua::Result<Value<'_>> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value<'_>> {
let t = lua.create_table_with_capacity(self.urls.len(), 0)?; let urls = lua.create_table_with_capacity(self.urls.len(), 0)?;
for (i, url) in self.urls.into_owned().into_iter().enumerate() { for (i, url) in self.urls.into_owned().into_iter().enumerate() {
t.raw_set(i + 1, lua.create_any_userdata(url)?)?; urls.raw_set(i + 1, lua.create_any_userdata(url)?)?;
} }
t.into_lua(lua) lua.create_table_from([("urls", urls)])?.into_lua(lua)
} }
} }

View file

@ -32,6 +32,13 @@ pub fn serve() {
LOCAL.with(Default::default); LOCAL.with(Default::default);
REMOTE.with(Default::default); REMOTE.with(Default::default);
// Env
std::env::set_var("YAZI_ID", ID.to_string());
std::env::set_var(
"YAZI_LEVEL",
(std::env::var("YAZI_LEVEL").unwrap_or_default().parse().unwrap_or(0u16) + 1).to_string(),
);
Pump::serve(); Pump::serve();
Client::serve(rx); Client::serve(rx);
} }

View file

@ -27,6 +27,7 @@ fdlimit = "0.3.0"
futures = "0.3.30" futures = "0.3.30"
mlua = { version = "0.9.6", features = [ "lua54", "vendored" ] } mlua = { version = "0.9.6", features = [ "lua54", "vendored" ] }
ratatui = "0.26.1" ratatui = "0.26.1"
scopeguard = "1.2.0"
syntect = { version = "5.2.0", default-features = false, features = [ "parsing", "plist-load", "regex-onig" ] } syntect = { version = "5.2.0", default-features = false, features = [ "parsing", "plist-load", "regex-onig" ] }
tokio = { version = "1.37.0", features = [ "full" ] } tokio = { version = "1.37.0", features = [ "full" ] }
tokio-util = "0.7.10" tokio-util = "0.7.10"

View file

@ -1,9 +1,10 @@
use std::fmt::Display; use std::fmt::Display;
use mlua::TableExt; use mlua::TableExt;
use scopeguard::defer;
use tracing::warn; use tracing::warn;
use yazi_plugin::{loader::LOADER, OptData, RtRef, LUA}; use yazi_plugin::{loader::LOADER, OptData, RtRef, LUA};
use yazi_shared::{emit, event::Cmd, Defer, Layer}; use yazi_shared::{emit, event::Cmd, Layer};
use crate::{app::App, lives::Lives}; use crate::{app::App, lives::Lives};
@ -45,7 +46,7 @@ impl App {
Err(e) => return warn!("{e}"), Err(e) => return warn!("{e}"),
} }
let _defer = Defer::new(|| LUA.named_registry_value::<RtRef>("rt").map(|mut r| r.reset())); defer! { LUA.named_registry_value::<RtRef>("rt").map(|mut r| r.reset()).ok(); };
let plugin = match LOADER.load(&opt.name) { let plugin = match LOADER.load(&opt.name) {
Ok(plugin) => plugin, Ok(plugin) => plugin,
Err(e) => return warn!("{e}"), Err(e) => return warn!("{e}"),

View file

@ -1,10 +1,11 @@
use std::{mem, sync::Arc}; use std::{mem, sync::Arc};
use mlua::{Scope, Table}; use mlua::{Scope, Table};
use scopeguard::defer;
use tracing::error; use tracing::error;
use yazi_config::LAYOUT; use yazi_config::LAYOUT;
use yazi_plugin::{elements::RectRef, LUA}; use yazi_plugin::{elements::RectRef, LUA};
use yazi_shared::{Defer, RoCell}; use yazi_shared::RoCell;
use crate::Ctx; use crate::Ctx;
@ -34,7 +35,7 @@ impl Lives {
f: impl FnOnce(&Scope<'a, 'a>) -> mlua::Result<T>, f: impl FnOnce(&Scope<'a, 'a>) -> mlua::Result<T>,
) -> mlua::Result<T> { ) -> mlua::Result<T> {
let result = LUA.scope(|scope| { let result = LUA.scope(|scope| {
let _defer = Defer::new(|| SCOPE.drop()); defer! { SCOPE.drop(); };
SCOPE.init(unsafe { mem::transmute(scope) }); SCOPE.init(unsafe { mem::transmute(scope) });
LUA.set_named_registry_value("cx", scope.create_any_userdata_ref(cx)?)?; LUA.set_named_registry_value("cx", scope.create_any_userdata_ref(cx)?)?;

View file

@ -24,6 +24,7 @@ crossterm = "0.27.0"
futures = "0.3.30" futures = "0.3.30"
parking_lot = "0.12.1" parking_lot = "0.12.1"
regex = "1.10.4" regex = "1.10.4"
scopeguard = "1.2.0"
tokio = { version = "1.37.0", features = [ "full" ] } tokio = { version = "1.37.0", features = [ "full" ] }
tokio-stream = "0.1.15" tokio-stream = "0.1.15"

View file

@ -1,7 +1,7 @@
use anyhow::Result; use anyhow::Result;
use scopeguard::defer;
use tokio::{io::{AsyncBufReadExt, BufReader}, select, sync::mpsc}; use tokio::{io::{AsyncBufReadExt, BufReader}, select, sync::mpsc};
use yazi_proxy::{AppProxy, HIDER}; use yazi_proxy::{AppProxy, HIDER};
use yazi_shared::Defer;
use super::{ProcessOpBg, ProcessOpBlock, ProcessOpOrphan, ShellOpt}; use super::{ProcessOpBg, ProcessOpBlock, ProcessOpOrphan, ShellOpt};
use crate::TaskProg; use crate::TaskProg;
@ -15,7 +15,7 @@ impl Process {
pub async fn block(&self, task: ProcessOpBlock) -> Result<()> { pub async fn block(&self, task: ProcessOpBlock) -> Result<()> {
let _permit = HIDER.acquire().await.unwrap(); let _permit = HIDER.acquire().await.unwrap();
let _defer = Defer::new(AppProxy::resume); defer!(AppProxy::resume());
AppProxy::stop().await; AppProxy::stop().await;
let (id, cmd) = (task.id, task.cmd.clone()); let (id, cmd) = (task.id, task.cmd.clone());

View file

@ -1,4 +1,4 @@
use std::{env, ffi::OsString, process::Stdio}; use std::{ffi::OsString, process::Stdio};
use anyhow::Result; use anyhow::Result;
use tokio::process::{Child, Command}; use tokio::process::{Child, Command};
@ -25,12 +25,9 @@ impl ShellOpt {
} }
pub fn shell(opt: ShellOpt) -> Result<Child> { pub fn shell(opt: ShellOpt) -> Result<Child> {
let level = env::var("YAZI_LEVEL").ok().and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);
#[cfg(unix)] #[cfg(unix)]
return Ok(unsafe { return Ok(unsafe {
Command::new("sh") Command::new("sh")
.env("YAZI_LEVEL", (level + 1).to_string())
.arg("-c") .arg("-c")
.stdin(opt.stdio()) .stdin(opt.stdio())
.stdout(opt.stdio()) .stdout(opt.stdio())
@ -54,7 +51,6 @@ pub fn shell(opt: ShellOpt) -> Result<Child> {
let expanded = parser::parse(opt.cmd.to_string_lossy().as_ref(), &args_); let expanded = parser::parse(opt.cmd.to_string_lossy().as_ref(), &args_);
Ok( Ok(
Command::new("cmd") Command::new("cmd")
.env("YAZI_LEVEL", (level + 1).to_string())
.arg("/C") .arg("/C")
.args(&expanded) .args(&expanded)
.stdin(opt.stdio()) .stdin(opt.stdio())

View file

@ -1,13 +0,0 @@
pub struct Defer<F: FnOnce() -> T, T>(Option<F>);
impl<F: FnOnce() -> T, T> Defer<F, T> {
pub fn new(f: F) -> Self { Defer(Some(f)) }
}
impl<F: FnOnce() -> T, T> Drop for Defer<F, T> {
fn drop(&mut self) {
if let Some(f) = self.0.take() {
_ = f();
}
}
}

View file

@ -3,7 +3,6 @@
mod chars; mod chars;
mod condition; mod condition;
mod debounce; mod debounce;
mod defer;
mod env; mod env;
mod errors; mod errors;
pub mod event; pub mod event;
@ -21,7 +20,6 @@ mod xdg;
pub use chars::*; pub use chars::*;
pub use condition::*; pub use condition::*;
pub use debounce::*; pub use debounce::*;
pub use defer::*;
pub use env::*; pub use env::*;
pub use errors::*; pub use errors::*;
pub use layer::*; pub use layer::*;