feat: multi-path architecture

This commit is contained in:
sxyazi 2025-11-18 07:08:52 +08:00
parent 4b56e73235
commit 53b6ac5004
No known key found for this signature in database
153 changed files with 4264 additions and 2417 deletions

1
Cargo.lock generated
View file

@ -5072,6 +5072,7 @@ dependencies = [
"parking_lot", "parking_lot",
"percent-encoding", "percent-encoding",
"serde", "serde",
"thiserror 2.0.17",
"tokio", "tokio",
"uzers", "uzers",
"windows-sys 0.61.2", "windows-sys 0.61.2",

View file

@ -48,6 +48,7 @@ scopeguard = "1.2.0"
serde = { version = "1.0.228", features = [ "derive" ] } serde = { version = "1.0.228", features = [ "derive" ] }
serde_json = "1.0.145" serde_json = "1.0.145"
syntect = { version = "5.3.0", default-features = false, features = [ "parsing", "plist-load", "regex-onig" ] } syntect = { version = "5.3.0", default-features = false, features = [ "parsing", "plist-load", "regex-onig" ] }
thiserror = "2.0.17"
tokio = { version = "1.48.0", features = [ "full" ] } tokio = { version = "1.48.0", features = [ "full" ] }
tokio-stream = "0.1.17" tokio-stream = "0.1.17"
tokio-util = "0.7.17" tokio-util = "0.7.17"
@ -61,4 +62,5 @@ uzers = "0.12.1"
format_push_string = "warn" format_push_string = "warn"
implicit_clone = "warn" implicit_clone = "warn"
module_inception = "allow" module_inception = "allow"
unit_arg = "allow"
use_self = "warn" use_self = "warn"

View file

@ -1 +1 @@
{"language":"en","flagWords":[],"words":["Punct","KEYMAP","splitn","crossterm","YAZI","peekable","ratatui","syntect","pbpaste","pbcopy","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","indexmap","indexmap","unwatch","canonicalize","serde","fsevent","Ueberzug","iterm","wezterm","sixel","chafa","ueberzugpp","Konsole","Überzug","pkgs","pdftoppm","poppler","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","Upserting","prio","Ghostty","Catmull","Lanczos","cmds","unyank","scrolloff","headsup","unsub","uzers","scopeguard","SPDLOG","globset","filetime","magick","magick","prefetcher","Prework","prefetchers","PREWORKERS","conds","translit","rxvt","Urxvt","realpath","realname","REPARSE","hardlink","hardlinking","nlink","nlink","linemodes","SIGSTOP","sevenzip","rsplitn","replacen","DECSET","DECRQM","repeek","cwds","tcsi","Hyprland","Wayfire","SWAYSOCK","btime","nsec","codegen","gethostname","fchmod","fdfind","Rustc","rustc","ffprobe","vframes","luma","obase","outln","errln","tmtheme","twox","cfgs","fstype","objc","rdev","runloop","exfat","rclone","DECRQSS","DECSCUSR","libvterm","Uninit","lockin","rposition","resvg","foldhash","tilded","futs","chdir","hashbrown","JEMALLOC","RUSTFLAGS","RDONLY","GETPATH","fcntl","casefold","inodes","Splatable","casefied"],"version":"0.2"} {"version":"0.2","flagWords":[],"language":"en","words":["Punct","KEYMAP","splitn","crossterm","YAZI","peekable","ratatui","syntect","pbpaste","pbcopy","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","indexmap","indexmap","unwatch","canonicalize","serde","fsevent","Ueberzug","iterm","wezterm","sixel","chafa","ueberzugpp","Konsole","Überzug","pkgs","pdftoppm","poppler","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","Upserting","prio","Ghostty","Catmull","Lanczos","cmds","unyank","scrolloff","headsup","unsub","uzers","scopeguard","SPDLOG","globset","filetime","magick","magick","prefetcher","Prework","prefetchers","PREWORKERS","conds","translit","rxvt","Urxvt","realpath","realname","REPARSE","hardlink","hardlinking","nlink","nlink","linemodes","SIGSTOP","sevenzip","rsplitn","replacen","DECSET","DECRQM","repeek","cwds","tcsi","Hyprland","Wayfire","SWAYSOCK","btime","nsec","codegen","gethostname","fchmod","fdfind","Rustc","rustc","ffprobe","vframes","luma","obase","outln","errln","tmtheme","twox","cfgs","fstype","objc","rdev","runloop","exfat","rclone","DECRQSS","DECSCUSR","libvterm","Uninit","lockin","rposition","resvg","foldhash","tilded","futs","chdir","hashbrown","JEMALLOC","RUSTFLAGS","RDONLY","GETPATH","fcntl","casefold","inodes","Splatable","casefied","thiserror","memchr","memmem","russh","deadpool","keepalive","nodelay","publickey","deadpool"]}

View file

@ -1,9 +1,9 @@
use std::{ffi::OsStr, mem, ops::ControlFlow}; use std::{mem, ops::ControlFlow};
use anyhow::Result; use anyhow::Result;
use yazi_macro::{render, succ}; use yazi_macro::{render, succ};
use yazi_parser::cmp::{CmpItem, ShowOpt}; use yazi_parser::cmp::{CmpItem, ShowOpt};
use yazi_shared::{data::Data, osstr_contains, osstr_starts_with}; use yazi_shared::{data::Data, path::{AsPathDyn, PathDyn, PathLike}, strand::{AsStrand, StrandLike}};
use crate::{Actor, Ctx}; use crate::{Actor, Ctx};
@ -30,7 +30,7 @@ impl Actor for Show {
}; };
cmp.ticket = opt.ticket; cmp.ticket = opt.ticket;
cmp.cands = Self::match_candidates(opt.word.as_os_str(), cache); cmp.cands = Self::match_candidates(opt.word.as_path_dyn(), cache);
if cmp.cands.is_empty() { if cmp.cands.is_empty() {
succ!(render!(mem::replace(&mut cmp.visible, false))); succ!(render!(mem::replace(&mut cmp.visible, false)));
} }
@ -43,16 +43,20 @@ impl Actor for Show {
} }
impl Show { impl Show {
fn match_candidates(word: &OsStr, cache: &[CmpItem]) -> Vec<CmpItem> { fn match_candidates(word: PathDyn, cache: &[CmpItem]) -> Vec<CmpItem> {
let smart = !word.as_encoded_bytes().iter().any(|c| c.is_ascii_uppercase()); let smart = !word.encoded_bytes().iter().any(|&b| b.is_ascii_uppercase());
let flow = cache.iter().try_fold((Vec::new(), Vec::new()), |(mut exact, mut fuzzy), item| { let flow = cache.iter().try_fold((Vec::new(), Vec::new()), |(mut exact, mut fuzzy), item| {
if osstr_starts_with(&item.name, word, smart) { let name = item.name.as_strand();
let starts_with =
if smart { name.eq_ignore_ascii_case(word) } else { name.starts_with(word) };
if starts_with {
exact.push(item); exact.push(item);
if exact.len() >= LIMIT { if exact.len() >= LIMIT {
return ControlFlow::Break((exact, fuzzy)); return ControlFlow::Break((exact, fuzzy));
} }
} else if fuzzy.len() < LIMIT - exact.len() && osstr_contains(&item.name, word) { } else if fuzzy.len() < LIMIT - exact.len() && name.contains(word) {
// Here we don't break the control flow, since we want more exact matching. // Here we don't break the control flow, since we want more exact matching.
fuzzy.push(item) fuzzy.push(item)
} }

View file

@ -1,11 +1,11 @@
use std::{ffi::OsString, mem, path::{MAIN_SEPARATOR_STR, PathBuf}}; use std::{mem, path::MAIN_SEPARATOR_STR};
use anyhow::Result; use anyhow::Result;
use yazi_fs::{CWD, path::expand_url, provider::{DirReader, FileHolder}}; use yazi_fs::{CWD, path::expand_url, provider::{DirReader, FileHolder}};
use yazi_macro::{act, render, succ}; use yazi_macro::{act, render, succ};
use yazi_parser::cmp::{CmpItem, ShowOpt, TriggerOpt}; use yazi_parser::cmp::{CmpItem, ShowOpt, TriggerOpt};
use yazi_proxy::CmpProxy; use yazi_proxy::CmpProxy;
use yazi_shared::{OsStrSplit, data::Data, natsort, scheme::SchemeLike, url::{UrlBuf, UrlCow}}; use yazi_shared::{AnyAsciiChar, data::Data, natsort, path::{AsPath, PathBufDyn, PathLike}, scheme::{SchemeCow, SchemeLike}, strand::StrandBufLike, url::{UrlBuf, UrlCow, UrlLike}};
use yazi_vfs::provider; use yazi_vfs::provider;
use crate::{Actor, Ctx}; use crate::{Actor, Ctx};
@ -32,7 +32,7 @@ impl Actor for Trigger {
if cmp.caches.contains_key(&parent) { if cmp.caches.contains_key(&parent) {
let ticket = cmp.ticket; let ticket = cmp.ticket;
return act!(cmp:show, cx, ShowOpt { cache_name: parent, word, ticket, ..Default::default() }); return act!(cmp:show, cx, ShowOpt { cache: vec![], cache_name: parent, word, ticket });
} }
let ticket = cmp.ticket; let ticket = cmp.ticket;
@ -42,8 +42,8 @@ impl Actor for Trigger {
// "/" is both a directory separator and the root directory per se // "/" is both a directory separator and the root directory per se
// As there's no parent directory for the FS root, it is a special case // As there's no parent directory for the FS root, it is a special case
if parent.loc.as_os_str() == "/" { if parent.loc() == "/" {
cache.push(CmpItem { name: OsString::new(), is_dir: true }); cache.push(CmpItem { name: Default::default(), is_dir: true });
} }
while let Ok(Some(ent)) = dir.next().await { while let Ok(Some(ent)) = dir.next().await {
@ -53,9 +53,8 @@ impl Actor for Trigger {
} }
if !cache.is_empty() { if !cache.is_empty() {
cache.sort_unstable_by(|a, b| { cache
natsort(a.name.as_encoded_bytes(), b.name.as_encoded_bytes(), false) .sort_unstable_by(|a, b| natsort(a.name.encoded_bytes(), b.name.encoded_bytes(), false));
});
CmpProxy::show(ShowOpt { cache, cache_name: parent, word, ticket }); CmpProxy::show(ShowOpt { cache, cache_name: parent, word, ticket });
} }
@ -67,23 +66,28 @@ impl Actor for Trigger {
} }
impl Trigger { impl Trigger {
fn split_url(s: &str) -> Option<(UrlBuf, PathBuf)> { fn split_url(s: &str) -> Option<(UrlBuf, PathBufDyn)> {
let (scheme, path, ..) = UrlCow::parse(s.as_bytes()).ok()?; let (scheme, path) = SchemeCow::parse(s.as_bytes()).ok()?;
if scheme.is_local() && path.as_os_str() == "~" { if scheme.is_local() && path == "~" {
return None; // We don't autocomplete a `~`, but `~/` return None; // We don't autocomplete a `~`, but `~/`
} }
#[cfg(windows)] let sep = if cfg!(windows) {
const SEP: &[char] = &['/', '\\']; AnyAsciiChar::new(&[b'/', b'\\']).unwrap()
#[cfg(not(windows))] } else {
const SEP: char = std::path::MAIN_SEPARATOR; AnyAsciiChar::new(&[b'/']).unwrap()
};
Some(match path.as_os_str().rsplit_once(SEP) { Some(match path.as_path().rsplit_pred(sep) {
Some((p, c)) if p.is_empty() => { Some((p, c)) if p.is_empty() => {
(UrlBuf { loc: MAIN_SEPARATOR_STR.into(), scheme: scheme.into() }, c.into()) let root = PathBufDyn::with(scheme.kind(), MAIN_SEPARATOR_STR).expect("valid root");
(UrlCow::try_from((scheme, root)).ok()?.into_owned(), c.into())
}
Some((p, c)) => {
let parent = PathBufDyn::with(scheme.kind(), p.as_dyn()).expect("valid parent");
(expand_url(UrlCow::try_from((scheme, parent)).ok()?), c.into())
} }
Some((p, c)) => (expand_url(UrlBuf { loc: p.into(), scheme: scheme.into() }), c.into()),
None => (CWD.load().as_ref().clone(), path.into()), None => (CWD.load().as_ref().clone(), path.into()),
}) })
} }
@ -91,13 +95,13 @@ impl Trigger {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use yazi_shared::url::UrlLike; use yazi_shared::{path::PathBufLike, url::UrlLike};
use super::*; use super::*;
fn compare(s: &str, parent: &str, child: &str) { fn compare(s: &str, parent: &str, child: &str) {
let (mut p, c) = Trigger::split_url(s).unwrap(); let (mut p, c) = Trigger::split_url(s).unwrap();
if let Some(u) = p.strip_prefix(yazi_fs::CWD.load().as_ref()) { if let Ok(u) = p.try_strip_prefix(yazi_fs::CWD.load().as_ref()) {
p = UrlBuf::from(u); p = UrlBuf::from(u);
} }
assert_eq!((p, c.to_str().unwrap()), (parent.parse().unwrap(), child)); assert_eq!((p, c.to_str().unwrap()), (parent.parse().unwrap(), child));

View file

@ -4,7 +4,7 @@ use mlua::{AnyUserData, IntoLua, UserData, UserDataFields, UserDataMethods, Valu
use yazi_binding::Style; use yazi_binding::Style;
use yazi_config::THEME; use yazi_config::THEME;
use yazi_plugin::bindings::Range; use yazi_plugin::bindings::Range;
use yazi_shared::url::UrlLike; use yazi_shared::{path::PathLike, url::UrlLike};
use super::Lives; use super::Lives;
use crate::lives::PtrCell; use crate::lives::PtrCell;
@ -88,11 +88,8 @@ impl UserData for File {
if !me.url.has_trail() { if !me.url.has_trail() {
return Ok(None); return Ok(None);
} }
let Some(path) = me.url.as_path() else {
return Ok(None);
};
let mut comp = path.strip_prefix(me.url.loc.trail()).unwrap_or(path).components(); let mut comp = me.url.try_strip_prefix(me.url.trail()).unwrap_or(me.url.loc()).components();
comp.next_back(); comp.next_back();
Some(lua.create_string(comp.as_path().as_os_str().as_encoded_bytes())).transpose() Some(lua.create_string(comp.as_path().as_os_str().as_encoded_bytes())).transpose()
}); });

View file

@ -2,7 +2,7 @@ use std::ops::Deref;
use mlua::{AnyUserData, UserData, UserDataFields, UserDataMethods, Value}; use mlua::{AnyUserData, UserData, UserDataFields, UserDataMethods, Value};
use yazi_binding::{Id, UrlRef, cached_field}; use yazi_binding::{Id, UrlRef, cached_field};
use yazi_shared::url::UrlLike; use yazi_shared::{path::PathLike, strand::StrandLike, url::UrlLike};
use super::{Finder, Folder, Lives, Mode, Preference, Preview, PtrCell, Selected}; use super::{Finder, Folder, Lives, Mode, Preference, Preview, PtrCell, Selected};
@ -47,7 +47,7 @@ impl UserData for Tab {
fields.add_field_method_get("id", |_, me| Ok(Id(me.id))); fields.add_field_method_get("id", |_, me| Ok(Id(me.id)));
cached_field!(fields, name, |lua, me| { cached_field!(fields, name, |lua, me| {
let url = &me.current.url; let url = &me.current.url;
lua.create_string(url.name().unwrap_or(url.loc.as_os_str()).as_encoded_bytes()) lua.create_string(url.name().map_or_else(|| url.loc().encoded_bytes(), |n| n.encoded_bytes()))
}); });
cached_field!(fields, mode, |_, me| Mode::make(&me.mode)); cached_field!(fields, mode, |_, me| Mode::make(&me.mode));

View file

@ -11,7 +11,7 @@ use yazi_fs::{File, FilesOp, Splatter, max_common_root, path::skip_url, provider
use yazi_macro::{err, succ}; use yazi_macro::{err, succ};
use yazi_parser::VoidOpt; use yazi_parser::VoidOpt;
use yazi_proxy::{AppProxy, HIDER, TasksProxy}; use yazi_proxy::{AppProxy, HIDER, TasksProxy};
use yazi_shared::{OsStrJoin, data::Data, terminal_clear, url::{AsUrl, Component, UrlBuf, UrlCow, UrlLike}}; use yazi_shared::{OsStrJoin, data::Data, path::PathDyn, terminal_clear, url::{AsUrl, UrlBuf, UrlCow, UrlLike}};
use yazi_term::tty::TTY; use yazi_term::tty::TTY;
use yazi_vfs::{VfsFile, maybe_exists, provider}; use yazi_vfs::{VfsFile, maybe_exists, provider};
use yazi_watcher::WATCHER; use yazi_watcher::WATCHER;
@ -50,7 +50,12 @@ impl Actor for BulkRename {
.write_all(old.join(OsStr::new("\n")).as_encoded_bytes()) .write_all(old.join(OsStr::new("\n")).as_encoded_bytes())
.await?; .await?;
defer! { tokio::spawn(Local.remove_file(tmp.clone())); } defer! {
let tmp = tmp.clone();
tokio::spawn(async move {
Local::regular(&tmp).remove_file().await
});
}
TasksProxy::process_exec( TasksProxy::process_exec(
cwd.into(), cwd.into(),
Splatter::new(&[UrlCow::default(), tmp.as_url().into()]).splat(&opener.run), Splatter::new(&[UrlCow::default(), tmp.as_url().into()]).splat(&opener.run),
@ -64,8 +69,8 @@ impl Actor for BulkRename {
defer!(AppProxy::resume()); defer!(AppProxy::resume());
AppProxy::stop().await; AppProxy::stop().await;
let new: Vec<_> = Local let new: Vec<_> = Local::regular(&tmp)
.read_to_string(&tmp) .read_to_string()
.await? .await?
.lines() .lines()
.take(old.len()) .take(old.len())
@ -120,10 +125,12 @@ impl BulkRename {
let permit = WATCHER.acquire().await.unwrap(); let permit = WATCHER.acquire().await.unwrap();
let (mut failed, mut succeeded) = (Vec::new(), HashMap::with_capacity(todo.len())); let (mut failed, mut succeeded) = (Vec::new(), HashMap::with_capacity(todo.len()));
for (o, n) in todo { for (o, n) in todo {
let (old, new): (UrlBuf, UrlBuf) = ( let (Ok(old), Ok(new)) =
selected[o.0].components().take(root).chain([Component::Normal(&o)]).collect(), (Self::replace_url(&selected[o.0], root, &o), Self::replace_url(&selected[n.0], root, &n))
selected[n.0].components().take(root).chain([Component::Normal(&n)]).collect(), else {
); failed.push((o, n, anyhow!("Invalid new or old file name")));
continue;
};
if maybe_exists(&new).await && !provider::must_identical(&old, &new).await { if maybe_exists(&new).await && !provider::must_identical(&old, &new).await {
failed.push((o, n, anyhow!("Destination already exists"))); failed.push((o, n, anyhow!("Destination already exists")));
@ -137,7 +144,7 @@ impl BulkRename {
} }
if !succeeded.is_empty() { if !succeeded.is_empty() {
let it = succeeded.iter().map(|(o, n)| (o, &n.url)); let it = succeeded.iter().map(|(o, n)| (o.as_url(), n.url.as_url()));
err!(Pubsub::pub_after_bulk(it)); err!(Pubsub::pub_after_bulk(it));
FilesOp::rename(succeeded); FilesOp::rename(succeeded);
} }
@ -153,6 +160,10 @@ impl BulkRename {
YAZI.opener.block(YAZI.open.all(Path::new("bulk-rename.txt"), "text/plain")) YAZI.opener.block(YAZI.open.all(Path::new("bulk-rename.txt"), "text/plain"))
} }
fn replace_url(url: &UrlBuf, take: usize, rep: &OsStr) -> Result<UrlBuf> {
Ok(url.try_replace(take, PathDyn::with(url.kind(), rep)?)?.into_owned())
}
async fn output_failed(failed: Vec<(Tuple, Tuple, anyhow::Error)>) -> Result<()> { async fn output_failed(failed: Vec<(Tuple, Tuple, anyhow::Error)>) -> Result<()> {
let mut stdout = TTY.lockout(); let mut stdout = TTY.lockout();
terminal_clear(&mut *stdout)?; terminal_clear(&mut *stdout)?;

View file

@ -1,5 +1,3 @@
use std::ffi::OsString;
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use yazi_macro::{act, succ}; use yazi_macro::{act, succ};
use yazi_parser::mgr::CopyOpt; use yazi_parser::mgr::CopyOpt;
@ -18,7 +16,7 @@ impl Actor for Copy {
fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> {
act!(mgr:escape_visual, cx)?; act!(mgr:escape_visual, cx)?;
let mut s = OsString::new(); let mut s = Vec::<u8>::new();
let mut it = if opt.hovered { let mut it = if opt.hovered {
Box::new(cx.hovered().map(|h| &h.url).into_iter()) Box::new(cx.hovered().map(|h| &h.url).into_iter())
} else { } else {
@ -30,29 +28,29 @@ impl Actor for Copy {
match opt.r#type.as_ref() { match opt.r#type.as_ref() {
// TODO: rename to "url" // TODO: rename to "url"
"path" => { "path" => {
s.push(opt.separator.transform(&u.os_str())); s.extend_from_slice(&opt.separator.transform(&u.os_str()));
} }
"dirname" => { "dirname" => {
if let Some(p) = u.parent() { if let Some(p) = u.parent() {
s.push(opt.separator.transform(&p.os_str())); s.extend_from_slice(&opt.separator.transform(&p.os_str()));
} }
} }
"filename" => { "filename" => {
s.push(opt.separator.transform(u.name().unwrap_or_default())); s.extend_from_slice(&opt.separator.transform(&u.name().unwrap_or_default()));
} }
"name_without_ext" => { "name_without_ext" => {
s.push(opt.separator.transform(u.stem().unwrap_or_default())); s.extend_from_slice(&opt.separator.transform(&u.stem().unwrap_or_default()));
} }
_ => bail!("Unknown copy type: {}", opt.r#type), _ => bail!("Unknown copy type: {}", opt.r#type),
}; };
if it.peek().is_some() { if it.peek().is_some() {
s.push("\n"); s.push(b'\n');
} }
} }
// Copy the CWD path regardless even if the directory is empty // Copy the CWD path regardless even if the directory is empty
if s.is_empty() && opt.r#type == "dirname" { if s.is_empty() && opt.r#type == "dirname" {
s.push(opt.separator.transform(&cx.cwd().os_str())); s.extend_from_slice(&opt.separator.transform(&cx.cwd().os_str()));
} }
futures::executor::block_on(CLIPBOARD.set(s)); futures::executor::block_on(CLIPBOARD.set(s));

View file

@ -27,7 +27,10 @@ impl Actor for Create {
return; return;
} }
let new = cwd.join(&name); let Ok(new) = cwd.try_join(&name) else {
return;
};
if !opt.force if !opt.force
&& maybe_exists(&new).await && maybe_exists(&new).await
&& !ConfirmProxy::show(ConfirmCfg::overwrite(&new)).await && !ConfirmProxy::show(ConfirmCfg::overwrite(&new)).await

View file

@ -8,7 +8,7 @@ use yazi_fs::{File, FsScheme, provider::{Provider, local::Local}};
use yazi_macro::succ; use yazi_macro::succ;
use yazi_parser::mgr::{DownloadOpt, OpenOpt}; use yazi_parser::mgr::{DownloadOpt, OpenOpt};
use yazi_proxy::MgrProxy; use yazi_proxy::MgrProxy;
use yazi_shared::{data::Data, url::UrlCow}; use yazi_shared::{data::Data, url::{UrlCow, UrlLike}};
use yazi_vfs::VfsFile; use yazi_vfs::VfsFile;
use crate::{Actor, Ctx}; use crate::{Actor, Ctx};
@ -78,7 +78,7 @@ impl Download {
let roots: HashSet<_> = urls.iter().filter_map(|u| u.scheme().cache()).collect(); let roots: HashSet<_> = urls.iter().filter_map(|u| u.scheme().cache()).collect();
for mut root in roots { for mut root in roots {
root.push("%lock"); root.push("%lock");
Local.create_dir_all(root).await.ok(); Local::regular(&root).create_dir_all().await.ok();
} }
} }
} }

View file

@ -15,7 +15,7 @@ impl Actor for Enter {
fn act(cx: &mut Ctx, _: Self::Options) -> Result<Data> { fn act(cx: &mut Ctx, _: Self::Options) -> Result<Data> {
let Some(h) = cx.hovered().filter(|h| h.is_dir()) else { succ!() }; let Some(h) = cx.hovered().filter(|h| h.is_dir()) else { succ!() };
let url = if h.url.is_search() { h.url.to_regular() } else { h.url.clone() }; let url = if h.url.is_search() { h.url.to_regular()? } else { h.url.clone() };
act!(mgr:cd, cx, (url, CdSource::Enter)) act!(mgr:cd, cx, (url, CdSource::Enter))
} }

View file

@ -16,11 +16,8 @@ impl Actor for Follow {
fn act(cx: &mut Ctx, _: Self::Options) -> Result<Data> { fn act(cx: &mut Ctx, _: Self::Options) -> Result<Data> {
let Some(file) = cx.hovered() else { succ!() }; let Some(file) = cx.hovered() else { succ!() };
let Some(link_to) = &file.link_to else { succ!() }; let Some(link_to) = &file.link_to else { succ!() };
let Some(parent) = file.url.parent() else { succ!() };
if let Some(p) = file.url.parent() { let Ok(joined) = parent.try_join(link_to) else { succ!() };
act!(mgr:reveal, cx, clean_url(p.join(link_to))) act!(mgr:reveal, cx, clean_url(joined))
} else {
succ!()
}
} }
} }

View file

@ -18,7 +18,7 @@ impl Actor for Hover {
// Parent should always track CWD // Parent should always track CWD
if let Some(p) = &mut tab.parent { if let Some(p) = &mut tab.parent {
render!(p.repos(tab.current.url.strip_prefix(&p.url))); render!(p.repos(tab.current.url.try_strip_prefix(&p.url).ok()));
} }
// Repos CWD // Repos CWD

View file

@ -21,7 +21,7 @@ impl Actor for Leave {
let Some(mut url) = url else { succ!() }; let Some(mut url) = url else { succ!() };
if url.is_search() { if url.is_search() {
url = url.into_regular(); url = url.as_regular()?;
} }
act!(mgr:cd, cx, (url, CdSource::Leave)) act!(mgr:cd, cx, (url, CdSource::Leave))

View file

@ -6,7 +6,7 @@ use yazi_fs::{CWD, Files, FilesOp, cha::Cha};
use yazi_macro::{act, succ}; use yazi_macro::{act, succ};
use yazi_parser::VoidOpt; use yazi_parser::VoidOpt;
use yazi_proxy::MgrProxy; use yazi_proxy::MgrProxy;
use yazi_shared::{data::Data, scheme::SchemeLike, url::UrlBuf}; use yazi_shared::{data::Data, url::{UrlBuf, UrlLike}};
use yazi_term::tty::TTY; use yazi_term::tty::TTY;
use yazi_vfs::{VfsFiles, VfsFilesOp}; use yazi_vfs::{VfsFiles, VfsFilesOp};
@ -41,7 +41,7 @@ impl Actor for Refresh {
impl Refresh { impl Refresh {
fn cwd_changed() { fn cwd_changed() {
if CWD.load().scheme.is_virtual() { if CWD.load().kind().is_virtual() {
MgrProxy::watch(); MgrProxy::watch();
} }
} }

View file

@ -5,7 +5,7 @@ use yazi_fs::{File, FilesOp};
use yazi_macro::{act, err, ok_or_not_found, succ}; use yazi_macro::{act, err, ok_or_not_found, succ};
use yazi_parser::mgr::RenameOpt; use yazi_parser::mgr::RenameOpt;
use yazi_proxy::{ConfirmProxy, InputProxy, MgrProxy}; use yazi_proxy::{ConfirmProxy, InputProxy, MgrProxy};
use yazi_shared::{Id, data::Data, path::PathLike, url::{UrlBuf, UrlLike}}; use yazi_shared::{Id, data::Data, path::PathLike, strand::StrandLike, url::{UrlBuf, UrlLike}};
use yazi_vfs::{VfsFile, maybe_exists, provider}; use yazi_vfs::{VfsFile, maybe_exists, provider};
use yazi_watcher::WATCHER; use yazi_watcher::WATCHER;
@ -49,7 +49,10 @@ impl Actor for Rename {
return; return;
} }
let new = old.parent().unwrap().join(name); let Some(Ok(new)) = old.parent().map(|u| u.try_join(name)) else {
return;
};
if opt.force || !maybe_exists(&new).await || provider::must_identical(&old, &new).await { if opt.force || !maybe_exists(&new).await || provider::must_identical(&old, &new).await {
Self::r#do(tab, old, new).await.ok(); Self::r#do(tab, old, new).await.ok();
} else if ConfirmProxy::show(ConfirmCfg::overwrite(&new)).await { } else if ConfirmProxy::show(ConfirmCfg::overwrite(&new)).await {

View file

@ -52,7 +52,7 @@ impl Actor for SearchDo {
handle.abort(); handle.abort();
} }
let cwd = tab.cwd().to_search(opt.subject.as_ref()); let cwd = tab.cwd().to_search(opt.subject.as_ref())?;
let hidden = tab.pref.show_hidden; let hidden = tab.pref.show_hidden;
tab.search = Some(tokio::spawn(async move { tab.search = Some(tokio::spawn(async move {
@ -111,7 +111,7 @@ impl Actor for SearchStop {
succ!(); succ!();
} }
let rep = tab.history.remove_or(tab.cwd().to_regular()); let rep = tab.history.remove_or(tab.cwd().to_regular()?);
drop(mem::replace(&mut tab.current, rep)); drop(mem::replace(&mut tab.current, rep));
act!(mgr:hidden, cx)?; act!(mgr:hidden, cx)?;

View file

@ -29,10 +29,13 @@ impl Actor for TabCreate {
(true, wd.into_owned()) (true, wd.into_owned())
} else if let Some(h) = cx.hovered() { } else if let Some(h) = cx.hovered() {
tab.pref = cx.tab().pref.clone(); tab.pref = cx.tab().pref.clone();
(false, h.url.to_regular()) (false, h.url.clone())
} else if cx.cwd().is_search() {
tab.pref = cx.tab().pref.clone();
(true, cx.cwd().to_regular()?)
} else { } else {
tab.pref = cx.tab().pref.clone(); tab.pref = cx.tab().pref.clone();
(true, cx.cwd().to_regular()) (true, cx.cwd().clone())
}; };
let tabs = &mut cx.mgr.tabs; let tabs = &mut cx.mgr.tabs;

View file

@ -17,7 +17,9 @@ impl Actor for UpdateFiles {
fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> {
let revision = cx.current().files.revision; let revision = cx.current().files.revision;
let linked: Vec<_> = LINKED.read().from_dir(opt.op.cwd()).map(|u| opt.op.chdir(u)).collect(); let linked: Vec<_> =
LINKED.read().from_dir(opt.op.cwd()).filter_map(|u| opt.op.chdir(u).ok()).collect();
for op in [opt.op].into_iter().chain(linked) { for op in [opt.op].into_iter().chain(linked) {
cx.mgr.yanked.apply_op(&op); cx.mgr.yanked.apply_op(&op);
Self::update_tab(cx, op).ok(); Self::update_tab(cx, op).ok();

View file

@ -39,7 +39,7 @@ impl Image {
}) })
.await??; .await??;
Ok(Local.write(cache, buf).await?) Ok(Local::regular(&cache).write(buf).await?)
} }
pub(super) async fn downscale(path: PathBuf, rect: Rect) -> Result<DynamicImage> { pub(super) async fn downscale(path: PathBuf, rect: Rect) -> Result<DynamicImage> {

View file

@ -1,4 +1,4 @@
#![allow(clippy::option_map_unit_fn, clippy::unit_arg)] #![allow(clippy::option_map_unit_fn)]
yazi_macro::mod_pub!(drivers); yazi_macro::mod_pub!(drivers);

View file

@ -1,7 +1,5 @@
#![allow(clippy::unit_arg)]
mod macros; mod macros;
yazi_macro::mod_pub!(elements); yazi_macro::mod_pub!(elements);
yazi_macro::mod_flat!(cha color composer error file icon id iter permit runtime scheme stage style url urn utils); yazi_macro::mod_flat!(cha color composer error file icon id iter path permit runtime scheme stage style url utils);

View file

@ -151,10 +151,11 @@ macro_rules! impl_file_fields {
($fields:ident) => { ($fields:ident) => {
$crate::cached_field!($fields, cha, |_, me| Ok($crate::Cha(me.cha))); $crate::cached_field!($fields, cha, |_, me| Ok($crate::Cha(me.cha)));
$crate::cached_field!($fields, url, |_, me| Ok($crate::Url::new(me.url_owned()))); $crate::cached_field!($fields, url, |_, me| Ok($crate::Url::new(me.url_owned())));
$crate::cached_field!($fields, link_to, |_, me| Ok(me.link_to.clone().map($crate::Url::new))); $crate::cached_field!($fields, link_to, |_, me| Ok(me.link_to_url().map($crate::Url::new)));
$crate::cached_field!($fields, name, |lua, me| { $crate::cached_field!($fields, name, |lua, me| {
me.name().map(|s| lua.create_string(s.as_encoded_bytes())).transpose() use yazi_shared::strand::StrandLike;
me.name().map(|s| lua.create_string(s.encoded_bytes())).transpose()
}); });
$crate::cached_field!($fields, cache, |_, me| { $crate::cached_field!($fields, cache, |_, me| {
use yazi_fs::FsUrl; use yazi_fs::FsUrl;

View file

@ -1,7 +1,7 @@
use std::ops::Deref; use std::ops::Deref;
use mlua::{ExternalError, FromLua, Lua, UserData, Value}; use mlua::{ExternalError, FromLua, Lua, MetaMethod, UserData, UserDataMethods, Value};
use yazi_shared::path::PathBufDyn; use yazi_shared::path::{PathBufDyn, PathBufLike};
pub struct Path(pub PathBufDyn); pub struct Path(pub PathBufDyn);
@ -24,4 +24,9 @@ impl FromLua for Path {
} }
} }
impl UserData for Path {} impl UserData for Path {
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods
.add_meta_method(MetaMethod::ToString, |lua, me, ()| lua.create_string(me.encoded_bytes()));
}
}

View file

@ -20,14 +20,14 @@ impl Deref for Scheme {
} }
impl Scheme { impl Scheme {
pub fn new(scheme: &yazi_shared::scheme::Scheme) -> Self { pub fn new(scheme: impl Into<yazi_shared::scheme::Scheme>) -> Self {
Self { inner: scheme.clone(), v_kind: None, v_cache: None } Self { inner: scheme.into(), v_kind: None, v_cache: None }
} }
} }
impl UserData for Scheme { impl UserData for Scheme {
fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
cached_field!(fields, kind, |_, me| Ok(me.kind())); cached_field!(fields, kind, |_, me| Ok(me.kind().as_str()));
cached_field!(fields, cache, |_, me| Ok(me.cache().map(Url::new))); cached_field!(fields, cache, |_, me| Ok(me.cache().map(Url::new)));
fields.add_field_method_get("is_virtual", |_, me| Ok(me.is_virtual())); fields.add_field_method_get("is_virtual", |_, me| Ok(me.is_virtual()));

View file

@ -1,8 +1,8 @@
use std::ops::Deref; use std::ops::Deref;
use mlua::{AnyUserData, ExternalError, FromLua, Lua, MetaMethod, UserData, UserDataFields, UserDataMethods, UserDataRef, Value}; use mlua::{AnyUserData, ExternalError, ExternalResult, FromLua, Lua, MetaMethod, UserData, UserDataFields, UserDataMethods, UserDataRef, Value};
use yazi_fs::{FsHash64, FsHash128}; use yazi_fs::{FsHash64, FsHash128};
use yazi_shared::{IntoOsStr, scheme::SchemeLike, url::{AsUrl, UrlCow, UrlLike}}; use yazi_shared::{path::{PathLike, StripPrefixError}, strand::{StrandCow, StrandLike}, url::{AsUrl, UrlCow, UrlLike}};
use crate::{Scheme, cached_field, deprecate}; use crate::{Scheme, cached_field, deprecate};
@ -99,26 +99,28 @@ impl FromLua for Url {
impl UserData for Url { impl UserData for Url {
fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
cached_field!(fields, name, |lua, me| { cached_field!(fields, name, |lua, me| {
me.name().map(|s| lua.create_string(s.as_encoded_bytes())).transpose() me.name().map(|s| lua.create_string(s.encoded_bytes())).transpose()
}); });
cached_field!(fields, stem, |lua, me| { cached_field!(fields, stem, |lua, me| {
me.stem().map(|s| lua.create_string(s.as_encoded_bytes())).transpose() me.stem().map(|s| lua.create_string(s.encoded_bytes())).transpose()
}); });
cached_field!(fields, ext, |lua, me| { cached_field!(fields, ext, |lua, me| {
me.ext().map(|s| lua.create_string(s.as_encoded_bytes())).transpose() me.ext().map(|s| lua.create_string(s.encoded_bytes())).transpose()
}); });
cached_field!(fields, parent, |_, me| Ok(me.parent().map(Self::new))); cached_field!(fields, parent, |_, me| Ok(me.parent().map(Self::new)));
cached_field!(fields, urn, |_, me| Ok(super::Path::new(me.urn()))); cached_field!(fields, urn, |_, me| Ok(super::Path::new(me.urn())));
cached_field!(fields, base, |_, me| Ok(me.base().map(Self::new))); cached_field!(fields, base, |_, me| {
Ok(Some(me.base()).filter(|u| !u.loc().is_empty()).map(Self::new))
});
cached_field!(fields, scheme, |_, me| Ok(Scheme::new(&me.scheme))); cached_field!(fields, scheme, |_, me| Ok(Scheme::new(me.scheme())));
cached_field!(fields, domain, |lua, me| { cached_field!(fields, domain, |lua, me| {
me.scheme.domain().map(|s| lua.create_string(s)).transpose() me.scheme().domain().map(|s| lua.create_string(s)).transpose()
}); });
fields.add_field_method_get("frag", |lua, me| { fields.add_field_method_get("frag", |lua, me| {
deprecate!(lua, "`frag` property of Url is deprecated and renamed to `domain`, please use the new name instead, in your {}"); deprecate!(lua, "`frag` property of Url is deprecated and renamed to `domain`, please use the new name instead, in your {}");
me.scheme.domain().map(|s| lua.create_string(s)).transpose() me.scheme().domain().map(|s| lua.create_string(s)).transpose()
}); });
fields.add_field_method_get("is_regular", |_, me| Ok(me.is_regular())); fields.add_field_method_get("is_regular", |_, me| Ok(me.is_regular()));
@ -138,42 +140,60 @@ impl UserData for Url {
}); });
methods.add_method("join", |_, me, other: Value| { methods.add_method("join", |_, me, other: Value| {
Ok(Self::new(match other { Ok(Self::new(match other {
Value::String(s) => me.join(s.as_bytes().into_os_str()?), Value::String(s) => {
let b = s.as_bytes();
me.try_join(StrandCow::with(me.kind(), &*b).into_lua_err()?).into_lua_err()?
}
Value::UserData(ud) => { Value::UserData(ud) => {
let url = ud.borrow::<Self>()?; let url = ud.borrow::<Self>()?;
if !me.scheme.covariant(&url.scheme) { if !me.scheme().covariant(url.scheme()) {
return Err("cannot join Urls with different schemes".into_lua_err()); return Err("cannot join Urls with different schemes".into_lua_err());
} }
me.join(&url.loc) me.try_join(url.loc()).into_lua_err()?
} }
_ => Err("must be a string or Url".into_lua_err())?, _ => Err("must be a string or Url".into_lua_err())?,
})) }))
}); });
methods.add_method("starts_with", |_, me, base: Value| { methods.add_method("starts_with", |_, me, base: Value| {
Ok(match base { Ok(match base {
Value::String(s) => me.loc.starts_with(s.as_bytes().into_os_str()?), Value::String(s) => {
Value::UserData(ud) => me.starts_with(&*ud.borrow::<Self>()?), let b = s.as_bytes();
me.loc().try_starts_with(&StrandCow::with(me.kind(), &*b).into_lua_err()?).into_lua_err()
}
Value::UserData(ud) => me.try_starts_with(&*ud.borrow::<Self>()?).into_lua_err(),
_ => Err("must be a string or Url".into_lua_err())?, _ => Err("must be a string or Url".into_lua_err())?,
}) })
}); });
methods.add_method("ends_with", |_, me, child: Value| { methods.add_method("ends_with", |_, me, child: Value| {
Ok(match child { Ok(match child {
Value::String(s) => me.loc.ends_with(s.as_bytes().into_os_str()?), Value::String(s) => {
Value::UserData(ud) => me.ends_with(&*ud.borrow::<Self>()?), let b = s.as_bytes();
me.loc().try_ends_with(&StrandCow::with(me.kind(), &*b).into_lua_err()?).into_lua_err()
}
Value::UserData(ud) => me.try_ends_with(&*ud.borrow::<Self>()?).into_lua_err(),
_ => Err("must be a string or Url".into_lua_err())?, _ => Err("must be a string or Url".into_lua_err())?,
}) })
}); });
methods.add_method("strip_prefix", |_, me, base: Value| { methods.add_method("strip_prefix", |_, me, base: Value| {
let path = match base { let strip = match base {
Value::String(s) => me.loc().strip_prefix(&s.as_bytes().into_os_str()?).map(Into::into), Value::String(s) => {
Value::UserData(ud) => me.strip_prefix(&*ud.borrow::<Self>()?), let b = s.as_bytes();
me.loc().try_strip_prefix(&StrandCow::with(me.kind(), &*b).into_lua_err()?)
}
Value::UserData(ud) => me.try_strip_prefix(&*ud.borrow::<Self>()?),
_ => Err("must be a string or Url".into_lua_err())?, _ => Err("must be a string or Url".into_lua_err())?,
}; };
Ok(path.map(Self::new)) // TODO: return `Path` instead of `Url`
Ok(match strip {
Ok(p) => Some(Self::new(p)), // TODO: return `Path` instead of `Url`
Err(StripPrefixError::Exotic | StripPrefixError::NotPrefix) => None,
Err(e @ StripPrefixError::WrongEncoding) => Err(e.into_lua_err())?,
})
}); });
methods.add_function_mut("into_search", |_, (ud, domain): (AnyUserData, mlua::String)| { methods.add_function_mut("into_search", |_, (ud, domain): (AnyUserData, mlua::String)| {
Ok(Self::new(ud.take::<Self>()?.inner.into_search(domain.to_str()?))) let url = ud.take::<Self>()?.inner.into_search(domain.to_str()?).into_lua_err()?;
Ok(Self::new(url))
}); });
methods.add_meta_method(MetaMethod::Eq, |_, me, other: UrlRef| Ok(me.inner == other.inner)); methods.add_meta_method(MetaMethod::Eq, |_, me, other: UrlRef| Ok(me.inner == other.inner));

View file

@ -4,13 +4,13 @@ use futures::executor::block_on;
use hashbrown::HashSet; use hashbrown::HashSet;
use serde::Serialize; use serde::Serialize;
use yazi_fs::{CWD, Xdg, path::expand_url}; use yazi_fs::{CWD, Xdg, path::expand_url};
use yazi_shared::{path::{PathBufDyn, PathLike}, url::{UrlBuf, UrlCow, UrlLike}}; use yazi_shared::{strand::StrandBuf, url::{UrlBuf, UrlLike}};
use yazi_vfs::provider; use yazi_vfs::provider;
#[derive(Debug, Default, Serialize)] #[derive(Debug, Default, Serialize)]
pub struct Boot { pub struct Boot {
pub cwds: Vec<UrlBuf>, pub cwds: Vec<UrlBuf>,
pub files: Vec<PathBufDyn>, pub files: Vec<StrandBuf>,
pub local_events: HashSet<String>, pub local_events: HashSet<String>,
pub remote_events: HashSet<String>, pub remote_events: HashSet<String>,
@ -22,25 +22,28 @@ pub struct Boot {
} }
impl Boot { impl Boot {
async fn parse_entries(entries: &[UrlBuf]) -> (Vec<UrlBuf>, Vec<PathBufDyn>) { async fn parse_entries(entries: &[UrlBuf]) -> (Vec<UrlBuf>, Vec<StrandBuf>) {
if entries.is_empty() { if entries.is_empty() {
return (vec![CWD.load().as_ref().clone()], vec![PathBufDyn::os_default()]); return (vec![CWD.load().as_ref().clone()], vec![Default::default()]);
} }
async fn go(entry: &UrlBuf) -> (UrlBuf, PathBufDyn) { async fn go(entry: &UrlBuf) -> (UrlBuf, StrandBuf) {
let mut entry = expand_url(entry); let mut entry = expand_url(entry);
if let Ok(u @ UrlCow::Owned { .. }) = provider::absolute(&entry).await {
if let Ok(u) = provider::absolute(&entry).await
&& u.is_owned()
{
entry = u.into_owned(); entry = u.into_owned();
} }
let Some((parent, child)) = entry.pair() else { let Some((parent, child)) = entry.pair() else {
return (entry, PathBufDyn::os_default()); return (entry, Default::default());
}; };
if provider::metadata(&entry).await.is_ok_and(|m| m.is_file()) { if provider::metadata(&entry).await.is_ok_and(|m| m.is_file()) {
(parent.into(), child.owned()) (parent.into(), child.into())
} else { } else {
(entry, PathBufDyn::os_default()) (entry, Default::default())
} }
} }

View file

@ -1,5 +1,5 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use yazi_fs::{ok_or_not_found, provider::{DirReader, FileHolder, Provider, local::Local}}; use yazi_fs::{ok_or_not_found, provider::{Provider, local::Local}};
use yazi_macro::outln; use yazi_macro::outln;
use super::Dependency; use super::Dependency;
@ -23,9 +23,9 @@ impl Dependency {
pub(super) async fn delete_assets(&self) -> Result<()> { pub(super) async fn delete_assets(&self) -> Result<()> {
let assets = self.target().join("assets"); let assets = self.target().join("assets");
match Local.read_dir(&assets).await { match tokio::fs::read_dir(&assets).await {
Ok(mut it) => { Ok(mut it) => {
while let Some(entry) = it.next().await? { while let Some(entry) = it.next_entry().await? {
remove_sealed(&entry.path()) remove_sealed(&entry.path())
.await .await
.with_context(|| format!("failed to remove `{}`", entry.path().display()))?; .with_context(|| format!("failed to remove `{}`", entry.path().display()))?;
@ -35,7 +35,7 @@ impl Dependency {
Err(e) => Err(e).context(format!("failed to read `{}`", assets.display()))?, Err(e) => Err(e).context(format!("failed to read `{}`", assets.display()))?,
}; };
Local.remove_dir_clean(assets).await; Local::regular(&assets).remove_dir_clean().await;
Ok(()) Ok(())
} }
@ -49,7 +49,7 @@ impl Dependency {
.with_context(|| format!("failed to delete `{}`", path.display()))?; .with_context(|| format!("failed to delete `{}`", path.display()))?;
} }
if ok_or_not_found(Local.remove_dir(&dir).await).is_ok() { if ok_or_not_found(Local::regular(&dir).remove_dir().await).is_ok() {
outln!("Done!")?; outln!("Done!")?;
} else { } else {
outln!( outln!(

View file

@ -3,7 +3,7 @@ use std::{io::BufWriter, path::{Path, PathBuf}, str::FromStr};
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer};
use twox_hash::XxHash3_128; use twox_hash::XxHash3_128;
use yazi_fs::{Xdg, provider::{DirReader, FileHolder, Provider, local::Local}}; use yazi_fs::Xdg;
use yazi_shared::BytesExt; use yazi_shared::BytesExt;
#[derive(Clone, Default)] #[derive(Clone, Default)]
@ -62,11 +62,11 @@ impl Dependency {
} }
pub(super) async fn plugin_files(dir: &Path) -> std::io::Result<Vec<String>> { pub(super) async fn plugin_files(dir: &Path) -> std::io::Result<Vec<String>> {
let mut it = Local.read_dir(dir).await?; let mut it = tokio::fs::read_dir(dir).await?;
let mut files: Vec<String> = let mut files: Vec<String> =
["LICENSE", "README.md", "main.lua"].into_iter().map(Into::into).collect(); ["LICENSE", "README.md", "main.lua"].into_iter().map(Into::into).collect();
while let Some(entry) = it.next().await? { while let Some(entry) = it.next_entry().await? {
if let Ok(name) = entry.name().into_owned().into_string() if let Ok(name) = entry.file_name().into_string()
&& let Some(stripped) = name.strip_suffix(".lua") && let Some(stripped) = name.strip_suffix(".lua")
&& stripped != "main" && stripped != "main"
&& stripped.as_bytes().kebab_cased() && stripped.as_bytes().kebab_cased()

View file

@ -1,7 +1,7 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use yazi_fs::provider::{DirReader, FileHolder, Provider, local::Local}; use yazi_fs::provider::{Provider, local::Local};
use yazi_macro::outln; use yazi_macro::outln;
use super::Dependency; use super::Dependency;
@ -20,7 +20,7 @@ impl Dependency {
self.hash_check().await?; self.hash_check().await?;
} }
Local.create_dir_all(&to).await?; Local::regular(&to).create_dir_all().await?;
self.delete_assets().await?; self.delete_assets().await?;
let res1 = Self::deploy_assets(from.join("assets"), to.join("assets")).await; let res1 = Self::deploy_assets(from.join("assets"), to.join("assets")).await;
@ -30,7 +30,7 @@ impl Dependency {
self.delete_sources().await?; self.delete_sources().await?;
} }
Local.remove_dir_clean(to).await; Local::regular(&to).remove_dir_clean().await;
self.hash = self.hash().await?; self.hash = self.hash().await?;
res2?; res2?;
res1?; res1?;
@ -40,11 +40,11 @@ impl Dependency {
} }
async fn deploy_assets(from: PathBuf, to: PathBuf) -> Result<()> { async fn deploy_assets(from: PathBuf, to: PathBuf) -> Result<()> {
match Local.read_dir(&from).await { match tokio::fs::read_dir(&from).await {
Ok(mut it) => { Ok(mut it) => {
Local.create_dir_all(&to).await?; Local::regular(&to).create_dir_all().await?;
while let Some(entry) = it.next().await? { while let Some(entry) = it.next_entry().await? {
let (src, dist) = (entry.path(), to.join(entry.name())); let (src, dist) = (entry.path(), to.join(entry.file_name()));
copy_and_seal(&src, &dist).await.with_context(|| { copy_and_seal(&src, &dist).await.with_context(|| {
format!("failed to copy `{}` to `{}`", src.display(), dist.display()) format!("failed to copy `{}` to `{}`", src.display(), dist.display())
})?; })?;

View file

@ -1,6 +1,6 @@
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use twox_hash::XxHash3_128; use twox_hash::XxHash3_128;
use yazi_fs::provider::{DirReader, FileHolder, Provider, local::Local}; use yazi_fs::provider::local::Local;
use yazi_macro::ok_or_not_found; use yazi_macro::ok_or_not_found;
use super::Dependency; use super::Dependency;
@ -15,17 +15,17 @@ impl Dependency {
for file in files { for file in files {
h.write(file.as_bytes()); h.write(file.as_bytes());
h.write(b"VpvFw9Atb7cWGOdqhZCra634CcJJRlsRl72RbZeV0vpG1\0"); h.write(b"VpvFw9Atb7cWGOdqhZCra634CcJJRlsRl72RbZeV0vpG1\0");
h.write(&ok_or_not_found!(Local.read(dir.join(file)).await)); h.write(&ok_or_not_found!(Local::regular(&dir.join(file)).read().await));
} }
let mut assets = vec![]; let mut assets = vec![];
match Local.read_dir(dir.join("assets")).await { match tokio::fs::read_dir(dir.join("assets")).await {
Ok(mut it) => { Ok(mut it) => {
while let Some(entry) = it.next().await? { while let Some(entry) = it.next_entry().await? {
let Ok(name) = entry.name().into_owned().into_string() else { let Ok(name) = entry.file_name().into_string() else {
bail!("asset path is not valid UTF-8: {}", entry.path().display()); bail!("asset path is not valid UTF-8: {}", entry.path().display());
}; };
assets.push((name, Local.read(entry.path()).await?)); assets.push((name, Local::regular(&entry.path()).read().await?));
} }
} }
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}

View file

@ -15,7 +15,7 @@ pub(crate) struct Package {
impl Package { impl Package {
pub(crate) async fn load() -> Result<Self> { pub(crate) async fn load() -> Result<Self> {
let s = ok_or_not_found!(Local.read_to_string(Self::toml()).await); let s = ok_or_not_found!(Local::regular(&Self::toml()).read_to_string().await);
Ok(toml::from_str(&s)?) Ok(toml::from_str(&s)?)
} }
@ -132,7 +132,7 @@ impl Package {
async fn save(&self) -> Result<()> { async fn save(&self) -> Result<()> {
let s = toml::to_string_pretty(self)?; let s = toml::to_string_pretty(self)?;
Local.write(Self::toml(), s).await.context("Failed to write package.toml") Local::regular(&Self::toml()).write(s).await.context("Failed to write package.toml")
} }
fn toml() -> PathBuf { Xdg::config_dir().join("package.toml") } fn toml() -> PathBuf { Xdg::config_dir().join("package.toml") }

View file

@ -6,19 +6,19 @@ use yazi_macro::ok_or_not_found;
#[inline] #[inline]
pub async fn must_exists(path: impl AsRef<Path>) -> bool { pub async fn must_exists(path: impl AsRef<Path>) -> bool {
Local.symlink_metadata(path).await.is_ok() Local::regular(&path).symlink_metadata().await.is_ok()
} }
#[inline] #[inline]
pub async fn maybe_exists(path: impl AsRef<Path>) -> bool { pub async fn maybe_exists(path: impl AsRef<Path>) -> bool {
match Local.symlink_metadata(path).await { match Local::regular(&path).symlink_metadata().await {
Ok(_) => true, Ok(_) => true,
Err(e) => e.kind() != std::io::ErrorKind::NotFound, Err(e) => e.kind() != std::io::ErrorKind::NotFound,
} }
} }
pub async fn copy_and_seal(from: &Path, to: &Path) -> io::Result<()> { pub async fn copy_and_seal(from: &Path, to: &Path) -> io::Result<()> {
let b = Local.read(from).await?; let b = Local::regular(from).read().await?;
ok_or_not_found!(remove_sealed(to).await); ok_or_not_found!(remove_sealed(to).await);
let mut file = Gate::default().create_new(true).write(true).truncate(true).open(to).await?; let mut file = Gate::default().create_new(true).write(true).truncate(true).open(to).await?;
@ -31,7 +31,6 @@ pub async fn copy_and_seal(from: &Path, to: &Path) -> io::Result<()> {
Ok(()) Ok(())
} }
// TODO: use `yazi_fs` instead of `tokio::fs`
pub async fn remove_sealed(p: &Path) -> io::Result<()> { pub async fn remove_sealed(p: &Path) -> io::Result<()> {
#[cfg(windows)] #[cfg(windows)]
{ {
@ -40,5 +39,5 @@ pub async fn remove_sealed(p: &Path) -> io::Result<()> {
tokio::fs::set_permissions(p, perm).await?; tokio::fs::set_permissions(p, perm).await?;
} }
Local.remove_file(p).await Local::regular(p).remove_file().await
} }

View file

@ -33,7 +33,7 @@ impl Mgr {
} }
let home = UrlBuf::from(dirs::home_dir().unwrap_or_default()); let home = UrlBuf::from(dirs::home_dir().unwrap_or_default());
let cwd = if let Some(p) = CWD.load().strip_prefix(&home) { let cwd = if let Ok(p) = CWD.load().try_strip_prefix(&home) {
format!("~{}{}", std::path::MAIN_SEPARATOR, p.display()) format!("~{}{}", std::path::MAIN_SEPARATOR, p.display())
} else { } else {
format!("{}", CWD.load().display()) format!("{}", CWD.load().display())

View file

@ -1,9 +1,9 @@
use std::{fmt::Debug, str::FromStr}; use std::{fmt::Debug, str::FromStr};
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use globset::GlobBuilder; use globset::{Candidate, GlobBuilder};
use serde::Deserialize; use serde::Deserialize;
use yazi_shared::{scheme::SchemeRef, url::AsUrl}; use yazi_shared::{path::PathLike, scheme::SchemeKind, url::AsUrl};
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(try_from = "String")] #[serde(try_from = "String")]
@ -28,28 +28,32 @@ impl Debug for Pattern {
} }
impl Pattern { impl Pattern {
// FIXME: simplify conditional compilation
pub fn match_url(&self, url: impl AsUrl, is_dir: bool) -> bool { pub fn match_url(&self, url: impl AsUrl, is_dir: bool) -> bool {
let url = url.as_url(); let url = url.as_url();
if is_dir != self.is_dir { if is_dir != self.is_dir {
return false; return false;
} else if !self.scheme.matches(url.scheme) { } else if !self.scheme.matches(url.kind()) {
return false; return false;
} else if self.is_star { } else if self.is_star {
return true; return true;
} }
#[cfg(unix)] #[cfg(unix)]
let path = &url.loc; {
self.inner.is_match_candidate(&Candidate::from_bytes(url.loc().encoded_bytes()))
}
#[cfg(windows)] #[cfg(windows)]
let path = if self.sep_lit { if self.sep_lit {
yazi_fs::path::backslash_to_slash(&url.loc) use yazi_shared::strand::AsStrandDyn;
self.inner.is_match_candidate(&Candidate::from_bytes(
url.loc().as_strand_dyn().backslash_to_slash().encoded_bytes(),
))
} else { } else {
std::borrow::Cow::Borrowed(url.loc.as_path()) self.inner.is_match_candidate(&Candidate::from_bytes(url.loc().encoded_bytes()))
}; }
self.inner.is_match(path)
} }
pub fn match_mime(&self, mime: impl AsRef<str>) -> bool { pub fn match_mime(&self, mime: impl AsRef<str>) -> bool {
@ -144,18 +148,19 @@ impl PatternScheme {
} }
#[inline] #[inline]
fn matches(self, scheme: SchemeRef) -> bool { fn matches(self, kind: SchemeKind) -> bool {
use SchemeRef as S; use SchemeKind as K;
match (self, scheme) {
match (self, kind) {
(Self::Any, _) => true, (Self::Any, _) => true,
(Self::Local, s) => s.is_local(), (Self::Local, s) => s.is_local(),
(Self::Remote, s) => s.is_remote(), (Self::Remote, s) => s.is_remote(),
(Self::Virtual, s) => s.is_virtual(), (Self::Virtual, s) => s.is_virtual(),
(Self::Regular, S::Regular) => true, (Self::Regular, K::Regular) => true,
(Self::Search, S::Search(_)) => true, (Self::Search, K::Search) => true,
(Self::Archive, S::Archive(_)) => true, (Self::Archive, K::Archive) => true,
(Self::Sftp, S::Sftp(_)) => true, (Self::Sftp, K::Sftp) => true,
_ => false, _ => false,
} }

View file

@ -50,7 +50,7 @@ impl Preview {
self.cache_dir = if self.cache_dir.as_os_str().is_empty() { self.cache_dir = if self.cache_dir.as_os_str().is_empty() {
Xdg::cache_dir().to_owned() Xdg::cache_dir().to_owned()
} else if let Some(p) = expand_url(self.cache_dir).into_path() { } else if let Some(p) = expand_url(self.cache_dir).into_local() {
p p
} else { } else {
bail!("[preview].cache_dir must be a path within local filesystem."); bail!("[preview].cache_dir must be a path within local filesystem.");

View file

@ -5,7 +5,7 @@ use hashbrown::HashMap;
use serde::{Deserialize, Deserializer}; use serde::{Deserialize, Deserializer};
use yazi_codegen::DeserializeOver2; use yazi_codegen::DeserializeOver2;
use yazi_fs::File; use yazi_fs::File;
use yazi_shared::{Condition, url::UrlLike}; use yazi_shared::{Condition, strand::StrandLike, url::UrlLike};
use crate::{Color, Icon as I, Pattern, Style}; use crate::{Color, Icon as I, Pattern, Style};
@ -74,7 +74,7 @@ impl Icon {
} }
fn match_by_name(&self, file: &File) -> Option<&I> { fn match_by_name(&self, file: &File) -> Option<&I> {
let name = file.name()?.to_str()?; let name = file.name()?.to_str().ok()?;
if file.is_dir() { if file.is_dir() {
self.dirs.get(name).or_else(|| self.dirs.get(&name.to_ascii_lowercase())) self.dirs.get(name).or_else(|| self.dirs.get(&name.to_ascii_lowercase()))
} else { } else {
@ -87,7 +87,7 @@ impl Icon {
} }
fn match_by_ext(&self, file: &File) -> Option<&I> { fn match_by_ext(&self, file: &File) -> Option<&I> {
let ext = file.url.ext()?.to_str()?; let ext = file.url.ext()?.to_str().ok()?;
self.exts.get(ext).or_else(|| self.exts.get(&ext.to_ascii_lowercase())) self.exts.get(ext).or_else(|| self.exts.get(&ext.to_ascii_lowercase()))
} }
} }

View file

@ -223,7 +223,7 @@ impl Theme {
self.mgr.syntect_theme = self self.mgr.syntect_theme = self
.flavor .flavor
.syntect_path(light) .syntect_path(light)
.or_else(|| expand_url(UrlBuf::from(&self.mgr.syntect_theme)).into_path()) .or_else(|| expand_url(UrlBuf::from(&self.mgr.syntect_theme)).into_local())
.ok_or(anyhow!("[mgr].syntect_theme must be a path within local filesystem"))?; .ok_or(anyhow!("[mgr].syntect_theme must be a path within local filesystem"))?;
Ok(self) Ok(self)

View file

@ -45,7 +45,7 @@ impl ProviderSftp {
fn reshape(&mut self) -> io::Result<()> { fn reshape(&mut self) -> io::Result<()> {
if !self.key_file.as_os_str().is_empty() { if !self.key_file.as_os_str().is_empty() {
self.key_file = expand_url(&self.key_file) self.key_file = expand_url(&self.key_file)
.into_path() .into_local()
.ok_or_else(|| io::Error::other("key_file must be a path within local filesystem"))?; .ok_or_else(|| io::Error::other("key_file must be a path within local filesystem"))?;
} }
@ -56,7 +56,7 @@ impl ProviderSftp {
.unwrap_or_default() .unwrap_or_default()
} else { } else {
expand_url(&self.identity_agent) expand_url(&self.identity_agent)
.into_path() .into_local()
.ok_or_else(|| io::Error::other("identity_agent must be a path within local filesystem"))? .ok_or_else(|| io::Error::other("identity_agent must be a path within local filesystem"))?
}; };

View file

@ -1,9 +1,4 @@
#![allow( #![allow(clippy::if_same_then_else, clippy::len_without_is_empty, clippy::option_map_unit_fn)]
clippy::if_same_then_else,
clippy::len_without_is_empty,
clippy::option_map_unit_fn,
clippy::unit_arg
)]
yazi_macro::mod_pub!(cmp confirm help input mgr notify pick spot tab tasks which); yazi_macro::mod_pub!(cmp confirm help input mgr notify pick spot tab tasks which);

View file

@ -142,23 +142,16 @@ impl Selected {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use yazi_shared::{scheme::SchemeCow, url::UrlCow}; use std::path::Path;
use super::*; use super::*;
fn url(s: &str) -> Url<'_> {
match UrlCow::try_from(s).unwrap() {
UrlCow::Borrowed { loc, scheme: SchemeCow::Borrowed(scheme) } => Url { loc, scheme },
_ => unreachable!(),
}
}
#[test] #[test]
fn test_insert_non_conflicting() { fn test_insert_non_conflicting() {
let mut s = Selected::default(); let mut s = Selected::default();
assert!(s.add(url("/a/b"))); assert!(s.add(Path::new("/a/b")));
assert!(s.add(url("/c/d"))); assert!(s.add(Path::new("/c/d")));
assert_eq!(s.inner.len(), 2); assert_eq!(s.inner.len(), 2);
} }
@ -166,27 +159,27 @@ mod tests {
fn test_insert_conflicting_parent() { fn test_insert_conflicting_parent() {
let mut s = Selected::default(); let mut s = Selected::default();
assert!(s.add(url("/a"))); assert!(s.add(Path::new("/a")));
assert!(!s.add(url("/a/b"))); assert!(!s.add(Path::new("/a/b")));
} }
#[test] #[test]
fn test_insert_conflicting_child() { fn test_insert_conflicting_child() {
let mut s = Selected::default(); let mut s = Selected::default();
assert!(s.add(url("/a/b/c"))); assert!(s.add(Path::new("/a/b/c")));
assert!(!s.add(url("/a/b"))); assert!(!s.add(Path::new("/a/b")));
assert!(s.add(url("/a/b/d"))); assert!(s.add(Path::new("/a/b/d")));
} }
#[test] #[test]
fn test_remove() { fn test_remove() {
let mut s = Selected::default(); let mut s = Selected::default();
assert!(s.add(url("/a/b"))); assert!(s.add(Path::new("/a/b")));
assert!(!s.remove(url("/a/c"))); assert!(!s.remove(Path::new("/a/c")));
assert!(s.remove(url("/a/b"))); assert!(s.remove(Path::new("/a/b")));
assert!(!s.remove(url("/a/b"))); assert!(!s.remove(Path::new("/a/b")));
assert!(s.inner.is_empty()); assert!(s.inner.is_empty());
assert!(s.parents.is_empty()); assert!(s.parents.is_empty());
} }
@ -197,7 +190,11 @@ mod tests {
assert_eq!( assert_eq!(
3, 3,
s.add_same([url("/parent/child1"), url("/parent/child2"), url("/parent/child3")]) s.add_same([
Path::new("/parent/child1"),
Path::new("/parent/child2"),
Path::new("/parent/child3")
])
); );
} }
@ -205,16 +202,16 @@ mod tests {
fn insert_many_with_existing_parent_fails() { fn insert_many_with_existing_parent_fails() {
let mut s = Selected::default(); let mut s = Selected::default();
s.add(url("/parent")); s.add(Path::new("/parent"));
assert_eq!(0, s.add_same([url("/parent/child1"), url("/parent/child2")])); assert_eq!(0, s.add_same([Path::new("/parent/child1"), Path::new("/parent/child2")]));
} }
#[test] #[test]
fn insert_many_with_existing_child_fails() { fn insert_many_with_existing_child_fails() {
let mut s = Selected::default(); let mut s = Selected::default();
s.add(url("/parent/child1")); s.add(Path::new("/parent/child1"));
assert_eq!(2, s.add_same([url("/parent/child1"), url("/parent/child2")])); assert_eq!(2, s.add_same([Path::new("/parent/child1"), Path::new("/parent/child2")]));
} }
#[test] #[test]
@ -228,48 +225,51 @@ mod tests {
fn insert_many_with_parent_as_child_of_another_url() { fn insert_many_with_parent_as_child_of_another_url() {
let mut s = Selected::default(); let mut s = Selected::default();
s.add(url("/parent/child")); s.add(Path::new("/parent/child"));
assert_eq!(0, s.add_same([url("/parent/child/child1"), url("/parent/child/child2")])); assert_eq!(
0,
s.add_same([Path::new("/parent/child/child1"), Path::new("/parent/child/child2")])
);
} }
#[test] #[test]
fn insert_many_with_direct_parent_fails() { fn insert_many_with_direct_parent_fails() {
let mut s = Selected::default(); let mut s = Selected::default();
s.add(url("/a")); s.add(Path::new("/a"));
assert_eq!(0, s.add_same([url("/a/b")])); assert_eq!(0, s.add_same([Path::new("/a/b")]));
} }
#[test] #[test]
fn insert_many_with_nested_child_fails() { fn insert_many_with_nested_child_fails() {
let mut s = Selected::default(); let mut s = Selected::default();
s.add(url("/a/b")); s.add(Path::new("/a/b"));
assert_eq!(0, s.add_same([url("/a")])); assert_eq!(0, s.add_same([Path::new("/a")]));
assert_eq!(1, s.add_same([url("/b"), url("/a")])); assert_eq!(1, s.add_same([Path::new("/b"), Path::new("/a")]));
} }
#[test] #[test]
fn insert_many_sibling_directories_success() { fn insert_many_sibling_directories_success() {
let mut s = Selected::default(); let mut s = Selected::default();
assert_eq!(2, s.add_same([url("/a/b"), url("/a/c")])); assert_eq!(2, s.add_same([Path::new("/a/b"), Path::new("/a/c")]));
} }
#[test] #[test]
fn insert_many_with_grandchild_fails() { fn insert_many_with_grandchild_fails() {
let mut s = Selected::default(); let mut s = Selected::default();
s.add(url("/a/b")); s.add(Path::new("/a/b"));
assert_eq!(0, s.add_same([url("/a/b/c")])); assert_eq!(0, s.add_same([Path::new("/a/b/c")]));
} }
#[test] #[test]
fn test_insert_many_with_remove() { fn test_insert_many_with_remove() {
let mut s = Selected::default(); let mut s = Selected::default();
let child1 = url("/parent/child1"); let child1 = Path::new("/parent/child1");
let child2 = url("/parent/child2"); let child2 = Path::new("/parent/child2");
let child3 = url("/parent/child3"); let child3 = Path::new("/parent/child3");
assert_eq!(3, s.add_same([child1, child2, child3])); assert_eq!(3, s.add_same([child1, child2, child3]));
assert!(s.remove(child1)); assert!(s.remove(child1));

View file

@ -8,9 +8,12 @@ use crate::mgr::Yanked;
impl Tasks { impl Tasks {
pub fn file_cut(&self, src: &Yanked, dest: &UrlBuf, force: bool) { pub fn file_cut(&self, src: &Yanked, dest: &UrlBuf, force: bool) {
for u in src.iter() { for u in src.iter() {
let to = dest.join(u.name().unwrap()); let Some(Ok(to)) = u.name().map(|n| dest.try_join(n)) else {
debug!("file_cut: cannot join {u:?} with {dest:?}");
continue;
};
if force && *u == to { if force && *u == to {
debug!("file_cut: same file, skipping {:?}", to); debug!("file_cut: same file, skip {to:?}");
} else { } else {
self.scheduler.file_cut(u.0.clone(), to, force); self.scheduler.file_cut(u.0.clone(), to, force);
} }
@ -19,9 +22,12 @@ impl Tasks {
pub fn file_copy(&self, src: &Yanked, dest: &UrlBuf, force: bool, follow: bool) { pub fn file_copy(&self, src: &Yanked, dest: &UrlBuf, force: bool, follow: bool) {
for u in src.iter() { for u in src.iter() {
let to = dest.join(u.name().unwrap()); let Some(Ok(to)) = u.name().map(|n| dest.try_join(n)) else {
debug!("file_copy: cannot join {u:?} with {dest:?}");
continue;
};
if force && *u == to { if force && *u == to {
debug!("file_copy: same file, skipping {:?}", to); debug!("file_copy: same file, skip {to:?}");
} else { } else {
self.scheduler.file_copy(u.0.clone(), to, force, follow); self.scheduler.file_copy(u.0.clone(), to, force, follow);
} }
@ -30,9 +36,12 @@ impl Tasks {
pub fn file_link(&self, src: &HashSet<UrlBufCov>, dest: &UrlBuf, relative: bool, force: bool) { pub fn file_link(&self, src: &HashSet<UrlBufCov>, dest: &UrlBuf, relative: bool, force: bool) {
for u in src { for u in src {
let to = dest.join(u.name().unwrap()); let Some(Ok(to)) = u.name().map(|n| dest.try_join(n)) else {
debug!("file_link: cannot join {u:?} with {dest:?}");
continue;
};
if force && *u == to { if force && *u == to {
debug!("file_link: same file, skipping {:?}", to); debug!("file_link: same file, skip {to:?}");
} else { } else {
self.scheduler.file_link(u.0.clone(), to, relative, force); self.scheduler.file_link(u.0.clone(), to, relative, force);
} }
@ -41,9 +50,12 @@ impl Tasks {
pub fn file_hardlink(&self, src: &HashSet<UrlBufCov>, dest: &UrlBuf, force: bool, follow: bool) { pub fn file_hardlink(&self, src: &HashSet<UrlBufCov>, dest: &UrlBuf, force: bool, follow: bool) {
for u in src { for u in src {
let to = dest.join(u.name().unwrap()); let Some(Ok(to)) = u.name().map(|n| dest.try_join(n)) else {
debug!("file_hardlink: cannot join {u:?} with {dest:?}");
continue;
};
if force && *u == to { if force && *u == to {
debug!("file_hardlink: same file, skipping {:?}", to); debug!("file_hardlink: same file, skip {to:?}");
} else { } else {
self.scheduler.file_hardlink(u.0.clone(), to, force, follow); self.scheduler.file_hardlink(u.0.clone(), to, force, follow);
} }

View file

@ -1,21 +1,19 @@
use std::borrow::Cow;
use hashbrown::HashMap; use hashbrown::HashMap;
use mlua::{IntoLua, Lua, Value}; use mlua::{IntoLua, Lua, Value};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use yazi_shared::url::UrlBuf; use yazi_shared::url::{Url, UrlCow};
use super::Ember; use super::Ember;
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
pub struct EmberBulk<'a> { pub struct EmberBulk<'a> {
pub changes: HashMap<Cow<'a, UrlBuf>, Cow<'a, UrlBuf>>, pub changes: HashMap<UrlCow<'a>, UrlCow<'a>>,
} }
impl<'a> EmberBulk<'a> { impl<'a> EmberBulk<'a> {
pub fn borrowed<I>(changes: I) -> Ember<'a> pub fn borrowed<I>(changes: I) -> Ember<'a>
where where
I: Iterator<Item = (&'a UrlBuf, &'a UrlBuf)>, I: Iterator<Item = (Url<'a>, Url<'a>)>,
{ {
Self { changes: changes.map(|(from, to)| (from.into(), to.into())).collect() }.into() Self { changes: changes.map(|(from, to)| (from.into(), to.into())).collect() }.into()
} }
@ -24,10 +22,12 @@ impl<'a> EmberBulk<'a> {
impl EmberBulk<'static> { impl EmberBulk<'static> {
pub fn owned<'a, I>(changes: I) -> Ember<'static> pub fn owned<'a, I>(changes: I) -> Ember<'static>
where where
I: Iterator<Item = (&'a UrlBuf, &'a UrlBuf)>, I: Iterator<Item = (Url<'a>, Url<'a>)>,
{ {
Self { changes: changes.map(|(from, to)| (from.clone().into(), to.clone().into())).collect() } Self {
.into() changes: changes.map(|(from, to)| (from.to_owned().into(), to.to_owned().into())).collect(),
}
.into()
} }
} }

View file

@ -4,7 +4,7 @@ use mlua::Function;
use parking_lot::RwLock; use parking_lot::RwLock;
use yazi_boot::BOOT; use yazi_boot::BOOT;
use yazi_fs::FolderStage; use yazi_fs::FolderStage;
use yazi_shared::{Id, RoCell, url::{UrlBuf, UrlBufCov}}; use yazi_shared::{Id, RoCell, url::{Url, UrlBuf, UrlBufCov}};
use crate::{Client, ID, PEERS, ember::{BodyMoveItem, Ember, EmberBulk, EmberHi}}; use crate::{Client, ID, PEERS, ember::{BodyMoveItem, Ember, EmberBulk, EmberHi}};
@ -123,7 +123,7 @@ impl Pubsub {
pub fn pub_after_bulk<'a, I>(changes: I) -> Result<()> pub fn pub_after_bulk<'a, I>(changes: I) -> Result<()>
where where
I: Iterator<Item = (&'a UrlBuf, &'a UrlBuf)> + Clone, I: Iterator<Item = (Url<'a>, Url<'a>)> + Clone,
{ {
if BOOT.local_events.contains("bulk") { if BOOT.local_events.contains("bulk") {
EmberBulk::borrowed(changes.clone()).with_receiver(*ID).flush()?; EmberBulk::borrowed(changes.clone()).with_receiver(*ID).flush()?;

View file

@ -58,7 +58,7 @@ impl State {
return Ok(()); return Ok(());
} }
Local.create_dir_all(&BOOT.state_dir).await?; Local::regular(&BOOT.state_dir).create_dir_all().await?;
let mut buf = BufWriter::new( let mut buf = BufWriter::new(
Gate::default() Gate::default()
.write(true) .write(true)
@ -79,7 +79,7 @@ impl State {
} }
async fn load(&self) -> Result<()> { async fn load(&self) -> Result<()> {
let mut file = BufReader::new(Local.open(BOOT.state_dir.join(".dds")).await?); let mut file = BufReader::new(Local::regular(&BOOT.state_dir.join(".dds")).open().await?);
let mut buf = String::new(); let mut buf = String::new();
let mut inner = HashMap::new(); let mut inner = HashMap::new();
@ -103,7 +103,7 @@ impl State {
} }
async fn skip(&self) -> Result<bool> { async fn skip(&self) -> Result<bool> {
let cha = Local.symlink_metadata(BOOT.state_dir.join(".dds")).await?; let cha = Local::regular(&BOOT.state_dir.join(".dds")).symlink_metadata().await?;
let modified = cha.mtime_dur()?.as_micros(); let modified = cha.mtime_dur()?.as_micros();
Ok(modified >= self.last.load(Ordering::Relaxed) as u128) Ok(modified >= self.last.load(Ordering::Relaxed) as u128)
} }

View file

@ -40,7 +40,7 @@ impl Stream {
let p = Self::socket_file(); let p = Self::socket_file();
yazi_fs::provider::local::Local.remove_file(&p).await.ok(); yazi_fs::provider::local::Local::regular(&p).remove_file().await.ok();
tokio::net::UnixListener::bind(p) tokio::net::UnixListener::bind(p)
} }

View file

@ -3,7 +3,7 @@ use yazi_actor::Ctx;
use yazi_boot::BOOT; use yazi_boot::BOOT;
use yazi_macro::act; use yazi_macro::act;
use yazi_parser::{VoidOpt, mgr::CdSource}; use yazi_parser::{VoidOpt, mgr::CdSource};
use yazi_shared::{data::Data, path::PathBufLike, url::UrlLike}; use yazi_shared::{data::Data, strand::StrandBufLike, url::UrlLike};
use crate::app::App; use crate::app::App;
@ -20,8 +20,8 @@ impl App {
if file.is_empty() { if file.is_empty() {
act!(mgr:cd, cx, (BOOT.cwds[i].clone(), CdSource::Tab))?; act!(mgr:cd, cx, (BOOT.cwds[i].clone(), CdSource::Tab))?;
} else { } else if let Ok(u) = BOOT.cwds[i].try_join(file) {
act!(mgr:reveal, cx, (BOOT.cwds[i].join(file), CdSource::Tab))?; act!(mgr:reveal, cx, (u, CdSource::Tab))?;
} }
} }

View file

@ -26,13 +26,13 @@ impl App {
async fn cwd_to_file(&self, no: bool) { async fn cwd_to_file(&self, no: bool) {
if let Some(p) = ARGS.cwd_file.as_ref().filter(|_| !no) { if let Some(p) = ARGS.cwd_file.as_ref().filter(|_| !no) {
let cwd = self.core.mgr.cwd().os_str(); let cwd = self.core.mgr.cwd().os_str();
Local.write(p, cwd.as_encoded_bytes()).await.ok(); Local::regular(p).write(cwd.as_encoded_bytes()).await.ok();
} }
} }
async fn selected_to_file(&self, selected: Option<OsString>) { async fn selected_to_file(&self, selected: Option<OsString>) {
if let (Some(s), Some(p)) = (selected, &ARGS.chooser_file) { if let (Some(s), Some(p)) = (selected, &ARGS.chooser_file) {
Local.write(p, s.as_encoded_bytes()).await.ok(); Local::regular(p).write(s.as_encoded_bytes()).await.ok();
} }
} }
} }

View file

@ -4,6 +4,7 @@ use ratatui::{buffer::Buffer, layout::Rect, widgets::{Block, BorderType, List, L
use yazi_adapter::Dimension; use yazi_adapter::Dimension;
use yazi_config::{THEME, popup::{Offset, Position}}; use yazi_config::{THEME, popup::{Offset, Position}};
use yazi_core::Core; use yazi_core::Core;
use yazi_shared::strand::{AsStrand, StrandLike};
pub(crate) struct Cmp<'a> { pub(crate) struct Cmp<'a> {
core: &'a Core, core: &'a Core,
@ -25,7 +26,7 @@ impl Widget for Cmp<'_> {
let icon = if x.is_dir { &THEME.cmp.icon_folder } else { &THEME.cmp.icon_file }; let icon = if x.is_dir { &THEME.cmp.icon_folder } else { &THEME.cmp.icon_file };
let slash = if x.is_dir { MAIN_SEPARATOR_STR } else { "" }; let slash = if x.is_dir { MAIN_SEPARATOR_STR } else { "" };
let mut item = ListItem::new(format!(" {icon} {}{slash}", x.name.display())); let mut item = ListItem::new(format!(" {icon} {}{slash}", x.name.as_strand().display()));
if i == self.core.cmp.rel_cursor() { if i == self.core.cmp.rel_cursor() {
item = item.style(THEME.cmp.active); item = item.style(THEME.cmp.active);
} else { } else {

View file

@ -2,6 +2,7 @@ use std::sync::atomic::Ordering;
use anyhow::Result; use anyhow::Result;
use crossterm::event::KeyEvent; use crossterm::event::KeyEvent;
use tracing::warn;
use yazi_config::keymap::Key; use yazi_config::keymap::Key;
use yazi_macro::{act, emit, succ}; use yazi_macro::{act, emit, succ};
use yazi_shared::{data::Data, event::{CmdCow, Event, NEED_RENDER}}; use yazi_shared::{data::Data, event::{CmdCow, Event, NEED_RENDER}};
@ -20,7 +21,7 @@ impl<'a> Dispatcher<'a> {
#[inline] #[inline]
pub(super) fn dispatch(&mut self, event: Event) -> Result<()> { pub(super) fn dispatch(&mut self, event: Event) -> Result<()> {
// FIXME: handle errors // FIXME: handle errors
_ = match event { let result = match event {
Event::Call(cmd) => self.dispatch_call(cmd), Event::Call(cmd) => self.dispatch_call(cmd),
Event::Seq(cmds) => self.dispatch_seq(cmds), Event::Seq(cmds) => self.dispatch_seq(cmds),
Event::Render => self.dispatch_render(), Event::Render => self.dispatch_render(),
@ -30,6 +31,10 @@ impl<'a> Dispatcher<'a> {
Event::Paste(str) => self.dispatch_paste(str), Event::Paste(str) => self.dispatch_paste(str),
Event::Quit(opt) => act!(quit, self.app, opt), Event::Quit(opt) => act!(quit, self.app, opt),
}; };
if let Err(err) = result {
warn!("Event dispatch error: {err:?}");
}
Ok(()) Ok(())
} }

View file

@ -1,4 +1,4 @@
#![allow(clippy::if_same_then_else, clippy::unit_arg)] #![allow(clippy::if_same_then_else)]
#[cfg(all(not(target_os = "macos"), not(target_os = "windows")))] #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
#[global_allocator] #[global_allocator]

View file

@ -1,8 +1,8 @@
use std::{ffi::OsStr, fs::Metadata, ops::Deref, time::{Duration, SystemTime, UNIX_EPOCH}}; use std::{fs::Metadata, ops::Deref, time::{Duration, SystemTime, UNIX_EPOCH}};
use anyhow::bail; use anyhow::bail;
use yazi_macro::{unix_either, win_either}; use yazi_macro::{unix_either, win_either};
use yazi_shared::url::AsUrl; use yazi_shared::{strand::AsStrand, url::AsUrl};
use super::ChaKind; use super::ChaKind;
use crate::cha::{ChaMode, ChaType}; use crate::cha::{ChaMode, ChaType};
@ -48,7 +48,10 @@ impl Default for Cha {
impl Cha { impl Cha {
#[inline] #[inline]
pub fn new(name: &OsStr, meta: Metadata) -> Self { pub fn new<T>(name: T, meta: Metadata) -> Self
where
T: AsStrand,
{
Self::from_bare(&meta).attach(ChaKind::hidden(name, &meta)) Self::from_bare(&meta).attach(ChaKind::hidden(name, &meta))
} }

View file

@ -1,6 +1,7 @@
use std::{ffi::OsStr, fs::Metadata}; use std::fs::Metadata;
use bitflags::bitflags; use bitflags::bitflags;
use yazi_shared::strand::AsStrand;
bitflags! { bitflags! {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@ -14,13 +15,16 @@ bitflags! {
impl ChaKind { impl ChaKind {
#[inline] #[inline]
pub(super) fn hidden(_name: &OsStr, _meta: &Metadata) -> Self { pub(super) fn hidden<T>(_name: T, _meta: &Metadata) -> Self
where
T: AsStrand,
{
let mut me = Self::empty(); let mut me = Self::empty();
#[cfg(unix)] #[cfg(unix)]
{ {
use std::os::unix::ffi::OsStrExt; use yazi_shared::strand::StrandLike;
if _name.as_bytes().starts_with(b".") { if _name.as_strand().starts_with(".") {
me |= Self::HIDDEN; me |= Self::HIDDEN;
} }
} }

View file

@ -28,10 +28,7 @@ impl Default for Cwd {
} }
impl Cwd { impl Cwd {
pub fn path(&self) -> PathBuf { pub fn path(&self) -> PathBuf { self.0.load().as_url().unified_path().into_owned() }
let url = self.0.load();
url.cache().unwrap_or_else(|| url.loc.to_path())
}
pub fn set(&self, url: &UrlBuf, callback: fn()) -> bool { pub fn set(&self, url: &UrlBuf, callback: fn()) -> bool {
if !url.is_absolute() { if !url.is_absolute() {
@ -50,7 +47,7 @@ impl Cwd {
use std::{io::ErrorKind::{AlreadyExists, NotADirectory, NotFound}, path::Component as C}; use std::{io::ErrorKind::{AlreadyExists, NotADirectory, NotFound}, path::Component as C};
let Some(cache) = url.cache() else { let Some(cache) = url.cache() else {
return url.loc.as_path().into(); return url.unified_path();
}; };
if !matches!(std::fs::create_dir_all(&cache), Err(e) if e.kind() == NotADirectory || e.kind() == AlreadyExists) if !matches!(std::fs::create_dir_all(&cache), Err(e) if e.kind() == NotADirectory || e.kind() == AlreadyExists)

View file

@ -1,6 +1,7 @@
use std::{ffi::OsStr, hash::{Hash, Hasher}, ops::Deref, path::{Path, PathBuf}}; use std::{hash::{Hash, Hasher}, ops::Deref, path::Path};
use yazi_shared::{path::PathDyn, url::{UrlBuf, UrlLike}}; use anyhow::Result;
use yazi_shared::{loc::Loc, path::{AsPathDyn, PathBufDyn, PathDyn}, strand::Strand, url::{Url, UrlBuf, UrlLike}};
use crate::cha::{Cha, ChaType}; use crate::cha::{Cha, ChaType};
@ -8,7 +9,7 @@ use crate::cha::{Cha, ChaType};
pub struct File { pub struct File {
pub url: UrlBuf, pub url: UrlBuf,
pub cha: Cha, pub cha: Cha,
pub link_to: Option<PathBuf>, pub link_to: Option<PathBufDyn>,
} }
impl Deref for File { impl Deref for File {
@ -26,8 +27,8 @@ impl File {
} }
#[inline] #[inline]
pub fn chdir(&self, wd: &Path) -> Self { pub fn chdir(&self, wd: &Path) -> Result<Self> {
Self { url: self.url.rebase(wd), cha: self.cha, link_to: self.link_to.clone() } Ok(Self { url: self.url.rebase(wd)?, cha: self.cha, link_to: self.link_to.clone() })
} }
} }
@ -43,10 +44,27 @@ impl File {
pub fn urn(&self) -> PathDyn<'_> { self.url.urn() } pub fn urn(&self) -> PathDyn<'_> { self.url.urn() }
#[inline] #[inline]
pub fn name(&self) -> Option<&OsStr> { self.url.name() } pub fn name(&self) -> Option<Strand<'_>> { self.url.name() }
#[inline] #[inline]
pub fn stem(&self) -> Option<&OsStr> { self.url.stem() } pub fn stem(&self) -> Option<Strand<'_>> { self.url.stem() }
pub fn link_to_url(&self) -> Option<Url<'_>> {
let to = self.link_to.as_ref()?.as_path_dyn();
let kind = self.url.kind();
Some(match &self.url {
UrlBuf::Regular(_) => Url::Regular(Loc::bare(to.as_os().ok()?)),
UrlBuf::Search { domain, .. } => {
Url::Search { loc: Loc::saturated(to.as_os().ok()?, kind), domain }
}
UrlBuf::Archive { domain, .. } => {
Url::Archive { loc: Loc::saturated(to.as_os().ok()?, kind), domain }
}
UrlBuf::Sftp { domain, .. } => {
Url::Sftp { loc: Loc::saturated(to.as_os().ok()?, kind), domain }
}
})
}
} }
impl Hash for File { impl Hash for File {

View file

@ -1,7 +1,7 @@
use std::{mem, ops::{Deref, DerefMut, Not}}; use std::{mem, ops::{Deref, DerefMut, Not}};
use hashbrown::{HashMap, HashSet}; use hashbrown::{HashMap, HashSet};
use yazi_shared::{Id, path::{PathBufDyn, PathBufLike, PathDyn, PathLike}}; use yazi_shared::{Id, path::{PathBufDyn, PathDyn, PathLike}};
use super::{FilesSorter, Filter}; use super::{FilesSorter, Filter};
use crate::{FILES_TICKET, File, SortBy}; use crate::{FILES_TICKET, File, SortBy};
@ -121,6 +121,7 @@ impl Files {
#[cfg(unix)] #[cfg(unix)]
pub fn update_deleting(&mut self, urns: HashSet<PathBufDyn>) -> Vec<usize> { pub fn update_deleting(&mut self, urns: HashSet<PathBufDyn>) -> Vec<usize> {
use yazi_shared::path::PathBufLike;
if urns.is_empty() { if urns.is_empty() {
return vec![]; return vec![];
} }

View file

@ -1,8 +1,8 @@
use std::{ffi::OsStr, fmt::Display, ops::Range}; use std::{fmt::Display, ops::Range};
use anyhow::Result; use anyhow::Result;
use regex::bytes::{Regex, RegexBuilder}; use regex::bytes::{Regex, RegexBuilder};
use yazi_shared::{event::Cmd, path::{AsPath, PathLike}}; use yazi_shared::{event::Cmd, strand::{AsStrand, StrandLike}};
pub struct Filter { pub struct Filter {
raw: String, raw: String,
@ -26,14 +26,14 @@ impl Filter {
#[allow(private_bounds)] #[allow(private_bounds)]
pub fn matches<T>(&self, name: T) -> bool pub fn matches<T>(&self, name: T) -> bool
where where
T: AsPath, T: AsStrand,
{ {
self.regex.is_match(name.as_path().encoded_bytes()) self.regex.is_match(name.as_strand().encoded_bytes())
} }
#[inline] #[inline]
pub fn highlighted(&self, name: impl AsRef<OsStr>) -> Option<Vec<Range<usize>>> { pub fn highlighted(&self, name: impl AsStrand) -> Option<Vec<Range<usize>>> {
self.regex.find(name.as_ref().as_encoded_bytes()).map(|m| vec![m.range()]) self.regex.find(name.as_strand().encoded_bytes()).map(|m| vec![m.range()])
} }
} }

View file

@ -1,4 +1,4 @@
#![allow(clippy::if_same_then_else, clippy::option_map_unit_fn, clippy::unit_arg)] #![allow(clippy::if_same_then_else, clippy::option_map_unit_fn)]
yazi_macro::mod_pub!(cha error mounts path provider); yazi_macro::mod_pub!(cha error mounts path provider);

View file

@ -1,5 +1,6 @@
use std::path::Path; use std::path::Path;
use anyhow::Result;
use hashbrown::{HashMap, HashSet}; use hashbrown::{HashMap, HashSet};
use yazi_macro::relay; use yazi_macro::relay;
use yazi_shared::{Id, Ids, path::{PathBufDyn, PathLike}, url::{UrlBuf, UrlLike}}; use yazi_shared::{Id, Ids, path::{PathBufDyn, PathLike}, url::{UrlBuf, UrlLike}};
@ -98,16 +99,21 @@ impl FilesOp {
} }
} }
pub fn chdir(&self, wd: &Path) -> Self { pub fn chdir(&self, wd: &Path) -> Result<Self> {
macro_rules! files { macro_rules! files {
($files:expr) => {{ $files.iter().map(|file| file.chdir(wd)).collect() }}; ($files:expr) => {{ $files.iter().map(|file| file.chdir(wd)).collect::<Result<_>>()? }};
} }
macro_rules! map { macro_rules! map {
($map:expr) => {{ $map.iter().map(|(urn, file)| (urn.clone(), file.chdir(wd))).collect() }}; ($map:expr) => {{
$map
.iter()
.map(|(urn, file)| file.chdir(wd).map(|file| (urn.clone(), file)))
.collect::<Result<_>>()?
}};
} }
let w = UrlBuf::from(wd); let w = UrlBuf::from(wd);
match self { Ok(match self {
Self::Full(_, files, cha) => Self::Full(w, files!(files), *cha), Self::Full(_, files, cha) => Self::Full(w, files!(files), *cha),
Self::Part(_, files, ticket) => Self::Part(w, files!(files), *ticket), Self::Part(_, files, ticket) => Self::Part(w, files!(files), *ticket),
Self::Done(_, cha, ticket) => Self::Done(w, *cha, *ticket), Self::Done(_, cha, ticket) => Self::Done(w, *cha, *ticket),
@ -118,16 +124,18 @@ impl FilesOp {
Self::Deleting(_, urns) => Self::Deleting(w, urns.clone()), Self::Deleting(_, urns) => Self::Deleting(w, urns.clone()),
Self::Updating(_, map) => Self::Updating(w, map!(map)), Self::Updating(_, map) => Self::Updating(w, map!(map)),
Self::Upserting(_, map) => Self::Upserting(w, map!(map)), Self::Upserting(_, map) => Self::Upserting(w, map!(map)),
} })
} }
pub fn diff_recoverable(&self, contains: impl Fn(&UrlBuf) -> bool) -> (Vec<UrlBuf>, Vec<UrlBuf>) { pub fn diff_recoverable(&self, contains: impl Fn(&UrlBuf) -> bool) -> (Vec<UrlBuf>, Vec<UrlBuf>) {
match self { match self {
Self::Deleting(cwd, urns) => (urns.iter().map(|u| cwd.join(u)).collect(), vec![]), Self::Deleting(cwd, urns) => {
(urns.iter().filter_map(|u| cwd.try_join(u).ok()).collect(), vec![])
}
Self::Updating(cwd, urns) | Self::Upserting(cwd, urns) => urns Self::Updating(cwd, urns) | Self::Upserting(cwd, urns) => urns
.iter() .iter()
.filter(|&(u, f)| u != f.urn()) .filter(|&(u, f)| u != f.urn())
.map(|(u, f)| (cwd.join(u), f)) .filter_map(|(u, f)| cwd.try_join(u).ok().map(|u| (u, f)))
.filter(|(u, _)| contains(u)) .filter(|(u, _)| contains(u))
.map(|(u, f)| (u, f.url_owned())) .map(|(u, f)| (u, f.url_owned()))
.unzip(), .unzip(),

View file

@ -1,21 +1,33 @@
use std::path::{Path, PathBuf}; use std::path::PathBuf;
use yazi_shared::{loc::LocBuf, url::{UrlBuf, UrlCow}}; use yazi_shared::{loc::LocBuf, path::{PathDyn, PathLike}, pool::InternStr, url::{AsUrl, Url, UrlBuf, UrlCow, UrlLike}};
pub fn clean_url<'a>(url: impl Into<UrlCow<'a>>) -> UrlBuf { pub fn clean_url<'a>(url: impl Into<UrlCow<'a>>) -> UrlBuf {
let cow: UrlCow = url.into(); let cow: UrlCow = url.into();
let (path, uri, urn) = clean_path_impl( let (path, uri, urn) = clean_path_impl(
&cow.loc(), cow.loc(),
cow.loc().base().components().count(), cow.base().components().count() - 1,
cow.loc().trail().components().count(), cow.trail().components().count() - 1,
); );
let loc = match cow.as_url() {
LocBuf::<PathBuf>::with(path, uri, urn).expect("Failed to create Loc from cleaned path"); Url::Regular(_) => UrlBuf::Regular(path.into()),
UrlBuf { loc, scheme: cow.into_scheme().into() } Url::Search { domain, .. } => UrlBuf::Search {
loc: LocBuf::<PathBuf>::with(path, uri, urn).expect("create Loc from cleaned path"),
domain: domain.intern(),
},
Url::Archive { domain, .. } => UrlBuf::Archive {
loc: LocBuf::<PathBuf>::with(path, uri, urn).expect("create Loc from cleaned path"),
domain: domain.intern(),
},
Url::Sftp { domain, .. } => UrlBuf::Sftp {
loc: LocBuf::<PathBuf>::with(path, uri, urn).expect("create Loc from cleaned path"),
domain: domain.intern(),
},
}
} }
fn clean_path_impl(path: &Path, base: usize, trail: usize) -> (PathBuf, usize, usize) { fn clean_path_impl(path: PathDyn, base: usize, trail: usize) -> (PathBuf, usize, usize) {
use std::path::Component::*; use std::path::Component::*;
let mut out = vec![]; let mut out = vec![];

View file

@ -1,6 +1,6 @@
use std::{borrow::Cow, ffi::{OsStr, OsString}, path::{Path, PathBuf}}; use std::{borrow::Cow, path::PathBuf};
use yazi_shared::{loc::LocBuf, path::PathLike, url::{AsUrl, Url, UrlBuf, UrlCow}}; use yazi_shared::{FromWtf8Vec, loc::LocBuf, path::{AsPath, PathBufDyn, PathCow, PathDyn, PathLike}, pool::InternStr, url::{AsUrl, Url, UrlBuf, UrlCow, UrlLike}};
use crate::{CWD, path::clean_url}; use crate::{CWD, path::clean_url};
@ -10,33 +10,44 @@ pub fn expand_url<'a>(url: impl Into<UrlCow<'a>>) -> UrlBuf {
} }
fn expand_url_impl<'a>(url: Url<'a>) -> UrlCow<'a> { fn expand_url_impl<'a>(url: Url<'a>) -> UrlCow<'a> {
let (o_base, o_rest, o_urn) = url.loc.triple(); let (o_base, o_rest, o_urn) = url.triple();
let n_base = expand_variables(o_base); let n_base = expand_variables(o_base);
let n_rest = expand_variables(o_rest); let n_rest = expand_variables(o_rest);
let n_urn = expand_variables(o_urn); let n_urn = expand_variables(o_urn);
let rest_diff = n_rest.components().count() as isize - o_rest.components().count() as isize; let rest_diff =
let urn_diff = n_urn.components().count() as isize - o_urn.components().count() as isize; n_rest.as_path().components().count() as isize - o_rest.components().count() as isize;
let urn_diff =
n_urn.as_path().components().count() as isize - o_urn.components().count() as isize;
let uri_count = url.uri().components().count() as isize; let uri_count = url.uri().components().count() as isize;
let urn_count = url.urn().components().count() as isize; let urn_count = url.urn().components().count() as isize;
let mut path = PathBufDyn::with_capacity(
url.kind(),
n_base.as_path().len() + n_rest.as_path().len() + n_urn.as_path().len(),
);
path.try_extend([n_base, n_rest, n_urn]).expect("extend original parts should not fail");
let loc = LocBuf::<PathBuf>::with( let loc = LocBuf::<PathBuf>::with(
PathBuf::from_iter([n_base, n_rest, n_urn]), path.into_os().expect("Failed to convert PathBufDyn to PathBuf"),
(uri_count + rest_diff + urn_diff) as usize, (uri_count + rest_diff + urn_diff) as usize,
(urn_count + urn_diff) as usize, (urn_count + urn_diff) as usize,
) )
.expect("Failed to create Loc from expanded path"); .expect("Failed to create Loc from expanded path");
let url = UrlBuf { loc, scheme: url.scheme.into() }; let expanded = match url {
match absolute_url(url.as_url()) { Url::Regular(_) => UrlBuf::Regular(loc),
UrlCow::Borrowed { .. } => url.into(), Url::Search { domain, .. } => UrlBuf::Search { loc, domain: domain.intern() },
c @ UrlCow::Owned { .. } => c.into_owned().into(), Url::Archive { domain, .. } => UrlBuf::Archive { loc, domain: domain.intern() },
} Url::Sftp { domain, .. } => UrlBuf::Sftp { loc, domain: domain.intern() },
};
absolute_url(expanded)
} }
fn expand_variables(p: &Path) -> Cow<'_, Path> { fn expand_variables<'a>(p: PathDyn<'a>) -> PathCow<'a> {
// ${HOME} or $HOME // ${HOME} or $HOME
#[cfg(unix)] #[cfg(unix)]
let re = regex::bytes::Regex::new(r"\$(?:\{([^}]+)\}|([a-zA-Z\d_]+))").unwrap(); let re = regex::bytes::Regex::new(r"\$(?:\{([^}]+)\}|([a-zA-Z\d_]+))").unwrap();
@ -45,7 +56,7 @@ fn expand_variables(p: &Path) -> Cow<'_, Path> {
#[cfg(windows)] #[cfg(windows)]
let re = regex::bytes::Regex::new(r"%([^%]+)%").unwrap(); let re = regex::bytes::Regex::new(r"%([^%]+)%").unwrap();
let b = p.as_os_str().as_encoded_bytes(); let b = p.encoded_bytes();
let b = re.replace_all(b, |caps: &regex::bytes::Captures| { let b = re.replace_all(b, |caps: &regex::bytes::Captures| {
let name = caps.get(2).or_else(|| caps.get(1)).unwrap(); let name = caps.get(2).or_else(|| caps.get(1)).unwrap();
str::from_utf8(name.as_bytes()) str::from_utf8(name.as_bytes())
@ -54,51 +65,58 @@ fn expand_variables(p: &Path) -> Cow<'_, Path> {
.map_or_else(|| caps.get(0).unwrap().as_bytes().to_owned(), |s| s.into_encoded_bytes()) .map_or_else(|| caps.get(0).unwrap().as_bytes().to_owned(), |s| s.into_encoded_bytes())
}); });
unsafe { match (b, p) {
match b { (Cow::Borrowed(_), _) => p.into(),
Cow::Borrowed(b) => Path::new(OsStr::from_encoded_bytes_unchecked(b)).into(), (Cow::Owned(b), PathDyn::Os(_)) => {
Cow::Owned(b) => PathBuf::from(OsString::from_encoded_bytes_unchecked(b)).into(), PathBufDyn::Os(std::path::PathBuf::from_wtf8_vec(b).expect("valid WTF-8 path")).into()
} }
} }
} }
pub fn absolute_url<'a>(url: Url<'a>) -> UrlCow<'a> { pub fn absolute_url<'a>(url: impl Into<UrlCow<'a>>) -> UrlCow<'a> { absolute_url_impl(url.into()) }
if url.scheme.is_virtual() {
fn absolute_url_impl<'a>(url: UrlCow<'a>) -> UrlCow<'a> {
if url.kind().is_virtual() {
return url.into(); return url.into();
} }
let b = url.loc.as_os_str().as_encoded_bytes(); let path = url.loc().as_os().expect("must be a local path");
if cfg!(windows) && b.len() == 2 && b[1] == b':' && b[0].is_ascii_alphabetic() { let b = path.as_os_str().as_encoded_bytes();
let loc = LocBuf::<PathBuf>::with(
let loc = if cfg!(windows) && b.len() == 2 && b[1] == b':' && b[0].is_ascii_alphabetic() {
LocBuf::<PathBuf>::with(
format!(r"{}:\", b[0].to_ascii_uppercase() as char).into(), format!(r"{}:\", b[0].to_ascii_uppercase() as char).into(),
if url.has_base() { 0 } else { 2 }, if url.has_base() { 0 } else { 2 },
if url.has_trail() { 0 } else { 2 }, if url.has_trail() { 0 } else { 2 },
) )
.expect("Failed to create Loc from drive letter"); .expect("Failed to create Loc from drive letter")
UrlBuf { loc, scheme: url.scheme.into() }.into() } else if let Ok(rest) = path.strip_prefix("~/")
} else if let Some(rest) = url.loc.strip_prefix("~/")
&& let Some(home) = dirs::home_dir() && let Some(home) = dirs::home_dir()
&& home.is_absolute() && home.is_absolute()
{ {
let add = home.components().count() - 1; // Home root ("~") has offset by the absolute root ("/") let add = home.components().count() - 1; // Home root ("~") has offset by the absolute root ("/")
let loc = LocBuf::<PathBuf>::with( LocBuf::<PathBuf>::with(
home.join(rest), home.join(rest),
url.uri().components().count() + if url.has_base() { 0 } else { add }, url.uri().components().count() + if url.has_base() { 0 } else { add },
url.urn().components().count() + if url.has_trail() { 0 } else { add }, url.urn().components().count() + if url.has_trail() { 0 } else { add },
) )
.expect("Failed to create Loc from home directory"); .expect("Failed to create Loc from home directory")
UrlBuf { loc, scheme: url.scheme.into() }.into()
} else if !url.is_absolute() { } else if !url.is_absolute() {
let cwd = CWD.path(); let cwd = CWD.path();
let loc = LocBuf::<PathBuf>::with( LocBuf::<PathBuf>::with(
cwd.join(url.loc), cwd.join(path),
url.uri().components().count(), url.uri().components().count(),
url.urn().components().count(), url.urn().components().count(),
) )
.expect("Failed to create Loc from relative path"); .expect("Failed to create Loc from relative path")
UrlBuf { loc, scheme: url.scheme.into() }.into()
} else { } else {
url.into() return url;
};
match url.as_url() {
Url::Regular(_) => UrlBuf::Regular(loc).into(),
Url::Search { domain, .. } => UrlBuf::Search { loc, domain: domain.intern() }.into(),
Url::Archive { .. } | Url::Sftp { .. } => unreachable!(),
} }
} }

View file

@ -12,28 +12,6 @@ pub fn skip_url(url: &UrlBuf, n: usize) -> Cow<'_, OsStr> {
it.os_str() it.os_str()
} }
#[cfg(windows)]
pub fn backslash_to_slash(p: &std::path::Path) -> Cow<'_, std::path::Path> {
use std::{ffi::OsString, path::PathBuf};
let bytes = p.as_os_str().as_encoded_bytes();
// Fast path to skip if there are no backslashes
let skip_len = bytes.iter().take_while(|&&b| b != b'\\').count();
if skip_len >= bytes.len() {
return Cow::Borrowed(p);
}
let (skip, rest) = bytes.split_at(skip_len);
let mut out = Vec::new();
out.try_reserve_exact(bytes.len()).unwrap_or_else(|_| panic!());
out.extend(skip);
for &b in rest {
out.push(if b == b'\\' { b'/' } else { b });
}
Cow::Owned(PathBuf::from(unsafe { OsString::from_encoded_bytes_unchecked(out) }))
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use yazi_shared::url::{AsUrl, UrlCow}; use yazi_shared::url::{AsUrl, UrlCow};

View file

@ -1,7 +1,7 @@
use std::{borrow::Cow, path::{Path, PathBuf}}; use std::{borrow::Cow, path::{Path, PathBuf}};
use percent_encoding::{AsciiSet, CONTROLS, percent_decode, percent_encode}; use percent_encoding::{AsciiSet, CONTROLS, percent_decode, percent_encode};
use yazi_shared::loc::Loc; use yazi_shared::path::PathDyn;
const SET: &AsciiSet = const SET: &AsciiSet =
&CONTROLS.add(b'"').add(b'*').add(b':').add(b'<').add(b'>').add(b'?').add(b'\\').add(b'|'); &CONTROLS.add(b'"').add(b'*').add(b':').add(b'<').add(b'>').add(b'?').add(b'\\').add(b'|');
@ -28,8 +28,16 @@ impl PercentEncoding for Path {
} }
} }
impl PercentEncoding for Loc<'_> { impl PercentEncoding for PathDyn<'_> {
fn percent_encode(&self) -> Cow<'_, Path> { self.as_path().percent_encode() } fn percent_encode(&self) -> Cow<'_, Path> {
match self {
PathDyn::Os(p) => p.percent_encode(),
}
}
fn percent_decode(&self) -> Cow<'_, [u8]> { self.as_path().percent_decode() } fn percent_decode(&self) -> Cow<'_, [u8]> {
match self {
PathDyn::Os(p) => p.percent_decode(),
}
}
} }

View file

@ -1,19 +1,17 @@
use std::{borrow::Cow, path::{Path, PathBuf}}; use std::path::PathBuf;
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use yazi_shared::{loc::LocBuf, url::{UrlBuf, UrlCow, UrlLike}}; use yazi_shared::{path::PathBufDyn, url::{UrlCow, UrlLike}};
pub fn path_relative_to<'a>( pub fn url_relative_to<'a, 'b, U, V>(from: U, to: V) -> Result<UrlCow<'b>>
from: impl AsRef<Path>, where
to: &'a impl AsRef<Path>, U: Into<UrlCow<'a>>,
) -> Result<Cow<'a, Path>> { V: Into<UrlCow<'b>>,
Ok(match url_relative_to(from.as_ref().into(), to.as_ref().into())? { {
UrlCow::Borrowed { loc, .. } => Cow::Borrowed(loc.as_path()), url_relative_to_(from.into(), to.into())
UrlCow::Owned { loc, .. } => Cow::Owned(loc.into_path()),
})
} }
pub(super) fn url_relative_to<'a>(from: UrlCow<'_>, to: UrlCow<'a>) -> Result<UrlCow<'a>> { fn url_relative_to_<'a>(from: UrlCow<'_>, to: UrlCow<'a>) -> Result<UrlCow<'a>> {
use yazi_shared::url::Component::*; use yazi_shared::url::Component::*;
if from.is_absolute() != to.is_absolute() { if from.is_absolute() != to.is_absolute() {
@ -25,7 +23,7 @@ pub(super) fn url_relative_to<'a>(from: UrlCow<'_>, to: UrlCow<'a>) -> Result<Ur
} }
if from.covariant(&to) { if from.covariant(&to) {
return Ok(UrlBuf { loc: LocBuf::<PathBuf>::zeroed("."), scheme: to.scheme().into() }.into()); return UrlCow::try_from((to.scheme().zeroed().to_owned(), PathBufDyn::with(to.kind(), ".")?));
} }
let (mut f_it, mut t_it) = (from.components(), to.components()); let (mut f_it, mut t_it) = (from.components(), to.components());
@ -46,6 +44,7 @@ pub(super) fn url_relative_to<'a>(from: UrlCow<'_>, to: UrlCow<'a>) -> Result<Ur
let dots = f_head.into_iter().chain(f_it).map(|_| ParentDir); let dots = f_head.into_iter().chain(f_it).map(|_| ParentDir);
let rest = t_head.into_iter().chain(t_it); let rest = t_head.into_iter().chain(t_it);
let buf: PathBuf = dots.chain(rest).collect(); let buf: PathBuf = dots.chain(rest).collect(); // FIXME: remove PathBuf
Ok(UrlBuf { loc: LocBuf::<PathBuf>::zeroed(buf), scheme: to.scheme().into() }.into()) let buf = PathBufDyn::from(buf);
UrlCow::try_from((to.scheme().zeroed().to_owned(), buf))
} }

View file

@ -1,18 +1,47 @@
use std::{borrow::Cow, ffi::OsStr, io, path::PathBuf}; use std::{io, sync::Arc};
use yazi_shared::{path::PathBufDyn, strand::StrandCow, url::{UrlBuf, UrlLike}};
use crate::{cha::{Cha, ChaType}, provider::FileHolder}; use crate::{cha::{Cha, ChaType}, provider::FileHolder};
pub struct DirEntry(pub(super) tokio::fs::DirEntry); pub enum DirEntry {
Regular(tokio::fs::DirEntry),
Others { entry: tokio::fs::DirEntry, dir: Arc<UrlBuf> },
}
impl FileHolder for DirEntry { impl FileHolder for DirEntry {
fn path(&self) -> PathBuf { self.0.path() } async fn file_type(&self) -> io::Result<ChaType> {
match self {
fn name(&self) -> Cow<'_, OsStr> { self.0.file_name().into() } Self::Regular(entry) | Self::Others { entry, .. } => entry.file_type().await.map(Into::into),
}
async fn metadata(&self) -> io::Result<Cha> {
let name = self.name(); // TODO: use `file_name_os_str` when stabilized
Ok(Cha::new(&name, self.0.metadata().await?))
} }
async fn file_type(&self) -> io::Result<ChaType> { self.0.file_type().await.map(Into::into) } async fn metadata(&self) -> io::Result<Cha> {
let meta = match self {
Self::Regular(entry) | Self::Others { entry, .. } => entry.metadata().await?,
};
Ok(Cha::new(self.name(), meta)) // TODO: use `file_name_os_str` when stabilized
}
fn name(&self) -> StrandCow<'_> {
match self {
Self::Regular(entry) | Self::Others { entry, .. } => entry.file_name().into(),
}
}
fn path(&self) -> PathBufDyn {
match self {
Self::Regular(entry) | Self::Others { entry, .. } => entry.path().into(),
}
}
fn url(&self) -> UrlBuf {
match self {
Self::Regular(entry) => entry.path().into(),
Self::Others { entry, dir } => {
dir.try_join(entry.file_name()).expect("entry name is a valid component of the local URL")
}
}
}
} }

View file

@ -1,6 +1,6 @@
use std::{io, path::Path}; use std::io;
use yazi_shared::scheme::SchemeRef; use yazi_shared::url::AsUrl;
use crate::provider::{Attrs, FileBuilder}; use crate::provider::{Attrs, FileBuilder};
@ -33,19 +33,16 @@ impl FileBuilder for Gate {
self self
} }
async fn new(scheme: SchemeRef<'_>) -> io::Result<Self> { async fn open<U>(&self, url: U) -> io::Result<Self::File>
if scheme.is_local() {
Ok(Self::default())
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Not a local filesystem"))?
}
}
async fn open<P>(&self, path: P) -> io::Result<Self::File>
where where
P: AsRef<Path>, U: AsUrl,
{ {
self.0.open(path).await let url = url.as_url();
if let Some(path) = url.as_local() {
self.0.open(path).await
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Not a local URL: {url:?}")))
}
} }
fn read(&mut self, read: bool) -> &mut Self { fn read(&mut self, read: bool) -> &mut Self {

View file

@ -1,206 +1,176 @@
use std::{io, path::{Path, PathBuf}}; use std::{io, path::{Path, PathBuf}, sync::Arc};
use yazi_shared::url::{AsUrl, UrlCow}; use yazi_shared::{path::{AsPathDyn, PathBufDyn}, scheme::SchemeKind, url::{Url, UrlBuf, UrlCow}};
use crate::{cha::Cha, path::absolute_url, provider::{Attrs, Provider}}; use crate::{cha::Cha, path::absolute_url, provider::{Attrs, Provider}};
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct Local; pub struct Local<'a> {
url: Url<'a>,
path: &'a Path,
}
impl Provider for Local { impl<'a> Provider for Local<'a> {
type File = tokio::fs::File; type File = tokio::fs::File;
type Gate = super::Gate; type Gate = super::Gate;
type Me<'b> = Local<'b>;
type ReadDir = super::ReadDir; type ReadDir = super::ReadDir;
type UrlCow = UrlCow<'a>;
async fn absolute<'a, U>(&self, url: &'a U) -> io::Result<UrlCow<'a>> async fn absolute(&self) -> io::Result<Self::UrlCow> { Ok(absolute_url(self.url)) }
where
U: AsUrl, #[inline]
{ async fn canonicalize(&self) -> io::Result<UrlBuf> {
let url = url.as_url(); tokio::fs::canonicalize(self.path).await.map(Into::into)
if url.scheme.is_local() { }
Ok(absolute_url(url))
} else { async fn casefold(&self) -> io::Result<UrlBuf> {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Not a local URL")) super::casefold(self.path).await.map(Into::into)
}
} }
#[inline] #[inline]
async fn canonicalize<P>(&self, path: P) -> io::Result<PathBuf> async fn copy<P>(&self, to: P, attrs: Attrs) -> io::Result<u64>
where where
P: AsRef<Path>, P: AsPathDyn,
{ {
tokio::fs::canonicalize(path).await let to = to.as_path_dyn().to_os_owned()?;
} let from = self.path.to_owned();
async fn casefold<P>(&self, path: P) -> io::Result<PathBuf>
where
P: AsRef<Path>,
{
super::casefold(path).await
}
#[inline]
async fn copy<P, Q>(&self, from: P, to: Q, attrs: Attrs) -> io::Result<u64>
where
P: AsRef<Path>,
Q: AsRef<Path>,
{
let from = from.as_ref().to_owned();
let to = to.as_ref().to_owned();
Self::copy_impl(from, to, attrs).await Self::copy_impl(from, to, attrs).await
} }
#[inline] #[inline]
async fn create_dir<P>(&self, path: P) -> io::Result<()> async fn create_dir(&self) -> io::Result<()> { tokio::fs::create_dir(self.path).await }
#[inline]
async fn create_dir_all(&self) -> io::Result<()> { tokio::fs::create_dir_all(self.path).await }
#[inline]
async fn hard_link<P>(&self, to: P) -> io::Result<()>
where where
P: AsRef<Path>, P: AsPathDyn,
{ {
tokio::fs::create_dir(path).await let to = to.as_path_dyn().as_os()?;
tokio::fs::hard_link(self.path, to).await
} }
#[inline] #[inline]
async fn create_dir_all<P>(&self, path: P) -> io::Result<()> async fn metadata(&self) -> io::Result<Cha> {
where Ok(Cha::new(self.path.file_name().unwrap_or_default(), tokio::fs::metadata(self.path).await?))
P: AsRef<Path>,
{
tokio::fs::create_dir_all(path).await
} }
#[inline] #[inline]
async fn gate(&self) -> io::Result<Self::Gate> { Ok(Self::Gate::default()) } async fn new<'b>(url: Url<'b>) -> io::Result<Self::Me<'b>> {
match url {
#[inline] Url::Regular(loc) | Url::Search { loc, .. } => Ok(Self::Me { url, path: loc.as_path() }),
async fn hard_link<P, Q>(&self, original: P, link: Q) -> io::Result<()> Url::Archive { .. } | Url::Sftp { .. } => {
where Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Not a local URL: {url:?}")))
P: AsRef<Path>, }
Q: AsRef<Path>, }
{
tokio::fs::hard_link(original, link).await
} }
#[inline] #[inline]
async fn metadata<P>(&self, path: P) -> io::Result<Cha> async fn read_dir(self) -> io::Result<Self::ReadDir> {
where Ok(match self.url.kind() {
P: AsRef<Path>, SchemeKind::Regular => Self::ReadDir::Regular(tokio::fs::read_dir(self.path).await?),
{ SchemeKind::Search => Self::ReadDir::Others {
let path = path.as_ref(); reader: tokio::fs::read_dir(self.path).await?,
Ok(Cha::new(path.file_name().unwrap_or_default(), tokio::fs::metadata(path).await?)) dir: Arc::new(self.url.to_owned()),
},
SchemeKind::Archive | SchemeKind::Sftp => Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Not a local URL: {:?}", self.url),
))?,
})
} }
#[inline] #[inline]
async fn read_dir<P>(&self, path: P) -> io::Result<Self::ReadDir> async fn read_link(&self) -> io::Result<PathBufDyn> {
where Ok(tokio::fs::read_link(self.path).await?.into())
P: AsRef<Path>,
{
tokio::fs::read_dir(path).await.map(super::ReadDir)
} }
#[inline] #[inline]
async fn read_link<P>(&self, path: P) -> io::Result<PathBuf> async fn remove_dir(&self) -> io::Result<()> { tokio::fs::remove_dir(self.path).await }
#[inline]
async fn remove_dir_all(&self) -> io::Result<()> { tokio::fs::remove_dir_all(self.path).await }
#[inline]
async fn remove_file(&self) -> io::Result<()> { tokio::fs::remove_file(self.path).await }
#[inline]
async fn rename<P>(&self, to: P) -> io::Result<()>
where where
P: AsRef<Path>, P: AsPathDyn,
{ {
tokio::fs::read_link(path).await let to = to.as_path_dyn().as_os()?;
tokio::fs::rename(self.path, to).await
} }
#[inline] #[inline]
async fn remove_dir<P>(&self, path: P) -> io::Result<()> async fn symlink<P, F>(&self, original: P, _is_dir: F) -> io::Result<()>
where where
P: AsRef<Path>, P: AsPathDyn,
{
tokio::fs::remove_dir(path).await
}
#[inline]
async fn remove_dir_all<P>(&self, path: P) -> io::Result<()>
where
P: AsRef<Path>,
{
tokio::fs::remove_dir_all(path).await
}
#[inline]
async fn remove_file<P>(&self, path: P) -> io::Result<()>
where
P: AsRef<Path>,
{
tokio::fs::remove_file(path).await
}
#[inline]
async fn rename<P, Q>(&self, from: P, to: Q) -> io::Result<()>
where
P: AsRef<Path>,
Q: AsRef<Path>,
{
tokio::fs::rename(from, to).await
}
#[inline]
async fn symlink<P, Q, F>(&self, original: P, link: Q, _is_dir: F) -> io::Result<()>
where
P: AsRef<Path>,
Q: AsRef<Path>,
F: AsyncFnOnce() -> io::Result<bool>, F: AsyncFnOnce() -> io::Result<bool>,
{ {
#[cfg(unix)] #[cfg(unix)]
{ {
tokio::fs::symlink(original, link).await let original = original.as_path_dyn().as_os()?;
tokio::fs::symlink(original, self.path).await
} }
#[cfg(windows)] #[cfg(windows)]
if _is_dir().await? { if _is_dir().await? {
self.symlink_dir(original, link).await self.symlink_dir(original).await
} else { } else {
self.symlink_file(original, link).await self.symlink_file(original).await
} }
} }
#[inline] #[inline]
async fn symlink_dir<P, Q>(&self, original: P, link: Q) -> io::Result<()> async fn symlink_dir<P>(&self, original: P) -> io::Result<()>
where where
P: AsRef<Path>, P: AsPathDyn,
Q: AsRef<Path>,
{ {
let original = original.as_path_dyn().as_os()?;
#[cfg(unix)] #[cfg(unix)]
{ {
tokio::fs::symlink(original, link).await tokio::fs::symlink(original, self.path).await
} }
#[cfg(windows)] #[cfg(windows)]
{ {
tokio::fs::symlink_dir(original, link).await tokio::fs::symlink_dir(original, self.path).await
} }
} }
#[inline] #[inline]
async fn symlink_file<P, Q>(&self, original: P, link: Q) -> io::Result<()> async fn symlink_file<P>(&self, original: P) -> io::Result<()>
where where
P: AsRef<Path>, P: AsPathDyn,
Q: AsRef<Path>,
{ {
let original = original.as_path_dyn().as_os()?;
#[cfg(unix)] #[cfg(unix)]
{ {
tokio::fs::symlink(original, link).await tokio::fs::symlink(original, self.path).await
} }
#[cfg(windows)] #[cfg(windows)]
{ {
tokio::fs::symlink_file(original, link).await tokio::fs::symlink_file(original, self.path).await
} }
} }
#[inline] #[inline]
async fn symlink_metadata<P>(&self, path: P) -> io::Result<Cha> async fn symlink_metadata(&self) -> io::Result<Cha> {
where Ok(Cha::new(
P: AsRef<Path>, self.path.file_name().unwrap_or_default(),
{ tokio::fs::symlink_metadata(self.path).await?,
let path = path.as_ref(); ))
Ok(Cha::new(path.file_name().unwrap_or_default(), tokio::fs::symlink_metadata(path).await?))
} }
async fn trash<P>(&self, path: P) -> io::Result<()> async fn trash(&self) -> io::Result<()> {
where let path = self.path.to_owned();
P: AsRef<Path>,
{
let path = path.as_ref().to_owned();
tokio::task::spawn_blocking(move || { tokio::task::spawn_blocking(move || {
#[cfg(target_os = "android")] #[cfg(target_os = "android")]
{ {
@ -222,16 +192,18 @@ impl Provider for Local {
} }
#[inline] #[inline]
async fn write<P, C>(&self, path: P, contents: C) -> io::Result<()> fn url(&self) -> Url<'_> { self.url }
#[inline]
async fn write<C>(&self, contents: C) -> io::Result<()>
where where
P: AsRef<Path>,
C: AsRef<[u8]>, C: AsRef<[u8]>,
{ {
tokio::fs::write(path, contents).await tokio::fs::write(self.path, contents).await
} }
} }
impl Local { impl<'a> Local<'a> {
async fn copy_impl(from: PathBuf, to: PathBuf, attrs: Attrs) -> io::Result<u64> { async fn copy_impl(from: PathBuf, to: PathBuf, attrs: Attrs) -> io::Result<u64> {
#[cfg(any(target_os = "linux", target_os = "android"))] #[cfg(any(target_os = "linux", target_os = "android"))]
{ {
@ -273,18 +245,18 @@ impl Local {
} }
#[inline] #[inline]
pub async fn read<P>(&self, path: P) -> io::Result<Vec<u8>> pub async fn read(&self) -> io::Result<Vec<u8>> { tokio::fs::read(self.path).await }
where
P: AsRef<Path>, #[inline]
{ pub async fn read_to_string(&self) -> io::Result<String> {
tokio::fs::read(path).await tokio::fs::read_to_string(self.path).await
} }
#[inline] #[inline]
pub async fn read_to_string<P>(&self, path: P) -> io::Result<String> pub fn regular<P>(path: &'a P) -> Self
where where
P: AsRef<Path>, P: ?Sized + AsRef<Path>,
{ {
tokio::fs::read_to_string(path).await Self { url: Url::regular(path), path: path.as_ref() }
} }
} }

View file

@ -1,13 +1,23 @@
use std::io; use std::{io, sync::Arc};
use yazi_shared::url::UrlBuf;
use crate::provider::DirReader; use crate::provider::DirReader;
pub struct ReadDir(pub(super) tokio::fs::ReadDir); pub enum ReadDir {
Regular(tokio::fs::ReadDir),
Others { reader: tokio::fs::ReadDir, dir: Arc<UrlBuf> },
}
impl DirReader for ReadDir { impl DirReader for ReadDir {
type Entry = super::DirEntry; type Entry = super::DirEntry;
async fn next(&mut self) -> io::Result<Option<Self::Entry>> { async fn next(&mut self) -> io::Result<Option<Self::Entry>> {
self.0.next_entry().await.map(|entry| entry.map(super::DirEntry)) Ok(match self {
Self::Regular(reader) => reader.next_entry().await?.map(Self::Entry::Regular),
Self::Others { reader, dir } => {
reader.next_entry().await?.map(|entry| Self::Entry::Others { entry, dir: dir.clone() })
}
})
} }
} }

View file

@ -1,75 +1,62 @@
use std::{borrow::Cow, ffi::OsStr, io, path::{Path, PathBuf}}; use std::io;
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
use yazi_macro::ok_or_not_found; use yazi_macro::ok_or_not_found;
use yazi_shared::{scheme::SchemeRef, url::{AsUrl, UrlCow}}; use yazi_shared::{path::{AsPathDyn, PathBufDyn, PathLike}, strand::StrandCow, url::{AsUrl, Url, UrlBuf}};
use crate::{cha::{Cha, ChaType}, provider::Attrs}; use crate::{cha::{Cha, ChaType}, provider::Attrs};
pub trait Provider { pub trait Provider: Sized {
type File: AsyncRead + AsyncWrite + Unpin; type File: AsyncRead + AsyncWrite + Unpin;
type Gate: FileBuilder<File = Self::File>; type Gate: FileBuilder<File = Self::File>;
type ReadDir: DirReader; type ReadDir: DirReader + 'static;
type UrlCow;
type Me<'a>: Provider;
fn absolute<'a, U>(&self, url: &'a U) -> impl Future<Output = io::Result<UrlCow<'a>>> fn absolute(&self) -> impl Future<Output = io::Result<Self::UrlCow>>;
where
U: AsUrl;
fn canonicalize<P>(&self, path: P) -> impl Future<Output = io::Result<PathBuf>> fn canonicalize(&self) -> impl Future<Output = io::Result<UrlBuf>>;
where
P: AsRef<Path>;
fn casefold<P>(&self, path: P) -> impl Future<Output = io::Result<PathBuf>> fn casefold(&self) -> impl Future<Output = io::Result<UrlBuf>>;
where
P: AsRef<Path>;
fn copy<P, Q>(&self, from: P, to: Q, attrs: Attrs) -> impl Future<Output = io::Result<u64>> fn copy<P>(&self, to: P, attrs: Attrs) -> impl Future<Output = io::Result<u64>>
where where
P: AsRef<Path>, P: AsPathDyn;
Q: AsRef<Path>;
fn create<P>(&self, path: P) -> impl Future<Output = io::Result<Self::File>> fn create(&self) -> impl Future<Output = io::Result<Self::File>> {
where async move { self.gate().write(true).create(true).truncate(true).open(self.url()).await }
P: AsRef<Path>,
{
async move { self.gate().await?.write(true).create(true).truncate(true).open(path).await }
} }
fn create_dir<P>(&self, path: P) -> impl Future<Output = io::Result<()>> fn create_dir(&self) -> impl Future<Output = io::Result<()>>;
where
P: AsRef<Path>;
fn create_dir_all<P>(&self, path: P) -> impl Future<Output = io::Result<()>> fn create_dir_all(&self) -> impl Future<Output = io::Result<()>> {
where
P: AsRef<Path>,
{
async move { async move {
let mut path = path.as_ref(); let mut url = self.url();
if path == Path::new("") { if url.loc().is_empty() {
return Ok(()); return Ok(());
} }
let mut stack = Vec::new(); let mut stack = Vec::new();
loop { loop {
match self.create_dir(path).await { match Self::new(url).await?.create_dir().await {
Ok(()) => break, Ok(()) => break,
Err(e) if e.kind() == io::ErrorKind::NotFound => { Err(e) if e.kind() == io::ErrorKind::NotFound => {
if let Some(parent) = path.parent() { if let Some(parent) = url.parent() {
stack.push(path); stack.push(url);
path = parent; url = parent;
} else { } else {
return Err(io::Error::other("failed to create whole tree")); return Err(io::Error::other("failed to create whole tree"));
} }
} }
Err(_) if self.metadata(path).await.is_ok_and(|m| m.is_dir()) => break, Err(_) if Self::new(url).await?.metadata().await.is_ok_and(|m| m.is_dir()) => break,
Err(e) => return Err(e), Err(e) => return Err(e),
} }
} }
while let Some(p) = stack.pop() { while let Some(u) = stack.pop() {
match self.create_dir(p).await { match Self::new(u).await?.create_dir().await {
Ok(()) => {} Ok(()) => {}
Err(_) if self.metadata(p).await.is_ok_and(|m| m.is_dir()) => {} Err(_) if Self::new(u).await?.metadata().await.is_ok_and(|m| m.is_dir()) => {}
Err(e) => return Err(e), Err(e) => return Err(e),
} }
} }
@ -78,87 +65,74 @@ pub trait Provider {
} }
} }
fn gate(&self) -> impl Future<Output = io::Result<Self::Gate>>; fn gate(&self) -> Self::Gate { Self::Gate::default() }
fn hard_link<P, Q>(&self, original: P, link: Q) -> impl Future<Output = io::Result<()>> fn hard_link<P>(&self, to: P) -> impl Future<Output = io::Result<()>>
where where
P: AsRef<Path>, P: AsPathDyn;
Q: AsRef<Path>;
fn metadata<P>(&self, path: P) -> impl Future<Output = io::Result<Cha>> fn metadata(&self) -> impl Future<Output = io::Result<Cha>>;
where
P: AsRef<Path>;
fn open<P>(&self, path: P) -> impl Future<Output = io::Result<Self::File>> fn new<'a>(url: Url<'a>) -> impl Future<Output = io::Result<Self::Me<'a>>>;
where
P: AsRef<Path>, fn open(&self) -> impl Future<Output = io::Result<Self::File>> {
{ async move { self.gate().read(true).open(self.url()).await }
async move { self.gate().await?.read(true).open(path).await }
} }
fn read_dir<P>(&self, path: P) -> impl Future<Output = io::Result<Self::ReadDir>> fn read_dir(self) -> impl Future<Output = io::Result<Self::ReadDir>>;
where
P: AsRef<Path>;
fn read_link<P>(&self, path: P) -> impl Future<Output = io::Result<PathBuf>> fn read_link(&self) -> impl Future<Output = io::Result<PathBufDyn>>;
where
P: AsRef<Path>;
fn remove_dir<P>(&self, path: P) -> impl Future<Output = io::Result<()>> fn remove_dir(&self) -> impl Future<Output = io::Result<()>>;
where
P: AsRef<Path>;
fn remove_dir_all<P>(&self, path: P) -> impl Future<Output = io::Result<()>> fn remove_dir_all(&self) -> impl Future<Output = io::Result<()>> {
where async fn remove_dir_all_impl<P>(url: Url<'_>) -> io::Result<()>
P: AsRef<Path>,
{
async fn remove_dir_all_impl<P>(me: &P, path: &Path) -> io::Result<()>
where where
P: Provider + ?Sized, P: Provider,
{ {
let mut it = ok_or_not_found!(me.read_dir(path).await, return Ok(())); let mut it = ok_or_not_found!(P::new(url).await?.read_dir().await, return Ok(()));
while let Some(child) = it.next().await? { while let Some(child) = it.next().await? {
let ft = ok_or_not_found!(child.file_type().await, continue); let ft = ok_or_not_found!(child.file_type().await, continue);
let result = if ft.is_dir() { let result = if ft.is_dir() {
Box::pin(remove_dir_all_impl(me, &child.path())).await Box::pin(remove_dir_all_impl::<P>(child.url().as_url())).await
} else { } else {
me.remove_file(&child.path()).await P::new(child.url().as_url()).await?.remove_file().await
}; };
() = ok_or_not_found!(result); () = ok_or_not_found!(result);
} }
Ok(ok_or_not_found!(me.remove_dir(path).await)) Ok(ok_or_not_found!(P::new(url).await?.remove_dir().await))
} }
async move { async move {
let path = path.as_ref(); let cha = ok_or_not_found!(self.symlink_metadata().await, return Ok(()));
let cha = ok_or_not_found!(self.symlink_metadata(path).await, return Ok(()));
if cha.is_link() { if cha.is_link() {
self.remove_file(path).await self.remove_file().await
} else { } else {
remove_dir_all_impl(self, path).await remove_dir_all_impl::<Self>(self.url()).await
} }
} }
} }
fn remove_dir_clean<P>(&self, root: P) -> impl Future<Output = ()> fn remove_dir_clean(&self) -> impl Future<Output = ()> {
where let root = self.url().to_owned();
P: AsRef<Path>,
{
let root = root.as_ref().to_path_buf();
async move { async move {
let mut stack = vec![(root, false)]; let mut stack = vec![(root, false)];
while let Some((dir, visited)) = stack.pop() { while let Some((dir, visited)) = stack.pop() {
let Ok(provider) = Self::new(dir.as_url()).await else {
continue;
};
if visited { if visited {
self.remove_dir(&dir).await.ok(); provider.remove_dir().await.ok();
} else if let Ok(mut it) = self.read_dir(&dir).await { } else if let Ok(mut it) = provider.read_dir().await {
stack.push((dir, true)); stack.push((dir, true));
while let Ok(Some(ent)) = it.next().await { while let Ok(Some(ent)) = it.next().await {
if ent.file_type().await.is_ok_and(|t| t.is_dir()) { if ent.file_type().await.is_ok_and(|t| t.is_dir()) {
stack.push((ent.path(), false)); stack.push((ent.url(), false));
} }
} }
} }
@ -166,56 +140,42 @@ pub trait Provider {
} }
} }
fn remove_file<P>(&self, path: P) -> impl Future<Output = io::Result<()>> fn remove_file(&self) -> impl Future<Output = io::Result<()>>;
where
P: AsRef<Path>;
fn rename<P, Q>(&self, from: P, to: Q) -> impl Future<Output = io::Result<()>> fn rename<P>(&self, to: P) -> impl Future<Output = io::Result<()>>
where where
P: AsRef<Path>, P: AsPathDyn;
Q: AsRef<Path>;
fn symlink<P, Q, F>( fn symlink<P, F>(&self, original: P, _is_dir: F) -> impl Future<Output = io::Result<()>>
&self,
original: P,
link: Q,
_is_dir: F,
) -> impl Future<Output = io::Result<()>>
where where
P: AsRef<Path>, P: AsPathDyn,
Q: AsRef<Path>,
F: AsyncFnOnce() -> io::Result<bool>; F: AsyncFnOnce() -> io::Result<bool>;
fn symlink_dir<P, Q>(&self, original: P, link: Q) -> impl Future<Output = io::Result<()>> fn symlink_dir<P>(&self, original: P) -> impl Future<Output = io::Result<()>>
where where
P: AsRef<Path>, P: AsPathDyn,
Q: AsRef<Path>,
{ {
self.symlink(original, link, async || Ok(true)) self.symlink(original, async || Ok(true))
} }
fn symlink_file<P, Q>(&self, original: P, link: Q) -> impl Future<Output = io::Result<()>> fn symlink_file<P>(&self, original: P) -> impl Future<Output = io::Result<()>>
where where
P: AsRef<Path>, P: AsPathDyn,
Q: AsRef<Path>,
{ {
self.symlink(original, link, async || Ok(false)) self.symlink(original, async || Ok(false))
} }
fn symlink_metadata<P>(&self, path: P) -> impl Future<Output = io::Result<Cha>> fn symlink_metadata(&self) -> impl Future<Output = io::Result<Cha>>;
where
P: AsRef<Path>;
fn trash<P>(&self, path: P) -> impl Future<Output = io::Result<()>> fn trash(&self) -> impl Future<Output = io::Result<()>>;
where
P: AsRef<Path>;
fn write<P, C>(&self, path: P, contents: C) -> impl Future<Output = io::Result<()>> fn url(&self) -> Url<'_>;
fn write<C>(&self, contents: C) -> impl Future<Output = io::Result<()>>
where where
P: AsRef<Path>,
C: AsRef<[u8]>, C: AsRef<[u8]>,
{ {
async move { self.create(path).await?.write_all(contents.as_ref()).await } async move { self.create().await?.write_all(contents.as_ref()).await }
} }
} }
@ -223,24 +183,30 @@ pub trait Provider {
pub trait DirReader { pub trait DirReader {
type Entry: FileHolder; type Entry: FileHolder;
#[must_use]
fn next(&mut self) -> impl Future<Output = io::Result<Option<Self::Entry>>>; fn next(&mut self) -> impl Future<Output = io::Result<Option<Self::Entry>>>;
} }
// --- FileHolder // --- FileHolder
pub trait FileHolder { pub trait FileHolder {
#[must_use] #[must_use]
fn path(&self) -> PathBuf; fn file_type(&self) -> impl Future<Output = io::Result<ChaType>>;
#[must_use] #[must_use]
fn name(&self) -> Cow<'_, OsStr>;
fn metadata(&self) -> impl Future<Output = io::Result<Cha>>; fn metadata(&self) -> impl Future<Output = io::Result<Cha>>;
fn file_type(&self) -> impl Future<Output = io::Result<ChaType>>; #[must_use]
fn name(&self) -> StrandCow<'_>;
#[must_use]
fn path(&self) -> PathBufDyn;
#[must_use]
fn url(&self) -> UrlBuf;
} }
// --- FileOpener // --- FileBuilder
pub trait FileBuilder { pub trait FileBuilder: Sized + Default {
type File: AsyncRead + AsyncWrite + Unpin; type File: AsyncRead + AsyncWrite + Unpin;
fn append(&mut self, append: bool) -> &mut Self; fn append(&mut self, append: bool) -> &mut Self;
@ -251,13 +217,9 @@ pub trait FileBuilder {
fn create_new(&mut self, create_new: bool) -> &mut Self; fn create_new(&mut self, create_new: bool) -> &mut Self;
fn new(scheme: SchemeRef) -> impl Future<Output = io::Result<Self>> fn open<U>(&self, url: U) -> impl Future<Output = io::Result<Self::File>>
where where
Self: Sized; U: AsUrl;
fn open<P>(&self, path: P) -> impl Future<Output = io::Result<Self::File>>
where
P: AsRef<Path>;
fn read(&mut self, read: bool) -> &mut Self; fn read(&mut self, read: bool) -> &mut Self;

View file

@ -11,12 +11,12 @@ pub trait FsScheme {
impl FsScheme for SchemeRef<'_> { impl FsScheme for SchemeRef<'_> {
fn cache(&self) -> Option<PathBuf> { fn cache(&self) -> Option<PathBuf> {
match self { match self {
SchemeRef::Regular | SchemeRef::Search(_) => None, Self::Regular { .. } | Self::Search { .. } => None,
SchemeRef::Archive(name) => { Self::Archive { domain, .. } => Some(
Some(Xdg::cache_dir().join(format!("archive-{}", yazi_shared::url::Encode::domain(name)))) Xdg::cache_dir().join(format!("archive-{}", yazi_shared::scheme::Encode::domain(domain))),
} ),
SchemeRef::Sftp(name) => { Self::Sftp { domain, .. } => {
Some(Xdg::cache_dir().join(format!("sftp-{}", yazi_shared::url::Encode::domain(name)))) Some(Xdg::cache_dir().join(format!("sftp-{}", yazi_shared::scheme::Encode::domain(domain))))
} }
} }
} }

View file

@ -1,7 +1,7 @@
use std::cmp::Ordering; use std::cmp::Ordering;
use hashbrown::HashMap; use hashbrown::HashMap;
use yazi_shared::{LcgRng, natsort, path::{PathBufDyn, PathLike}, translit::Transliterator, url::UrlLike}; use yazi_shared::{LcgRng, natsort, path::{PathBufDyn, PathLike}, strand::StrandLike, translit::Transliterator, url::UrlLike};
use crate::{File, SortBy}; use crate::{File, SortBy};
@ -43,8 +43,8 @@ impl FilesSorter {
self.cmp(a.url.ext(), b.url.ext(), self.promote(a, b)) self.cmp(a.url.ext(), b.url.ext(), self.promote(a, b))
} else { } else {
self.cmp_insensitive( self.cmp_insensitive(
a.url.ext().map_or(&[], |s| s.as_encoded_bytes()), a.url.ext().map_or(&[], |s| s.encoded_bytes()),
b.url.ext().map_or(&[], |s| s.as_encoded_bytes()), b.url.ext().map_or(&[], |s| s.encoded_bytes()),
self.promote(a, b), self.promote(a, b),
) )
}; };

View file

@ -1,6 +1,6 @@
use std::{borrow::Cow, ffi::OsStr, path::{Path, PathBuf}}; use std::{borrow::Cow, ffi::OsStr, path::{Path, PathBuf}};
use yazi_shared::{loc::Loc, url::{AsUrl, Url, UrlBuf, UrlCow}}; use yazi_shared::{path::{PathDyn, PathLike}, url::{AsUrl, Url, UrlBuf, UrlCow}};
use crate::{FsHash128, FsScheme, path::PercentEncoding}; use crate::{FsHash128, FsScheme, path::PercentEncoding};
@ -24,22 +24,22 @@ pub trait FsUrl<'a> {
impl<'a> FsUrl<'a> for Url<'a> { impl<'a> FsUrl<'a> for Url<'a> {
fn cache(&self) -> Option<PathBuf> { fn cache(&self) -> Option<PathBuf> {
fn with_loc(loc: Loc, mut path: PathBuf) -> PathBuf { fn with_loc(loc: PathDyn, mut root: PathBuf) -> PathBuf {
let mut it = loc.components(); let mut it = loc.components();
if it.next() == Some(std::path::Component::RootDir) { if it.next() == Some(std::path::Component::RootDir) {
path.push(it.as_path().percent_encode()); root.push(it.as_path().percent_encode());
} else { } else {
path.push(".%2F"); root.push(".%2F");
path.push(loc.percent_encode()); root.push(loc.percent_encode());
} }
path root
} }
self.scheme.cache().map(|root| with_loc(self.loc, root)) self.scheme().cache().map(|root| with_loc(self.loc(), root))
} }
fn cache_lock(&self) -> Option<PathBuf> { fn cache_lock(&self) -> Option<PathBuf> {
self.scheme.cache().map(|mut root| { self.scheme().cache().map(|mut root| {
root.push("%lock"); root.push("%lock");
root.push(format!("{:x}", self.hash_u128())); root.push(format!("{:x}", self.hash_u128()));
root root
@ -47,7 +47,12 @@ impl<'a> FsUrl<'a> for Url<'a> {
} }
fn unified_path(self) -> Cow<'a, Path> { fn unified_path(self) -> Cow<'a, Path> {
self.cache().map(Cow::Owned).unwrap_or_else(|| Cow::Borrowed(self.loc.as_path())) match self {
Self::Regular(loc) | Self::Search { loc, .. } => loc.as_path().into(),
Self::Archive { .. } | Self::Sftp { .. } => {
self.cache().expect("non-local URL should have a cache path").into()
}
}
} }
} }
@ -57,7 +62,12 @@ impl FsUrl<'_> for UrlBuf {
fn cache_lock(&self) -> Option<PathBuf> { self.as_url().cache_lock() } fn cache_lock(&self) -> Option<PathBuf> { self.as_url().cache_lock() }
fn unified_path(self) -> Cow<'static, Path> { fn unified_path(self) -> Cow<'static, Path> {
self.cache().unwrap_or_else(|| self.loc.into_path()).into() match self {
Self::Regular(loc) | Self::Search { loc, .. } => loc.into_path().into(),
Self::Archive { .. } | Self::Sftp { .. } => {
self.cache().expect("non-local URL should have a cache path").into()
}
}
} }
} }
@ -67,10 +77,12 @@ impl<'a> FsUrl<'a> for UrlCow<'a> {
fn cache_lock(&self) -> Option<PathBuf> { self.as_url().cache_lock() } fn cache_lock(&self) -> Option<PathBuf> { self.as_url().cache_lock() }
fn unified_path(self) -> Cow<'a, Path> { fn unified_path(self) -> Cow<'a, Path> {
match (self.cache(), self) { match self {
(None, UrlCow::Borrowed { loc, .. }) => loc.as_path().into(), Self::Regular(loc) | Self::Search { loc, .. } => loc.into_path().into(),
(None, UrlCow::Owned { loc, .. }) => loc.into_path().into(), Self::RegularRef(loc) | Self::SearchRef { loc, .. } => loc.as_path().into(),
(Some(cache), _) => cache.into(), Self::Archive { .. } | Self::ArchiveRef { .. } | Self::Sftp { .. } | Self::SftpRef { .. } => {
self.cache().expect("non-local URL should have a cache path").into()
}
} }
} }
} }

View file

@ -1,14 +1,14 @@
use std::{ffi::OsString, path::{MAIN_SEPARATOR_STR, PathBuf}}; use std::path::MAIN_SEPARATOR_STR;
use anyhow::bail; use anyhow::bail;
use mlua::{ExternalError, FromLua, IntoLua, Lua, Value}; use mlua::{ExternalError, FromLua, IntoLua, Lua, Value};
use yazi_shared::{Id, event::CmdCow, url::UrlBuf}; use yazi_shared::{Id, event::CmdCow, path::PathBufDyn, strand::{StrandBuf, StrandBufLike}, url::UrlBuf};
#[derive(Debug, Default)] #[derive(Debug)]
pub struct ShowOpt { pub struct ShowOpt {
pub cache: Vec<CmpItem>, pub cache: Vec<CmpItem>,
pub cache_name: UrlBuf, pub cache_name: UrlBuf,
pub word: PathBuf, pub word: PathBufDyn,
pub ticket: Id, pub ticket: Id,
} }
@ -35,7 +35,7 @@ impl IntoLua for ShowOpt {
// --- Item // --- Item
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CmpItem { pub struct CmpItem {
pub name: OsString, pub name: StrandBuf,
pub is_dir: bool, pub is_dir: bool,
} }

View file

@ -1,8 +1,8 @@
use std::{borrow::Cow, ffi::OsStr, path::Path, str::FromStr}; use std::{borrow::Cow, str::FromStr};
use mlua::{ExternalError, FromLua, IntoLua, Lua, Value}; use mlua::{ExternalError, FromLua, IntoLua, Lua, Value};
use serde::Deserialize; use serde::Deserialize;
use yazi_shared::{SStr, event::CmdCow}; use yazi_shared::{SStr, event::CmdCow, strand::{AsStrandDyn, StrandLike}};
#[derive(Debug)] #[derive(Debug)]
pub struct CopyOpt { pub struct CopyOpt {
@ -47,14 +47,18 @@ impl FromStr for CopySeparator {
} }
impl CopySeparator { impl CopySeparator {
pub fn transform<T: AsRef<Path> + ?Sized>(self, p: &T) -> Cow<'_, OsStr> { pub fn transform<T>(self, s: &T) -> Cow<'_, [u8]>
where
T: ?Sized + AsStrandDyn,
{
#[cfg(windows)] #[cfg(windows)]
if self == Self::Unix { if self == Self::Unix {
return match yazi_fs::path::backslash_to_slash(p.as_ref()) { use yazi_shared::strand::{StrandBufLike, StrandCow};
Cow::Owned(p) => Cow::Owned(p.into_os_string()), return match s.as_strand_dyn().backslash_to_slash() {
Cow::Borrowed(p) => Cow::Borrowed(p.as_os_str()), StrandCow::Borrowed(s) => s.encoded_bytes().into(),
StrandCow::Owned(s) => s.into_encoded_bytes().into(),
}; };
} }
Cow::Borrowed(p.as_ref().as_os_str()) Cow::Borrowed(s.as_strand_dyn().encoded_bytes())
} }
} }

View file

@ -21,7 +21,10 @@ pub fn fd(opt: FdOpt) -> Result<UnboundedReceiver<File>> {
tokio::spawn(async move { tokio::spawn(async move {
while let Ok(Some(line)) = it.next_line().await { while let Ok(Some(line)) = it.next_line().await {
if let Ok(file) = File::new(opt.cwd.join(line)).await { let Ok(url) = opt.cwd.try_join(line) else {
continue;
};
if let Ok(file) = File::new(url).await {
tx.send(file).ok(); tx.send(file).ok();
} }
} }
@ -31,7 +34,7 @@ pub fn fd(opt: FdOpt) -> Result<UnboundedReceiver<File>> {
} }
fn spawn(program: &str, opt: &FdOpt) -> std::io::Result<Child> { fn spawn(program: &str, opt: &FdOpt) -> std::io::Result<Child> {
let Some(path) = opt.cwd.as_path() else { let Some(path) = opt.cwd.as_local() else {
return Err(std::io::Error::new( return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput, std::io::ErrorKind::InvalidInput,
"fd can only search local filesystem", "fd can only search local filesystem",

View file

@ -44,7 +44,7 @@ impl Highlighter {
pub fn abort() { INCR.next(); } pub fn abort() { INCR.next(); }
pub async fn highlight(&self, skip: usize, size: Size) -> Result<Text<'static>, PeekError> { pub async fn highlight(&self, skip: usize, size: Size) -> Result<Text<'static>, PeekError> {
let mut reader = BufReader::new(Local.open(&self.path).await?); let mut reader = BufReader::new(Local::regular(&self.path).open().await?);
let syntax = Self::find_syntax(&self.path, &mut reader).await; let syntax = Self::find_syntax(&self.path, &mut reader).await;
let mut plain = syntax.is_err(); let mut plain = syntax.is_err();

View file

@ -14,7 +14,7 @@ pub struct RgOpt {
} }
pub fn rg(opt: RgOpt) -> Result<UnboundedReceiver<File>> { pub fn rg(opt: RgOpt) -> Result<UnboundedReceiver<File>> {
let Some(path) = opt.cwd.as_path() else { let Some(path) = opt.cwd.as_local() else {
bail!("rg can only search local filesystem"); bail!("rg can only search local filesystem");
}; };
@ -34,7 +34,10 @@ pub fn rg(opt: RgOpt) -> Result<UnboundedReceiver<File>> {
tokio::spawn(async move { tokio::spawn(async move {
while let Ok(Some(line)) = it.next_line().await { while let Ok(Some(line)) = it.next_line().await {
if let Ok(file) = File::new(opt.cwd.join(line)).await { let Ok(url) = opt.cwd.try_join(line) else {
continue;
};
if let Ok(file) = File::new(url).await {
tx.send(file).ok(); tx.send(file).ok();
} }
} }

View file

@ -14,7 +14,7 @@ pub struct RgaOpt {
} }
pub fn rga(opt: RgaOpt) -> Result<UnboundedReceiver<File>> { pub fn rga(opt: RgaOpt) -> Result<UnboundedReceiver<File>> {
let Some(path) = opt.cwd.as_path() else { let Some(path) = opt.cwd.as_local() else {
bail!("rga can only search local filesystem"); bail!("rga can only search local filesystem");
}; };
@ -34,7 +34,10 @@ pub fn rga(opt: RgaOpt) -> Result<UnboundedReceiver<File>> {
tokio::spawn(async move { tokio::spawn(async move {
while let Ok(Some(line)) = it.next_line().await { while let Ok(Some(line)) = it.next_line().await {
if let Ok(file) = File::new(opt.cwd.join(line)).await { let Ok(url) = opt.cwd.try_join(line) else {
continue;
};
if let Ok(file) = File::new(url).await {
tx.send(file).ok(); tx.send(file).ok();
} }
} }

View file

@ -148,7 +148,7 @@ fn read_dir(lua: &Lua) -> mlua::Result<Function> {
fn calc_size(lua: &Lua) -> mlua::Result<Function> { fn calc_size(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, url: UrlRef| async move { lua.create_async_function(|lua, url: UrlRef| async move {
let it = if let Some(path) = url.as_path() { let it = if let Some(path) = url.as_local() {
yazi_fs::provider::local::SizeCalculator::new(path).await.map(SizeCalculator::Local) yazi_fs::provider::local::SizeCalculator::new(path).await.map(SizeCalculator::Local)
} else { } else {
yazi_vfs::provider::SizeCalculator::new(&*url).await.map(SizeCalculator::Remote) yazi_vfs::provider::SizeCalculator::new(&*url).await.map(SizeCalculator::Remote)

View file

@ -1,4 +1,4 @@
#![allow(clippy::if_same_then_else, clippy::unit_arg)] #![allow(clippy::if_same_then_else)]
yazi_macro::mod_pub!(bindings elements external fs isolate loader process pubsub runtime theme utils); yazi_macro::mod_pub!(bindings elements external fs isolate loader process pubsub runtime theme utils);

View file

@ -65,8 +65,11 @@ impl Loader {
} }
let p = BOOT.plugin_dir.join(format!("{plugin}.yazi/{entry}.lua")); let p = BOOT.plugin_dir.join(format!("{plugin}.yazi/{entry}.lua"));
let chunk = let chunk = Local::regular(&p)
Local.read(&p).await.with_context(|| format!("Failed to load plugin from {p:?}"))?.into(); .read()
.await
.with_context(|| format!("Failed to load plugin from {p:?}"))?
.into();
let result = Self::compatible_or_error(id, &chunk); let result = Self::compatible_or_error(id, &chunk);
let inspect = f(&chunk); let inspect = f(&chunk);

View file

@ -30,7 +30,7 @@ impl Utils {
pub(super) fn image_precache(lua: &Lua) -> mlua::Result<Function> { pub(super) fn image_precache(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, (src, dist): (UrlRef, UrlRef)| async move { lua.create_async_function(|lua, (src, dist): (UrlRef, UrlRef)| async move {
let Some(dist) = dist.as_path() else { let Some(dist) = dist.as_local() else {
return (Value::Nil, Error::custom("Destination must be a local path")) return (Value::Nil, Error::custom("Destination must be a local path"))
.into_lua_multi(&lua); .into_lua_multi(&lua);
}; };

View file

@ -91,7 +91,7 @@ impl Utils {
CLIPBOARD.set(text).await; CLIPBOARD.set(text).await;
Ok(None) Ok(None)
} else { } else {
Some(lua.create_string(CLIPBOARD.get().await.as_encoded_bytes())).transpose() Some(lua.create_string(CLIPBOARD.get().await)).transpose()
} }
}) })
} }

View file

@ -1,12 +1,12 @@
use std::{borrow::Cow, collections::VecDeque, hash::{BuildHasher, Hash, Hasher}}; use std::{collections::VecDeque, hash::{BuildHasher, Hash, Hasher}};
use anyhow::{Context, Result, anyhow}; use anyhow::{Context, Result, anyhow};
use tokio::{io::{self, ErrorKind::{AlreadyExists, NotFound}}, sync::mpsc}; use tokio::{io::{self, ErrorKind::{AlreadyExists, NotFound}}, sync::mpsc};
use tracing::warn; use tracing::warn;
use yazi_config::YAZI; use yazi_config::YAZI;
use yazi_fs::{Cwd, FsHash128, FsUrl, cha::Cha, ok_or_not_found, path::{path_relative_to, skip_url}, provider::{Attrs, DirReader, FileHolder, Provider, local::Local}}; use yazi_fs::{Cwd, FsHash128, FsUrl, cha::Cha, ok_or_not_found, path::{skip_url, url_relative_to}, provider::{Attrs, DirReader, FileHolder, Provider, local::Local}};
use yazi_macro::ok_or_not_found; use yazi_macro::ok_or_not_found;
use yazi_shared::{scheme::SchemeLike, timestamp_us, url::{AsUrl, UrlBuf, UrlCow, UrlLike}}; use yazi_shared::{path::PathCow, timestamp_us, url::{AsUrl, UrlBuf, UrlCow, UrlLike}};
use yazi_vfs::{VfsCha, copy_with_progress, maybe_exists, provider::{self, DirEntry}, unique_name}; use yazi_vfs::{VfsCha, copy_with_progress, maybe_exists, provider::{self, DirEntry}, unique_name};
use super::{FileInDelete, FileInHardlink, FileInLink, FileInPaste, FileInTrash}; use super::{FileInDelete, FileInHardlink, FileInLink, FileInPaste, FileInTrash};
@ -64,7 +64,7 @@ impl File {
let mut dirs = VecDeque::from([task.from.clone()]); let mut dirs = VecDeque::from([task.from.clone()]);
while let Some(src) = dirs.pop_front() { while let Some(src) = dirs.pop_front() {
let dest = root.join(skip_url(&src, skip)); let dest = continue_unless_ok!(root.try_join(skip_url(&src, skip)));
continue_unless_ok!(match provider::create_dir(&dest).await { continue_unless_ok!(match provider::create_dir(&dest).await {
Err(e) if e.kind() != AlreadyExists => Err(e), Err(e) if e.kind() != AlreadyExists => Err(e),
_ => Ok(()), _ => Ok(()),
@ -80,7 +80,7 @@ impl File {
continue; continue;
} }
let to = dest.join(from.name().unwrap()); let to = continue_unless_ok!(dest.try_join(from.name().unwrap()));
if cha.is_orphan() || (cha.is_link() && !task.follow) { if cha.is_orphan() || (cha.is_link() && !task.follow) {
self.ops.out(task.id, FileOutPaste::New(0)); self.ops.out(task.id, FileOutPaste::New(0));
self.queue(task.spawn(from, to, cha).into_link(), NORMAL); self.queue(task.spawn(from, to, cha).into_link(), NORMAL);
@ -132,20 +132,21 @@ impl File {
} }
pub(crate) async fn link_do(&self, task: FileInLink) -> Result<(), FileOutLink> { pub(crate) async fn link_do(&self, task: FileInLink) -> Result<(), FileOutLink> {
let src: Cow<_> = if task.resolve { let src: PathCow = if task.resolve {
ok_or_not_found!( ok_or_not_found!(
provider::read_link(&task.from).await, provider::read_link(&task.from).await,
return Ok(self.ops.out(task.id, FileOutLink::Succ)) return Ok(self.ops.out(task.id, FileOutLink::Succ))
) )
.into() .into()
} else if task.from.scheme.covariant(&task.to.scheme) { } else if task.from.scheme().covariant(task.to.scheme()) {
task.from.loc.as_path().into() task.from.loc().into()
} else { } else {
Err(anyhow!("Source and target must be on the same filesystem: {task:?}"))? Err(anyhow!("Source and target must be on the same filesystem: {task:?}"))?
}; };
let src = UrlCow::try_from((task.from.scheme(), src))?;
let src = if task.relative { let src = if task.relative {
path_relative_to(provider::canonicalize(task.to.parent().unwrap()).await?.loc, &src)? url_relative_to(provider::canonicalize(task.to.parent().unwrap()).await?, &src)?
} else { } else {
src src
}; };
@ -196,7 +197,7 @@ impl File {
let mut dirs = VecDeque::from([task.from.clone()]); let mut dirs = VecDeque::from([task.from.clone()]);
while let Some(src) = dirs.pop_front() { while let Some(src) = dirs.pop_front() {
let dest = root.join(skip_url(&src, skip)); let dest = continue_unless_ok!(root.try_join(skip_url(&src, skip)));
continue_unless_ok!(match provider::create_dir(&dest).await { continue_unless_ok!(match provider::create_dir(&dest).await {
Err(e) if e.kind() != AlreadyExists => Err(e), Err(e) if e.kind() != AlreadyExists => Err(e),
_ => Ok(()), _ => Ok(()),
@ -212,7 +213,7 @@ impl File {
continue; continue;
} }
let to = dest.join(from.name().unwrap()); let to = continue_unless_ok!(dest.try_join(from.name().unwrap()));
self.ops.out(task.id, FileOutHardlink::New); self.ops.out(task.id, FileOutHardlink::New);
self.queue(task.spawn(from, to, cha), NORMAL); self.queue(task.spawn(from, to, cha), NORMAL);
} }
@ -353,12 +354,12 @@ impl File {
while let Some(res) = it.recv().await { while let Some(res) = it.recv().await {
match res { match res {
Ok(0) => { Ok(0) => {
Local.remove_dir_all(&cache).await.ok(); Local::regular(&cache).remove_dir_all().await.ok();
provider::rename(cache_tmp, cache).await.context("Cannot persist downloaded file")?; provider::rename(cache_tmp, cache).await.context("Cannot persist downloaded file")?;
let lock = task.url.cache_lock().context("Cannot determine cache lock")?; let lock = task.url.cache_lock().context("Cannot determine cache lock")?;
let hash = format!("{:x}", cha.hash_u128()); let hash = format!("{:x}", cha.hash_u128());
Local.write(lock, hash).await.context("Cannot lock cache")?; Local::regular(&lock).write(hash).await.context("Cannot lock cache")?;
break; break;
} }
@ -448,7 +449,7 @@ impl File {
pub(crate) async fn upload_do(&self, task: FileInUploadDo) -> Result<(), FileOutUploadDo> { pub(crate) async fn upload_do(&self, task: FileInUploadDo) -> Result<(), FileOutUploadDo> {
let lock = task.url.cache_lock().context("Cannot determine cache lock")?; let lock = task.url.cache_lock().context("Cannot determine cache lock")?;
let hash = Local.read_to_string(&lock).await.context("Cannot read cache lock")?; let hash = Local::regular(&lock).read_to_string().await.context("Cannot read cache lock")?;
let hash = u128::from_str_radix(&hash, 16).context("Cannot parse hash from lock")?; let hash = u128::from_str_radix(&hash, 16).context("Cannot parse hash from lock")?;
if hash != task.cha.hash_u128() { if hash != task.cha.hash_u128() {
Err(anyhow!("Remote file has changed since last download"))?; Err(anyhow!("Remote file has changed since last download"))?;
@ -474,7 +475,7 @@ impl File {
let cha = Self::cha(&task.url, true, None).await.context("Cannot stat uploaded file")?; let cha = Self::cha(&task.url, true, None).await.context("Cannot stat uploaded file")?;
let hash = format!("{:x}", cha.hash_u128()); let hash = format!("{:x}", cha.hash_u128());
Local.write(lock, hash).await.context("Cannot lock cache")?; Local::regular(&lock).write(hash).await.context("Cannot lock cache")?;
break; break;
} }
@ -510,7 +511,7 @@ impl File {
url.hash(&mut h); url.hash(&mut h);
timestamp_us().hash(&mut h); timestamp_us().hash(&mut h);
unique_name(parent.join(format!(".{:x}.%tmp", h.finish())), async { false }).await unique_name(parent.try_join(format!(".{:x}.%tmp", h.finish()))?, async { false }).await
} }
} }

View file

@ -1,4 +1,4 @@
#![allow(clippy::option_map_unit_fn, clippy::unit_arg)] #![allow(clippy::option_map_unit_fn)]
mod macros; mod macros;

View file

@ -8,7 +8,7 @@ use yazi_config::{YAZI, plugin::{Fetcher, Preloader}};
use yazi_dds::Pump; use yazi_dds::Pump;
use yazi_parser::{app::PluginOpt, tasks::ProcessOpenOpt}; use yazi_parser::{app::PluginOpt, tasks::ProcessOpenOpt};
use yazi_proxy::TasksProxy; use yazi_proxy::TasksProxy;
use yazi_shared::{Id, Throttle, scheme::SchemeLike, url::{UrlBuf, UrlLike}}; use yazi_shared::{Id, Throttle, url::{UrlBuf, UrlLike}};
use yazi_vfs::{must_be_dir, provider, unique_name}; use yazi_vfs::{must_be_dir, provider, unique_name};
use super::{Ongoing, TaskOp}; use super::{Ongoing, TaskOp};
@ -79,7 +79,13 @@ impl Scheduler {
let mut ongoing = self.ongoing.lock(); let mut ongoing = self.ongoing.lock();
let id = ongoing.add::<FileProgPaste>(format!("Cut {} to {}", from.display(), to.display())); let id = ongoing.add::<FileProgPaste>(format!("Cut {} to {}", from.display(), to.display()));
if to.starts_with(&from) && !to.covariant(&from) { let Ok(prefixed) = to.try_starts_with(&from) else {
return self
.ops
.out(id, FileOutPaste::Fail("Path being cut has a different encoding".to_owned()));
};
if prefixed && !to.covariant(&from) {
return self.ops.out(id, FileOutPaste::Fail("Cannot cut directory into itself".to_owned())); return self.ops.out(id, FileOutPaste::Fail("Cannot cut directory into itself".to_owned()));
} }
@ -112,7 +118,13 @@ impl Scheduler {
to.display() to.display()
)); ));
if to.starts_with(&from) && !to.covariant(&from) { let Ok(prefixed) = to.try_starts_with(&from) else {
return self
.ops
.out(id, FileOutPaste::Fail("Path being copied has a different encoding".to_owned()));
};
if prefixed && !to.covariant(&from) {
return self.ops.out(id, FileOutPaste::Fail("Cannot copy directory into itself".to_owned())); return self.ops.out(id, FileOutPaste::Fail("Cannot copy directory into itself".to_owned()));
} }
@ -148,7 +160,14 @@ impl Scheduler {
to.display() to.display()
)); ));
if to.starts_with(&from) && !to.covariant(&from) { let Ok(prefixed) = to.try_starts_with(&from) else {
return self.ops.out(
id,
FileOutHardlink::Fail("Path being hardlinked has a different encoding".to_owned()),
);
};
if prefixed && !to.covariant(&from) {
return self return self
.ops .ops
.out(id, FileOutHardlink::Fail("Cannot hardlink directory into itself".to_owned())); .out(id, FileOutHardlink::Fail("Cannot hardlink directory into itself".to_owned()));
@ -215,7 +234,7 @@ impl Scheduler {
ongoing.hooks.add_sync(id, move |canceled| _ = tx.send(canceled)); ongoing.hooks.add_sync(id, move |canceled| _ = tx.send(canceled));
} }
if !url.scheme.is_remote() { if !url.kind().is_remote() {
return self.ops.out(id, FileOutDownload::Fail("Cannot download non-remote file".to_owned())); return self.ops.out(id, FileOutDownload::Fail("Cannot download non-remote file".to_owned()));
}; };
@ -229,7 +248,7 @@ impl Scheduler {
let mut ongoing = self.ongoing.lock(); let mut ongoing = self.ongoing.lock();
let id = ongoing.add::<FileProgUpload>(format!("Upload {}", url.display())); let id = ongoing.add::<FileProgUpload>(format!("Upload {}", url.display()));
if !url.scheme.is_remote() { if !url.kind().is_remote() {
return self.ops.out(id, FileOutUpload::Fail("Cannot upload non-remote file".to_owned())); return self.ops.out(id, FileOutUpload::Fail("Cannot upload non-remote file".to_owned()));
}; };

View file

@ -23,6 +23,7 @@ ordered-float = { workspace = true }
parking_lot = { workspace = true } parking_lot = { workspace = true }
percent-encoding = { workspace = true } percent-encoding = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
[target."cfg(unix)".dependencies] [target."cfg(unix)".dependencies]

View file

@ -1,16 +1,61 @@
use std::fmt::Display;
use crate::BytePredictor;
pub trait BytesExt { pub trait BytesExt {
fn display(&self) -> impl Display;
fn kebab_cased(&self) -> bool; fn kebab_cased(&self) -> bool;
fn split_by_seq(&self, sep: &[u8]) -> Option<(&[u8], &[u8])>;
fn rsplit_pred_once<P: BytePredictor>(&self, pred: P) -> Option<(&[u8], &[u8])>;
fn rsplit_seq_once(&self, sep: &[u8]) -> Option<(&[u8], &[u8])>;
fn split_seq_once(&self, sep: &[u8]) -> Option<(&[u8], &[u8])>;
} }
impl BytesExt for [u8] { impl BytesExt for [u8] {
fn display(&self) -> impl Display {
struct D<'a>(&'a [u8]);
impl Display for D<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for chunk in self.0.utf8_chunks() {
chunk.valid().fmt(f)?;
if !chunk.invalid().is_empty() {
char::REPLACEMENT_CHARACTER.fmt(f)?;
}
}
Ok(())
}
}
D(self)
}
fn kebab_cased(&self) -> bool { fn kebab_cased(&self) -> bool {
self.iter().all(|&b| matches!(b, b'0'..=b'9' | b'a'..=b'z' | b'-')) self.iter().all(|&b| matches!(b, b'0'..=b'9' | b'a'..=b'z' | b'-'))
} }
fn split_by_seq(&self, sep: &[u8]) -> Option<(&[u8], &[u8])> { fn rsplit_pred_once<P: BytePredictor>(&self, pred: P) -> Option<(&[u8], &[u8])> {
for (i, &byte) in self.iter().enumerate().rev() {
if pred.predicate(byte) {
let (a, b) = self.split_at(i);
return Some((a, &b[1..]));
}
}
None
}
fn split_seq_once(&self, sep: &[u8]) -> Option<(&[u8], &[u8])> {
let idx = memchr::memmem::find(self, sep)?; let idx = memchr::memmem::find(self, sep)?;
let (left, right) = self.split_at(idx); let (a, b) = self.split_at(idx);
Some((left, &right[sep.len()..])) Some((a, &b[sep.len()..]))
}
fn rsplit_seq_once(&self, sep: &[u8]) -> Option<(&[u8], &[u8])> {
let idx = memchr::memmem::rfind(self, sep)?;
let (a, b) = self.split_at(idx);
Some((a, &b[sep.len()..]))
} }
} }

View file

@ -1,5 +1,5 @@
use core::str; use core::str;
use std::{borrow::Cow, ffi::OsStr}; use std::borrow::Cow;
#[derive(Clone, Copy, PartialEq, Eq)] #[derive(Clone, Copy, PartialEq, Eq)]
pub enum CharKind { pub enum CharKind {
@ -117,23 +117,3 @@ pub fn replace_to_printable(s: &[String], tab_size: u8) -> String {
} }
unsafe { String::from_utf8_unchecked(buf) } unsafe { String::from_utf8_unchecked(buf) }
} }
pub fn osstr_contains(s: impl AsRef<OsStr>, needle: impl AsRef<OsStr>) -> bool {
memchr::memmem::find(s.as_ref().as_encoded_bytes(), needle.as_ref().as_encoded_bytes()).is_some()
}
pub fn osstr_starts_with(
s: impl AsRef<OsStr>,
prefix: impl AsRef<OsStr>,
insensitive: bool,
) -> bool {
let (s, prefix) = (s.as_ref().as_encoded_bytes(), prefix.as_ref().as_encoded_bytes());
if s.len() < prefix.len() {
return false;
}
if insensitive {
s[..prefix.len()].eq_ignore_ascii_case(prefix)
} else {
s[..prefix.len()] == *prefix
}
}

View file

@ -1,8 +1,8 @@
#![allow(clippy::option_map_unit_fn)] #![allow(clippy::option_map_unit_fn)]
yazi_macro::mod_pub!(data errors event loc path pool scheme shell translit url); yazi_macro::mod_pub!(data errors event loc path pool scheme shell strand translit url);
yazi_macro::mod_flat!(alias bytes chars condition debounce either env id layer natsort os osstr rand ro_cell source string sync_cell terminal tests throttle time utf8); yazi_macro::mod_flat!(alias bytes chars condition debounce either env id layer natsort os osstr predictor rand ro_cell source string sync_cell terminal tests throttle time utf8 wtf8);
pub fn init() { pub fn init() {
pool::init(); pool::init();

View file

@ -2,7 +2,7 @@ use std::{cmp, ffi::OsStr, fmt::{self, Debug, Formatter}, hash::{Hash, Hasher},
use anyhow::Result; use anyhow::Result;
use crate::{loc::Loc, path::{AsInnerView, AsPathDyn, AsPathView, PathBufLike, PathDyn, PathLike}}; use crate::{loc::Loc, path::{AsPathDyn, AsPathView, PathBufLike, PathBufUnsafeExt, PathDyn, PathLike, PathUnsafeExt, SetNameError}, scheme::SchemeKind, strand::AsStrandView};
#[derive(Clone, Default, Eq)] #[derive(Clone, Default, Eq)]
pub struct LocBuf<P: PathBufLike = PathBuf> { pub struct LocBuf<P: PathBufLike = PathBuf> {
@ -65,7 +65,8 @@ where
// --- Hash // --- Hash
impl<P> Hash for LocBuf<P> impl<P> Hash for LocBuf<P>
where where
P: PathBufLike, P: PathBufLike + PathBufUnsafeExt,
for<'a> P::Borrowed<'a>: PathUnsafeExt<'a>,
for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>, for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>,
{ {
fn hash<H: Hasher>(&self, state: &mut H) { self.as_loc().hash(state) } fn hash<H: Hasher>(&self, state: &mut H) { self.as_loc().hash(state) }
@ -73,7 +74,8 @@ where
impl<P> Debug for LocBuf<P> impl<P> Debug for LocBuf<P>
where where
P: PathBufLike + Debug, P: PathBufLike + PathBufUnsafeExt + Debug,
for<'a> P::Borrowed<'a>: PathUnsafeExt<'a>,
for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>, for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>,
{ {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
@ -87,7 +89,8 @@ where
impl<P> From<P> for LocBuf<P> impl<P> From<P> for LocBuf<P>
where where
P: PathBufLike, P: PathBufLike + PathBufUnsafeExt,
for<'a> P::Borrowed<'a>: PathUnsafeExt<'a>,
for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>, for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>,
{ {
fn from(path: P) -> Self { fn from(path: P) -> Self {
@ -106,12 +109,13 @@ impl<T: ?Sized + AsRef<OsStr>> From<&T> for LocBuf<PathBuf> {
impl<P> LocBuf<P> impl<P> LocBuf<P>
where where
P: PathBufLike, P: PathBufLike + PathBufUnsafeExt,
for<'a> P::Borrowed<'a>: PathUnsafeExt<'a>,
for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>, for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>,
{ {
pub fn new<'a, T>(path: P, base: T, trail: T) -> Self pub fn new<'a, S>(path: P, base: S, trail: S) -> Self
where where
T: for<'b> AsPathView<'a, <P::Borrowed<'b> as PathLike<'b>>::View<'a>>, S: for<'b> AsStrandView<'a, <P::Borrowed<'b> as PathLike<'b>>::Strand<'a>>,
{ {
let loc = Self::from(path); let loc = Self::from(path);
let Loc { inner, uri, urn, _phantom } = Loc::new(&loc.inner, base, trail); let Loc { inner, uri, urn, _phantom } = Loc::new(&loc.inner, base, trail);
@ -142,9 +146,9 @@ where
Self { inner: loc.inner, uri, urn } Self { inner: loc.inner, uri, urn }
} }
pub fn floated<'a, T>(path: P, base: T) -> Self pub fn floated<'a, S>(path: P, base: S) -> Self
where where
T: for<'b> AsPathView<'a, <P::Borrowed<'b> as PathLike<'b>>::View<'a>>, S: for<'b> AsStrandView<'a, <P::Borrowed<'b> as PathLike<'b>>::Strand<'a>>,
{ {
let loc = Self::from(path); let loc = Self::from(path);
let Loc { inner, uri, urn, _phantom } = Loc::floated(&loc.inner, base); let Loc { inner, uri, urn, _phantom } = Loc::floated(&loc.inner, base);
@ -153,6 +157,14 @@ where
Self { inner: loc.inner, uri, urn } Self { inner: loc.inner, uri, urn }
} }
pub fn saturated(path: P, kind: SchemeKind) -> Self {
let loc = Self::from(path);
let Loc { inner, uri, urn, _phantom } = Loc::saturated(&loc.inner, kind);
debug_assert!(inner.encoded_bytes() == loc.inner.encoded_bytes());
Self { inner: loc.inner, uri, urn }
}
#[inline] #[inline]
pub fn as_loc<'a>(&'a self) -> Loc<'a, P::Borrowed<'a>> { pub fn as_loc<'a>(&'a self) -> Loc<'a, P::Borrowed<'a>> {
Loc { Loc {
@ -174,16 +186,16 @@ where
#[inline] #[inline]
pub fn into_path(self) -> P { self.inner } pub fn into_path(self) -> P { self.inner }
pub fn set_name<T>(&mut self, name: T) pub fn try_set_name<'a, T>(&mut self, name: T) -> Result<(), SetNameError>
where where
T: for<'a> AsInnerView<'a, P::InnerRef<'a>>, T: AsStrandView<'a, P::Strand<'a>>,
{ {
let old = self.inner.len(); let old = self.inner.len();
self.mutate(|path| path.set_file_name(name)); self.mutate(|path| path.try_set_name(name))?;
let new = self.len(); let new = self.len();
if new == old { if new == old {
return; return Ok(());
} }
if self.uri != 0 { if self.uri != 0 {
@ -200,31 +212,34 @@ where
self.urn -= old - new; self.urn -= old - new;
} }
} }
Ok(())
} }
#[inline] #[inline]
pub fn rebase<'a, 'b>(&'a self, base: P::Borrowed<'b>) -> Self pub fn rebase<'a, 'b>(&'a self, base: P::Borrowed<'b>) -> Result<Self>
where where
'a: 'b, 'a: 'b,
for<'c> <P::Borrowed<'c> as PathLike<'c>>::Owned: Into<Self>, for<'c> <P::Borrowed<'c> as PathLike<'c>>::Owned: Into<Self>,
{ {
let mut loc: Self = base.join(self.uri()).into(); let mut loc: Self = base.try_join(self.uri())?.into();
(loc.uri, loc.urn) = (self.uri, self.urn); (loc.uri, loc.urn) = (self.uri, self.urn);
loc Ok(loc)
} }
#[inline] #[inline]
fn mutate<F: FnOnce(&mut P)>(&mut self, f: F) { fn mutate<T, F: FnOnce(&mut P) -> T>(&mut self, f: F) -> T {
let mut inner = self.inner.take(); let mut inner = self.inner.take();
f(&mut inner); let result = f(&mut inner);
self.inner = Self::from(inner).inner; self.inner = Self::from(inner).inner;
result
} }
} }
// FIXME: macro // FIXME: macro
impl<P> LocBuf<P> impl<P> LocBuf<P>
where where
P: PathBufLike, P: PathBufLike + PathBufUnsafeExt,
for<'a> P::Borrowed<'a>: PathUnsafeExt<'a>,
for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>, for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>,
{ {
#[inline] #[inline]
@ -246,13 +261,17 @@ where
pub fn has_trail(&self) -> bool { self.as_loc().has_trail() } pub fn has_trail(&self) -> bool { self.as_loc().has_trail() }
#[inline] #[inline]
pub fn name(&self) -> Option<<P::Borrowed<'_> as PathLike<'_>>::Inner> { self.as_loc().name() } pub fn name(&self) -> Option<<P::Borrowed<'_> as PathLike<'_>>::Strand<'_>> {
self.as_loc().name()
}
#[inline] #[inline]
pub fn stem(&self) -> Option<<P::Borrowed<'_> as PathLike<'_>>::Inner> { self.as_loc().stem() } pub fn stem(&self) -> Option<<P::Borrowed<'_> as PathLike<'_>>::Strand<'_>> {
self.as_loc().stem()
}
#[inline] #[inline]
pub fn ext(&self) -> Option<<P::Borrowed<'_> as PathLike<'_>>::Inner> { self.as_loc().ext() } pub fn ext(&self) -> Option<<P::Borrowed<'_> as PathLike<'_>>::Strand<'_>> { self.as_loc().ext() }
} }
impl LocBuf<PathBuf> { impl LocBuf<PathBuf> {
@ -360,7 +379,7 @@ mod tests {
for (input, name, expected) in cases { for (input, name, expected) in cases {
let mut a: UrlBuf = input.parse()?; let mut a: UrlBuf = input.parse()?;
let b: UrlBuf = expected.parse()?; let b: UrlBuf = expected.parse()?;
a.set_name(name); a.try_set_name(name).unwrap();
assert_eq!( assert_eq!(
(a.name(), format!("{a:?}").replace(r"\", "/")), (a.name(), format!("{a:?}").replace(r"\", "/")),
(b.name(), expected.replace(r"\", "/")) (b.name(), expected.replace(r"\", "/"))

View file

@ -2,7 +2,7 @@ use std::{hash::{Hash, Hasher}, marker::PhantomData, ops::Deref, path::Path};
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use crate::{loc::LocBuf, path::{AsPathView, PathBufLike, PathInner, PathLike}}; use crate::{loc::LocBuf, path::{AsPathDyn, AsPathView, PathBufLike, PathDyn, PathLike, PathUnsafeExt}, scheme::SchemeKind, strand::{AsStrandView, StrandLike}};
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
pub struct Loc<'p, P = &'p Path> { pub struct Loc<'p, P = &'p Path> {
@ -28,6 +28,13 @@ where
fn deref(&self) -> &Self::Target { &self.inner } fn deref(&self) -> &Self::Target { &self.inner }
} }
impl<'p, P> AsPathDyn for Loc<'p, P>
where
P: PathLike<'p> + AsPathDyn,
{
fn as_path_dyn(&self) -> PathDyn<'_> { self.inner.as_path_dyn() }
}
// FIXME: remove // FIXME: remove
impl AsRef<std::path::Path> for Loc<'_, &std::path::Path> { impl AsRef<std::path::Path> for Loc<'_, &std::path::Path> {
fn as_ref(&self) -> &std::path::Path { self.inner } fn as_ref(&self) -> &std::path::Path { self.inner }
@ -63,16 +70,16 @@ impl<'p, P> Eq for Loc<'p, P> where P: PathLike<'p> + Eq {}
impl<'p, P> Loc<'p, P> impl<'p, P> Loc<'p, P>
where where
P: PathLike<'p>, P: PathLike<'p> + PathUnsafeExt<'p>,
{ {
pub fn new<'a, T, U>(path: T, base: U, trail: U) -> Self pub fn new<'a, T, S>(path: T, base: S, trail: S) -> Self
where where
T: AsPathView<'p, P>, T: AsPathView<'p, P>,
U: AsPathView<'a, P::View<'a>>, S: AsStrandView<'a, P::Strand<'a>>,
{ {
let mut loc = Self::bare(path); let mut loc = Self::bare(path);
loc.uri = loc.inner.strip_prefix(base).expect("Loc must start with the given base").len(); loc.uri = loc.inner.try_strip_prefix(base).expect("Loc must start with the given base").len();
loc.urn = loc.inner.strip_prefix(trail).expect("Loc must start with the given trail").len(); loc.urn = loc.inner.try_strip_prefix(trail).expect("Loc must start with the given trail").len();
loc loc
} }
@ -98,10 +105,10 @@ where
bail!("URI exceeds the entire URL"); bail!("URI exceeds the entire URL");
} }
if i == urn { if i == urn {
loc.urn = loc.strip_prefix(it.clone()).unwrap().len(); loc.urn = loc.try_strip_prefix(it.clone())?.len();
} }
if i == uri { if i == uri {
loc.uri = loc.strip_prefix(it).unwrap().len(); loc.uri = loc.try_strip_prefix(it)?.len();
break; break;
} }
} }
@ -113,7 +120,7 @@ where
T: AsPathView<'p, P>, T: AsPathView<'p, P>,
{ {
let path = path.as_path_view(); let path = path.as_path_view();
let Some(name) = path.file_name() else { let Some(name) = path.name() else {
let uri = path.len(); let uri = path.len();
return Self { inner: path, uri, urn: 0, _phantom: PhantomData }; return Self { inner: path, uri, urn: 0, _phantom: PhantomData };
}; };
@ -140,22 +147,37 @@ where
loc loc
} }
pub fn floated<'a, T, U>(path: T, base: U) -> Self pub fn floated<'a, T, S>(path: T, base: S) -> Self
where where
T: AsPathView<'p, P>, T: AsPathView<'p, P>,
U: AsPathView<'a, P::View<'a>>, S: AsStrandView<'a, P::Strand<'a>>,
{ {
let mut loc = Self::bare(path); let mut loc = Self::bare(path);
loc.uri = loc.inner.strip_prefix(base).expect("Loc must start with the given base").len(); loc.uri = loc.inner.try_strip_prefix(base).expect("Loc must start with the given base").len();
loc loc
} }
pub fn saturated<'a, T>(path: T, kind: SchemeKind) -> Self
where
T: AsPathView<'p, P>,
{
match kind {
SchemeKind::Regular => Self::bare(path),
SchemeKind::Search => Self::zeroed(path),
SchemeKind::Archive => Self::zeroed(path),
SchemeKind::Sftp => Self::bare(path),
}
}
#[inline] #[inline]
pub fn as_loc(self) -> Self { self } pub fn as_loc(self) -> Self { self }
#[inline] #[inline]
pub fn as_path(self) -> P { self.inner } pub fn as_path(self) -> P { self.inner }
#[inline]
pub fn is_empty(self) -> bool { self.inner.is_empty() }
#[inline] #[inline]
pub fn uri(self) -> P { pub fn uri(self) -> P {
unsafe { unsafe {
@ -190,18 +212,6 @@ where
#[inline] #[inline]
pub fn has_trail(self) -> bool { self.inner.len() != self.urn } pub fn has_trail(self) -> bool { self.inner.len() != self.urn }
#[inline]
pub fn name(self) -> Option<P::Inner> { self.inner.file_name() }
#[inline]
pub fn stem(self) -> Option<P::Inner> { self.inner.file_stem() }
#[inline]
pub fn ext(self) -> Option<P::Inner> { self.inner.extension() }
#[inline]
pub fn parent(self) -> Option<P> { self.inner.parent() }
#[inline] #[inline]
pub fn triple(self) -> (P, P, P) { pub fn triple(self) -> (P, P, P) {
let len = self.inner.len(); let len = self.inner.len();
@ -218,12 +228,4 @@ where
) )
} }
} }
#[inline]
pub fn strip_prefix<'a, T>(self, base: T) -> Option<P>
where
T: AsPathView<'a, P::View<'a>>,
{
self.inner.strip_prefix(base)
}
} }

View file

@ -58,38 +58,3 @@ where
result result
} }
} }
// --- OsStrSplit
pub trait OsStrSplit {
fn rsplit_once<P: Pattern>(&self, predicate: P) -> Option<(&Self, &Self)>;
}
impl OsStrSplit for OsStr {
fn rsplit_once<P: Pattern>(&self, pat: P) -> Option<(&Self, &Self)> {
let bytes = self.as_encoded_bytes();
for (i, &byte) in bytes.iter().enumerate().rev() {
if !pat.predicate(byte) {
continue;
}
let (a, b) = bytes.split_at(i);
// SAFETY: These substrings were separated by a UTF-8 string.
return Some(unsafe {
(Self::from_encoded_bytes_unchecked(a), Self::from_encoded_bytes_unchecked(&b[1..]))
});
}
None
}
}
pub trait Pattern {
fn predicate(&self, byte: u8) -> bool;
}
impl Pattern for char {
fn predicate(&self, byte: u8) -> bool { *self == byte as Self }
}
impl Pattern for &[char] {
fn predicate(&self, byte: u8) -> bool { self.contains(&(byte as char)) }
}

View file

@ -1,54 +1,61 @@
use std::{fmt::Debug, hash::Hash}; use std::{fmt::Debug, hash::Hash};
use crate::path::{AsInnerView, AsPathView, PathInner, PathLike}; use crate::{path::{AsPath, AsPathView, PathBufDyn, PathLike, SetNameError, StartsWithError}, strand::{AsStrandView, StrandLike}};
pub trait PathBufLike pub trait PathBufLike
where where
Self: 'static, Self: 'static + AsPath,
{ {
type Inner: for<'a> AsInnerView<'a, Self::InnerRef<'a>>; type Strand<'a>: StrandLike<'a>;
type InnerRef<'a>: PathInner<'a>;
type Borrowed<'a>: PathLike<'a> + AsPathView<'a, Self::Borrowed<'a>> + Debug + Hash; type Borrowed<'a>: PathLike<'a> + AsPathView<'a, Self::Borrowed<'a>> + Debug + Hash;
fn borrow(&self) -> Self::Borrowed<'_>; fn borrow(&self) -> Self::Borrowed<'_>;
fn encoded_bytes(&self) -> &[u8]; fn encoded_bytes(&self) -> &[u8] { self.borrow().encoded_bytes() }
unsafe fn from_encoded_bytes(bytes: Vec<u8>) -> Self; fn into_dyn(self) -> PathBufDyn;
fn into_encoded_bytes(self) -> Vec<u8>; fn into_encoded_bytes(self) -> Vec<u8>;
fn is_empty(&self) -> bool { self.encoded_bytes().is_empty() } fn is_empty(&self) -> bool { self.borrow().is_empty() }
fn len(&self) -> usize { self.encoded_bytes().len() } fn len(&self) -> usize { self.borrow().len() }
fn set_file_name<T>(&mut self, name: T) fn to_str(&self) -> Result<&str, std::str::Utf8Error> { self.borrow().to_str() }
fn try_set_name<'a, T>(&mut self, name: T) -> Result<(), SetNameError>
where where
T: for<'a> AsInnerView<'a, Self::InnerRef<'a>>; T: AsStrandView<'a, Self::Strand<'a>>;
fn try_starts_with<'a, T>(&self, base: T) -> Result<bool, StartsWithError>
where
T: AsStrandView<'a, Self::Strand<'a>>;
fn take(&mut self) -> Self; fn take(&mut self) -> Self;
} }
impl PathBufLike for std::path::PathBuf { impl PathBufLike for std::path::PathBuf {
type Borrowed<'a> = &'a std::path::Path; type Borrowed<'a> = &'a std::path::Path;
type Inner = std::ffi::OsString; type Strand<'a> = &'a std::ffi::OsStr;
type InnerRef<'a> = &'a std::ffi::OsStr;
fn borrow(&self) -> Self::Borrowed<'_> { self.as_path() } fn borrow(&self) -> Self::Borrowed<'_> { self.as_path() }
fn encoded_bytes(&self) -> &[u8] { self.as_os_str().as_encoded_bytes() } fn into_dyn(self) -> PathBufDyn { PathBufDyn::Os(self) }
unsafe fn from_encoded_bytes(bytes: Vec<u8>) -> Self {
Self::from(unsafe { Self::Inner::from_encoded_bytes_unchecked(bytes) })
}
fn into_encoded_bytes(self) -> Vec<u8> { self.into_os_string().into_encoded_bytes() } fn into_encoded_bytes(self) -> Vec<u8> { self.into_os_string().into_encoded_bytes() }
fn set_file_name<T>(&mut self, name: T) fn try_set_name<'a, T>(&mut self, name: T) -> Result<(), SetNameError>
where where
T: for<'a> AsInnerView<'a, Self::InnerRef<'a>>, T: AsStrandView<'a, Self::Strand<'a>>,
{ {
self.set_file_name(name.as_inner_view()); Ok(self.set_file_name(name.as_strand_view()))
}
fn try_starts_with<'a, T>(&self, base: T) -> Result<bool, StartsWithError>
where
T: AsStrandView<'a, Self::Strand<'a>>,
{
Ok(self.starts_with(base.as_strand_view()))
} }
fn take(&mut self) -> Self { std::mem::take(self) } fn take(&mut self) -> Self { std::mem::take(self) }

View file

@ -0,0 +1,105 @@
use std::{borrow::Cow, ffi::OsStr};
use super::{PathBufDyn, PathDyn};
use crate::path::{PathBufLike, PathCow, PathLike};
// --- AsPath
pub trait AsPath {
fn as_path(&self) -> impl PathLike<'_>;
}
impl AsPath for OsStr {
fn as_path(&self) -> impl PathLike<'_> { std::path::Path::new(self) }
}
impl AsPath for &OsStr {
fn as_path(&self) -> impl PathLike<'_> { std::path::Path::new(self) }
}
impl AsPath for std::path::Path {
fn as_path(&self) -> impl PathLike<'_> { self }
}
impl AsPath for std::path::PathBuf {
fn as_path(&self) -> impl PathLike<'_> { self.as_path() }
}
impl AsPath for PathDyn<'_> {
fn as_path(&self) -> impl PathLike<'_> { *self }
}
impl AsPath for PathBufDyn {
fn as_path(&self) -> impl PathLike<'_> { self.borrow() }
}
impl AsPath for &PathBufDyn {
fn as_path(&self) -> impl PathLike<'_> { self.borrow() }
}
impl AsPath for PathCow<'_> {
fn as_path(&self) -> impl PathLike<'_> {
match self {
PathCow::Borrowed(p) => *p,
PathCow::Owned(p) => p.into(),
}
}
}
// --- AsPathDyn
pub trait AsPathDyn {
fn as_path_dyn(&self) -> PathDyn<'_>;
}
impl AsPathDyn for OsStr {
fn as_path_dyn(&self) -> PathDyn<'_> { std::path::Path::new(self).into() }
}
impl AsPathDyn for &OsStr {
fn as_path_dyn(&self) -> PathDyn<'_> { std::path::Path::new(self).into() }
}
impl AsPathDyn for Cow<'_, OsStr> {
fn as_path_dyn(&self) -> PathDyn<'_> { std::path::Path::new(self).into() }
}
impl AsPathDyn for std::path::Path {
fn as_path_dyn(&self) -> PathDyn<'_> { self.into() }
}
impl AsPathDyn for std::path::PathBuf {
fn as_path_dyn(&self) -> PathDyn<'_> { self.as_path().into() }
}
impl AsPathDyn for &std::path::PathBuf {
fn as_path_dyn(&self) -> PathDyn<'_> { self.as_path().into() }
}
impl AsPathDyn for PathDyn<'_> {
fn as_path_dyn(&self) -> PathDyn<'_> { *self }
}
impl AsPathDyn for PathBufDyn {
fn as_path_dyn(&self) -> PathDyn<'_> { self.borrow() }
}
impl AsPathDyn for &PathBufDyn {
fn as_path_dyn(&self) -> PathDyn<'_> { self.borrow() }
}
impl AsPathDyn for PathCow<'_> {
fn as_path_dyn(&self) -> PathDyn<'_> {
match self {
Self::Borrowed(p) => p.as_path_dyn(),
Self::Owned(p) => p.as_path_dyn(),
}
}
}
// --- AsPathRef
pub trait AsPathRef<'a> {
fn as_path_ref(self) -> PathDyn<'a>;
}
impl<'a> AsPathRef<'a> for PathDyn<'a> {
fn as_path_ref(self) -> PathDyn<'a> { self }
}

View file

@ -0,0 +1,56 @@
use std::borrow::Cow;
use anyhow::Result;
use crate::{IntoOsStr, path::{AsPathDyn, PathBufDyn, PathBufLike, PathDyn, PathLike}};
// --- PathCow
pub enum PathCow<'a> {
Borrowed(PathDyn<'a>),
Owned(PathBufDyn),
}
impl<'a> From<PathDyn<'a>> for PathCow<'a> {
fn from(value: PathDyn<'a>) -> Self { Self::Borrowed(value) }
}
impl From<PathBufDyn> for PathCow<'_> {
fn from(value: PathBufDyn) -> Self { Self::Owned(value) }
}
impl From<PathCow<'_>> for PathBufDyn {
fn from(value: PathCow<'_>) -> Self { value.into_owned() }
}
impl PartialEq<&str> for PathCow<'_> {
fn eq(&self, other: &&str) -> bool {
match self {
Self::Borrowed(s) => s.as_path_dyn() == *other,
Self::Owned(s) => s.as_path_dyn() == *other,
}
}
}
impl<'a> PathCow<'a> {
pub fn from_os_bytes(bytes: impl Into<Cow<'a, [u8]>>) -> Result<Self> {
Ok(match bytes.into().into_os_str()? {
Cow::Borrowed(s) => PathDyn::os(s).into(),
Cow::Owned(s) => PathBufDyn::os(s).into(),
})
}
pub fn into_owned(self) -> PathBufDyn {
match self {
Self::Borrowed(s) => s.to_buf_dyn(),
Self::Owned(s) => s,
}
}
// FIXME: remove, instead implement PathLike for PathCow
pub fn encoded_bytes(&self) -> &[u8] {
match self {
Self::Borrowed(s) => s.encoded_bytes(),
Self::Owned(s) => s.encoded_bytes(),
}
}
}

View file

@ -1,8 +1,11 @@
use std::ffi::OsStr;
use anyhow::Result;
use hashbrown::Equivalent; use hashbrown::Equivalent;
use serde::Serialize; use serde::Serialize;
use super::{AsInnerView, AsPathView}; use super::{AsPathView, RsplitOnceError, StartsWithError};
use crate::path::{PathBufLike, PathLike}; use crate::{FromWtf8, Utf8BytePredictor, path::{AsPathDyn, EndsWithError, JoinError, PathBufDynError, PathBufLike, PathBufUnsafeExt, PathDynError, PathKind, PathLike, SetNameError, StripPrefixError}, scheme::SchemeKind, strand::{AsStrandDyn, AsStrandView, Strand, StrandError}};
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum PathDyn<'p> { pub enum PathDyn<'p> {
@ -18,20 +21,46 @@ impl<'a> AsPathView<'a, PathDyn<'a>> for std::path::Components<'a> {
} }
impl<'a> From<&'a std::path::Path> for PathDyn<'a> { impl<'a> From<&'a std::path::Path> for PathDyn<'a> {
fn from(value: &'a std::path::Path) -> Self { PathDyn::Os(value) } fn from(value: &'a std::path::Path) -> Self { Self::Os(value) }
} }
impl<'a> From<&'a PathBufDyn> for PathDyn<'a> { impl<'a> From<&'a PathBufDyn> for PathDyn<'a> {
fn from(value: &'a PathBufDyn) -> Self { value.borrow() } fn from(value: &'a PathBufDyn) -> Self { value.borrow() }
} }
impl PartialEq<PathBufDyn> for PathDyn<'_> {
fn eq(&self, other: &PathBufDyn) -> bool { *self == other.borrow() }
}
impl PartialEq<PathDyn<'_>> for &std::path::Path {
fn eq(&self, other: &PathDyn<'_>) -> bool { matches!(*other, PathDyn::Os(p) if p == *self) }
}
impl PartialEq<&std::path::Path> for PathDyn<'_> {
fn eq(&self, other: &&std::path::Path) -> bool { matches!(*self, PathDyn::Os(p) if p == *other) }
}
impl PartialEq<&str> for PathDyn<'_> {
fn eq(&self, other: &&str) -> bool {
match self {
PathDyn::Os(p) => p == other,
}
}
}
impl Equivalent<PathBufDyn> for PathDyn<'_> {
fn equivalent(&self, key: &PathBufDyn) -> bool { *self == key.borrow() }
}
impl<'p> PathLike<'p> for PathDyn<'p> { impl<'p> PathLike<'p> for PathDyn<'p> {
type Components<'a> = std::path::Components<'a>; type Components<'a> = std::path::Components<'a>;
type Display<'a> = std::path::Display<'a>; type Display<'a> = std::path::Display<'a>;
type Inner = &'p [u8];
type Owned = PathBufDyn; type Owned = PathBufDyn;
type Strand<'a> = Strand<'a>;
type View<'a> = PathDyn<'a>; type View<'a> = PathDyn<'a>;
fn as_dyn(self) -> PathDyn<'p> { self }
fn components(self) -> Self::Components<'p> { fn components(self) -> Self::Components<'p> {
match self { match self {
Self::Os(p) => p.components(), Self::Os(p) => p.components(),
@ -53,38 +82,36 @@ impl<'p> PathLike<'p> for PathDyn<'p> {
} }
} }
fn extension(self) -> Option<Self::Inner> { fn ext(self) -> Option<Self::Strand<'p>> {
Some(match self { Some(match self {
Self::Os(p) => p.extension()?.as_encoded_bytes(), Self::Os(p) => p.extension()?.into(),
}) })
} }
fn file_name(self) -> Option<Self::Inner> { fn has_root(self) -> bool {
Some(match self { match self {
Self::Os(p) => p.file_name()?.as_encoded_bytes(), Self::Os(p) => p.has_root(),
})
}
fn file_stem(self) -> Option<Self::Inner> {
Some(match self {
Self::Os(p) => p.file_stem()?.as_encoded_bytes(),
})
}
// FIXME: remove
unsafe fn from_encoded_bytes(bytes: &'p [u8]) -> Self {
Self::Os(std::path::Path::new(unsafe { std::ffi::OsStr::from_encoded_bytes_unchecked(bytes) }))
}
fn join<'a, T>(self, base: T) -> Self::Owned
where
T: AsPathView<'a, Self::View<'a>>,
{
match (self, base.as_path_view()) {
(Self::Os(p), PathDyn::Os(q)) => Self::Owned::Os(p.join(q)),
} }
} }
fn is_absolute(self) -> bool {
match self {
Self::Os(p) => p.is_absolute(),
}
}
fn kind(self) -> PathKind {
match self {
Self::Os(_) => PathKind::Os,
}
}
fn name(self) -> Option<Self::Strand<'p>> {
Some(match self {
Self::Os(p) => p.file_name()?.into(),
})
}
fn owned(self) -> Self::Owned { fn owned(self) -> Self::Owned {
match self { match self {
Self::Os(p) => Self::Owned::Os(p.to_path_buf()), Self::Os(p) => Self::Owned::Os(p.to_path_buf()),
@ -97,26 +124,129 @@ impl<'p> PathLike<'p> for PathDyn<'p> {
}) })
} }
fn strip_prefix<'a, T>(self, base: T) -> Option<Self> fn stem(self) -> Option<Self::Strand<'p>> {
Some(match self {
Self::Os(p) => p.file_stem()?.into(),
})
}
fn try_ends_with<'a, T>(self, child: T) -> Result<bool, EndsWithError>
where where
T: AsPathView<'a, Self::View<'a>>, T: AsStrandView<'a, Self::Strand<'a>>,
{ {
Some(match (self, base.as_path_view()) { Ok(match (self, child.as_strand_view()) {
(Self::Os(p), PathDyn::Os(q)) => Self::Os(p.strip_prefix(q).ok()?), (Self::Os(p), Strand::Os(q)) => p.ends_with(q),
(Self::Os(p), Strand::Utf8(q)) => p.ends_with(q),
(Self::Os(p), Strand::Bytes(b)) => {
p.ends_with(OsStr::from_wtf8(b).map_err(|_| EndsWithError)?)
}
})
}
fn try_join<'a, T>(self, path: T) -> Result<Self::Owned, JoinError>
where
T: AsStrandView<'a, Self::Strand<'a>>,
{
Ok(match (self, path.as_strand_view()) {
(Self::Os(p), Strand::Os(q)) => Self::Owned::Os(p.join(q)),
(Self::Os(p), Strand::Utf8(q)) => Self::Owned::Os(p.join(q)),
(Self::Os(p), Strand::Bytes(b)) => {
Self::Owned::Os(p.join(OsStr::from_wtf8(b).map_err(|_| JoinError::FromWtf8)?))
}
})
}
fn rsplit_pred<'a, T>(self, pred: T) -> Option<(Self, Self)>
where
T: Utf8BytePredictor,
{
match self {
PathDyn::Os(p) => p.rsplit_pred(pred).map(|(l, r)| (Self::Os(l), Self::Os(r))),
}
}
fn try_rsplit_seq<'a, T>(self, pat: T) -> Result<(Self, Self), RsplitOnceError>
where
T: AsStrandView<'a, Self::Strand<'a>>,
{
let pat = pat.as_strand_view();
match self {
PathDyn::Os(p) => {
let (l, r) = p.try_rsplit_seq(pat.as_os().map_err(|_| RsplitOnceError::AsOs)?)?;
Ok((Self::Os(l), Self::Os(r)))
}
}
}
fn try_starts_with<'a, T>(self, base: T) -> Result<bool, StartsWithError>
where
T: AsStrandView<'a, Self::Strand<'a>>,
{
Ok(match (self, base.as_strand_view()) {
(Self::Os(p), Strand::Os(q)) => p.starts_with(q),
(Self::Os(p), Strand::Utf8(q)) => p.starts_with(q),
(Self::Os(p), Strand::Bytes(b)) => {
p.starts_with(OsStr::from_wtf8(b).map_err(|_| StartsWithError)?)
}
})
}
fn try_strip_prefix<'a, T>(self, base: T) -> Result<Self, StripPrefixError>
where
T: AsStrandView<'a, Self::Strand<'a>>,
{
Ok(match (self, base.as_strand_view()) {
(Self::Os(p), Strand::Os(q)) => Self::Os(p.strip_prefix(q)?),
(Self::Os(p), Strand::Utf8(q)) => Self::Os(p.strip_prefix(q)?),
(Self::Os(p), Strand::Bytes(b)) => {
Self::Os(p.strip_prefix(OsStr::from_wtf8(b).map_err(|_| StripPrefixError::WrongEncoding)?)?)
}
}) })
} }
} }
impl PartialEq<PathBufDyn> for PathDyn<'_> { impl<'a> PathDyn<'a> {
fn eq(&self, other: &PathBufDyn) -> bool { *self == other.borrow() } #[inline]
} pub fn os<T>(path: &'a T) -> Self
where
T: ?Sized + AsRef<std::path::Path>,
{
Self::Os(path.as_ref())
}
impl PartialEq<PathDyn<'_>> for &std::path::Path { #[inline]
fn eq(&self, other: &PathDyn<'_>) -> bool { matches!(*other, PathDyn::Os(p) if p == *self) } pub fn as_os(self) -> Result<&'a std::path::Path, PathDynError> {
} match self {
Self::Os(p) => Ok(p),
}
}
impl Equivalent<PathBufDyn> for PathDyn<'_> { #[inline]
fn equivalent(&self, key: &PathBufDyn) -> bool { *self == key.borrow() } pub fn to_os_owned(self) -> Result<std::path::PathBuf, PathDynError> {
match self {
Self::Os(p) => Ok(p.to_owned()),
}
}
pub fn with<T>(kind: SchemeKind, strand: &'a T) -> Result<Self, StrandError>
where
T: ?Sized + AsStrandDyn,
{
use SchemeKind as K;
let s = strand.as_strand_dyn();
Ok(match kind {
K::Regular | K::Search | K::Archive => Self::Os(std::path::Path::new(s.as_os()?)),
K::Sftp => Self::Os(std::path::Path::new(s.as_os()?)), // FIXME
})
}
#[inline]
pub unsafe fn from_encoded_bytes(kind: impl Into<PathKind>, bytes: &'a [u8]) -> Self {
match kind.into() {
PathKind::Os => Self::Os(unsafe { OsStr::from_encoded_bytes_unchecked(bytes) }.as_ref()),
}
}
} }
// --- PathBufDyn // --- PathBufDyn
@ -126,67 +256,20 @@ pub enum PathBufDyn {
Os(std::path::PathBuf), Os(std::path::PathBuf),
} }
impl PathBufDyn { impl From<std::path::PathBuf> for PathBufDyn {
pub const fn os_default() -> Self { Self::Os(std::path::PathBuf::new()) } fn from(value: std::path::PathBuf) -> Self { Self::Os(value) }
}
impl PathBufLike for PathBufDyn {
type Borrowed<'a> = PathDyn<'a>;
type Inner = Vec<u8>;
type InnerRef<'a> = &'a [u8];
fn borrow(&self) -> Self::Borrowed<'_> {
match self {
Self::Os(p) => Self::Borrowed::Os(p.as_path()),
}
}
fn encoded_bytes(&self) -> &[u8] {
match self {
Self::Os(p) => p.as_os_str().as_encoded_bytes(),
}
}
// FIXME: remove
unsafe fn from_encoded_bytes(bytes: Vec<u8>) -> Self {
Self::Os(std::path::PathBuf::from(unsafe {
std::ffi::OsString::from_encoded_bytes_unchecked(bytes)
}))
}
fn into_encoded_bytes(self) -> Vec<u8> {
match self {
Self::Os(p) => p.into_os_string().into_encoded_bytes(),
}
}
fn set_file_name<T>(&mut self, name: T)
where
T: for<'a> AsInnerView<'a, Self::InnerRef<'a>>,
{
// TODO: introduce a new `PathInnerDyn`
todo!()
}
fn take(&mut self) -> Self {
match self {
Self::Os(p) => Self::Os(std::mem::take(p)),
}
}
}
impl From<PathDyn<'_>> for PathBufDyn {
fn from(value: PathDyn<'_>) -> Self {
match value {
PathDyn::Os(p) => Self::Os(p.to_path_buf()),
}
}
} }
impl From<&PathBufDyn> for PathBufDyn { impl From<&PathBufDyn> for PathBufDyn {
fn from(value: &PathBufDyn) -> Self { value.clone() } fn from(value: &PathBufDyn) -> Self { value.clone() }
} }
impl TryFrom<PathBufDyn> for std::path::PathBuf {
type Error = PathBufDynError;
fn try_from(value: PathBufDyn) -> Result<Self, Self::Error> { value.into_os() }
}
impl PartialEq<PathDyn<'_>> for PathBufDyn { impl PartialEq<PathDyn<'_>> for PathBufDyn {
fn eq(&self, other: &PathDyn<'_>) -> bool { self.borrow() == *other } fn eq(&self, other: &PathDyn<'_>) -> bool { self.borrow() == *other }
} }
@ -198,3 +281,131 @@ impl PartialEq<PathDyn<'_>> for &PathBufDyn {
impl Equivalent<PathDyn<'_>> for PathBufDyn { impl Equivalent<PathDyn<'_>> for PathBufDyn {
fn equivalent(&self, key: &PathDyn<'_>) -> bool { self.borrow() == *key } fn equivalent(&self, key: &PathDyn<'_>) -> bool { self.borrow() == *key }
} }
impl PathBufLike for PathBufDyn {
type Borrowed<'a> = PathDyn<'a>;
type Strand<'a> = Strand<'a>;
fn borrow(&self) -> Self::Borrowed<'_> {
match self {
Self::Os(p) => Self::Borrowed::Os(p.as_path()),
}
}
fn encoded_bytes(&self) -> &[u8] {
match self {
Self::Os(p) => p.as_os_str().as_encoded_bytes(),
}
}
fn into_dyn(self) -> PathBufDyn { self }
fn into_encoded_bytes(self) -> Vec<u8> {
match self {
Self::Os(p) => p.into_os_string().into_encoded_bytes(),
}
}
fn try_set_name<'a, T>(&mut self, name: T) -> Result<(), SetNameError>
where
T: AsStrandView<'a, Self::Strand<'a>>,
{
Ok(match (self, name.as_strand_view()) {
(Self::Os(p), Strand::Os(q)) => p.set_file_name(q),
(Self::Os(p), Strand::Utf8(q)) => p.set_file_name(q),
(Self::Os(p), Strand::Bytes(b)) => {
p.set_file_name(OsStr::from_wtf8(b).map_err(|_| SetNameError::FromWtf8)?)
}
})
}
fn try_starts_with<'a, T>(&self, base: T) -> Result<bool, StartsWithError>
where
T: AsStrandView<'a, Self::Strand<'a>>,
{
Ok(match (self, base.as_strand_view()) {
(Self::Os(p), Strand::Os(q)) => p.starts_with(q),
(Self::Os(p), Strand::Utf8(q)) => p.starts_with(q),
(Self::Os(p), Strand::Bytes(b)) => {
p.starts_with(OsStr::from_wtf8(b).map_err(|_| StartsWithError)?)
}
})
}
fn take(&mut self) -> Self {
match self {
Self::Os(p) => Self::Os(std::mem::take(p)),
}
}
}
impl PathBufDyn {
#[inline]
pub fn os(path: impl Into<std::path::PathBuf>) -> Self { Self::Os(path.into()) }
#[inline]
pub fn into_os(self) -> Result<std::path::PathBuf, PathBufDynError> {
Ok(match self {
PathBufDyn::Os(p) => p,
})
}
#[inline]
pub fn new(kind: SchemeKind) -> Self {
use SchemeKind as K;
match kind {
K::Regular | K::Search | K::Archive => Self::Os(std::path::PathBuf::new()),
K::Sftp => Self::Os(std::path::PathBuf::new()), // FIXME
}
}
pub fn with<T>(kind: SchemeKind, strand: T) -> Result<Self, StrandError>
where
T: AsStrandDyn,
{
use SchemeKind as K;
let s = strand.as_strand_dyn();
Ok(match kind {
K::Regular | K::Search | K::Archive => Self::Os(std::path::PathBuf::from(s.as_os()?)),
K::Sftp => Self::Os(std::path::PathBuf::from(s.as_os()?)), // FIXME
})
}
pub fn with_capacity(kind: SchemeKind, capacity: usize) -> Self {
use SchemeKind as K;
match kind {
K::Regular | K::Search | K::Archive => Self::Os(std::path::PathBuf::with_capacity(capacity)),
K::Sftp => Self::Os(std::path::PathBuf::with_capacity(capacity)), // FIXME
}
}
pub fn try_push<T>(&mut self, path: T) -> Result<(), StrandError>
where
T: AsPathDyn,
{
let path = path.as_path_dyn();
Ok(match self {
PathBufDyn::Os(p) => p.push(path.as_os()?),
})
}
pub fn try_extend<T>(&mut self, paths: T) -> Result<(), StrandError>
where
T: IntoIterator,
T::Item: AsPathDyn,
{
for p in paths {
self.try_push(p)?;
}
Ok(())
}
#[inline]
pub unsafe fn from_encoded_bytes(kind: impl Into<PathKind>, bytes: Vec<u8>) -> Self {
match kind.into() {
PathKind::Os => Self::Os(unsafe { std::path::PathBuf::from_encoded_bytes(bytes) }),
}
}
}

View file

@ -0,0 +1,82 @@
use thiserror::Error;
use crate::strand::StrandError;
// --- EndsWithError
#[derive(Debug, Error)]
#[error("calling ends_with on paths with different encodings")]
pub struct EndsWithError;
// --- JoinError
#[derive(Debug, Error)]
#[error("calling join on paths with different encodings")]
pub enum JoinError {
FromWtf8,
FromPathBufDyn(#[from] PathBufDynError),
}
impl From<JoinError> for std::io::Error {
fn from(err: JoinError) -> Self { std::io::Error::other(err) }
}
// --- PathDynError
#[derive(Debug, Error)]
pub enum PathDynError {
#[error("conversion to OsStr failed")]
AsOs,
}
impl From<PathDynError> for std::io::Error {
fn from(err: PathDynError) -> Self { std::io::Error::other(err) }
}
// --- PathBufDynError
#[derive(Debug, Error)]
pub enum PathBufDynError {
#[error("conversion to OsString failed")]
IntoOs,
}
// --- SetNameError
#[derive(Debug, Error)]
#[error("calling set_name on paths with different encodings")]
pub enum SetNameError {
FromWtf8,
FromStrandDyn(#[from] StrandError),
}
impl From<SetNameError> for std::io::Error {
fn from(err: SetNameError) -> Self { std::io::Error::other(err) }
}
// --- RsplitOnce
#[derive(Error, Debug)]
#[error("calling rsplit_once on paths with different encodings")]
pub enum RsplitOnceError {
#[error("conversion to OsStr failed")]
AsOs,
#[error("conversion to UTF-8 str failed")]
AsUtf8,
#[error("the pattern was not found")]
NotFound,
}
// --- StartsWithError
#[derive(Error, Debug)]
#[error("calling starts_with on paths with different encodings")]
pub struct StartsWithError;
// --- StripPrefixError
#[derive(Debug, Error)]
pub enum StripPrefixError {
#[error("calling strip_prefix on URLs with different schemes")]
Exotic,
#[error("the base is not a prefix of the path")]
NotPrefix,
#[error("calling strip_prefix on paths with different encodings")]
WrongEncoding,
}
impl From<std::path::StripPrefixError> for StripPrefixError {
fn from(_: std::path::StripPrefixError) -> Self { Self::NotPrefix }
}

View file

@ -1,15 +0,0 @@
pub trait PathInner<'a>: Copy {
fn encoded_bytes(self) -> &'a [u8];
fn is_empty(self) -> bool { self.encoded_bytes().is_empty() }
fn len(self) -> usize { self.encoded_bytes().len() }
}
impl<'a> PathInner<'a> for &'a std::ffi::OsStr {
fn encoded_bytes(self) -> &'a [u8] { self.as_encoded_bytes() }
}
impl<'a> PathInner<'a> for &'a [u8] {
fn encoded_bytes(self) -> &'a [u8] { self }
}

Some files were not shown because too many files have changed in this diff Show more