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",
"percent-encoding",
"serde",
"thiserror 2.0.17",
"tokio",
"uzers",
"windows-sys 0.61.2",

View file

@ -48,6 +48,7 @@ scopeguard = "1.2.0"
serde = { version = "1.0.228", features = [ "derive" ] }
serde_json = "1.0.145"
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-stream = "0.1.17"
tokio-util = "0.7.17"
@ -61,4 +62,5 @@ uzers = "0.12.1"
format_push_string = "warn"
implicit_clone = "warn"
module_inception = "allow"
unit_arg = "allow"
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 yazi_macro::{render, succ};
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};
@ -30,7 +30,7 @@ impl Actor for Show {
};
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() {
succ!(render!(mem::replace(&mut cmp.visible, false)));
}
@ -43,16 +43,20 @@ impl Actor for Show {
}
impl Show {
fn match_candidates(word: &OsStr, cache: &[CmpItem]) -> Vec<CmpItem> {
let smart = !word.as_encoded_bytes().iter().any(|c| c.is_ascii_uppercase());
fn match_candidates(word: PathDyn, cache: &[CmpItem]) -> Vec<CmpItem> {
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| {
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);
if exact.len() >= LIMIT {
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.
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 yazi_fs::{CWD, path::expand_url, provider::{DirReader, FileHolder}};
use yazi_macro::{act, render, succ};
use yazi_parser::cmp::{CmpItem, ShowOpt, TriggerOpt};
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 crate::{Actor, Ctx};
@ -32,7 +32,7 @@ impl Actor for Trigger {
if cmp.caches.contains_key(&parent) {
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;
@ -42,8 +42,8 @@ impl Actor for Trigger {
// "/" 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
if parent.loc.as_os_str() == "/" {
cache.push(CmpItem { name: OsString::new(), is_dir: true });
if parent.loc() == "/" {
cache.push(CmpItem { name: Default::default(), is_dir: true });
}
while let Ok(Some(ent)) = dir.next().await {
@ -53,9 +53,8 @@ impl Actor for Trigger {
}
if !cache.is_empty() {
cache.sort_unstable_by(|a, b| {
natsort(a.name.as_encoded_bytes(), b.name.as_encoded_bytes(), false)
});
cache
.sort_unstable_by(|a, b| natsort(a.name.encoded_bytes(), b.name.encoded_bytes(), false));
CmpProxy::show(ShowOpt { cache, cache_name: parent, word, ticket });
}
@ -67,23 +66,28 @@ impl Actor for Trigger {
}
impl Trigger {
fn split_url(s: &str) -> Option<(UrlBuf, PathBuf)> {
let (scheme, path, ..) = UrlCow::parse(s.as_bytes()).ok()?;
fn split_url(s: &str) -> Option<(UrlBuf, PathBufDyn)> {
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 `~/`
}
#[cfg(windows)]
const SEP: &[char] = &['/', '\\'];
#[cfg(not(windows))]
const SEP: char = std::path::MAIN_SEPARATOR;
let sep = if cfg!(windows) {
AnyAsciiChar::new(&[b'/', b'\\']).unwrap()
} else {
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() => {
(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()),
})
}
@ -91,13 +95,13 @@ impl Trigger {
#[cfg(test)]
mod tests {
use yazi_shared::url::UrlLike;
use yazi_shared::{path::PathBufLike, url::UrlLike};
use super::*;
fn compare(s: &str, parent: &str, child: &str) {
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);
}
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_config::THEME;
use yazi_plugin::bindings::Range;
use yazi_shared::url::UrlLike;
use yazi_shared::{path::PathLike, url::UrlLike};
use super::Lives;
use crate::lives::PtrCell;
@ -88,11 +88,8 @@ impl UserData for File {
if !me.url.has_trail() {
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();
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 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};
@ -47,7 +47,7 @@ impl UserData for Tab {
fields.add_field_method_get("id", |_, me| Ok(Id(me.id)));
cached_field!(fields, name, |lua, me| {
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));

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_parser::VoidOpt;
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_vfs::{VfsFile, maybe_exists, provider};
use yazi_watcher::WATCHER;
@ -50,7 +50,12 @@ impl Actor for BulkRename {
.write_all(old.join(OsStr::new("\n")).as_encoded_bytes())
.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(
cwd.into(),
Splatter::new(&[UrlCow::default(), tmp.as_url().into()]).splat(&opener.run),
@ -64,8 +69,8 @@ impl Actor for BulkRename {
defer!(AppProxy::resume());
AppProxy::stop().await;
let new: Vec<_> = Local
.read_to_string(&tmp)
let new: Vec<_> = Local::regular(&tmp)
.read_to_string()
.await?
.lines()
.take(old.len())
@ -120,10 +125,12 @@ impl BulkRename {
let permit = WATCHER.acquire().await.unwrap();
let (mut failed, mut succeeded) = (Vec::new(), HashMap::with_capacity(todo.len()));
for (o, n) in todo {
let (old, new): (UrlBuf, UrlBuf) = (
selected[o.0].components().take(root).chain([Component::Normal(&o)]).collect(),
selected[n.0].components().take(root).chain([Component::Normal(&n)]).collect(),
);
let (Ok(old), Ok(new)) =
(Self::replace_url(&selected[o.0], root, &o), Self::replace_url(&selected[n.0], root, &n))
else {
failed.push((o, n, anyhow!("Invalid new or old file name")));
continue;
};
if maybe_exists(&new).await && !provider::must_identical(&old, &new).await {
failed.push((o, n, anyhow!("Destination already exists")));
@ -137,7 +144,7 @@ impl BulkRename {
}
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));
FilesOp::rename(succeeded);
}
@ -153,6 +160,10 @@ impl BulkRename {
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<()> {
let mut stdout = TTY.lockout();
terminal_clear(&mut *stdout)?;

View file

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

View file

@ -27,7 +27,10 @@ impl Actor for Create {
return;
}
let new = cwd.join(&name);
let Ok(new) = cwd.try_join(&name) else {
return;
};
if !opt.force
&& maybe_exists(&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_parser::mgr::{DownloadOpt, OpenOpt};
use yazi_proxy::MgrProxy;
use yazi_shared::{data::Data, url::UrlCow};
use yazi_shared::{data::Data, url::{UrlCow, UrlLike}};
use yazi_vfs::VfsFile;
use crate::{Actor, Ctx};
@ -78,7 +78,7 @@ impl Download {
let roots: HashSet<_> = urls.iter().filter_map(|u| u.scheme().cache()).collect();
for mut root in roots {
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> {
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))
}

View file

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

View file

@ -18,7 +18,7 @@ impl Actor for Hover {
// Parent should always track CWD
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

View file

@ -21,7 +21,7 @@ impl Actor for Leave {
let Some(mut url) = url else { succ!() };
if url.is_search() {
url = url.into_regular();
url = url.as_regular()?;
}
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_parser::VoidOpt;
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_vfs::{VfsFiles, VfsFilesOp};
@ -41,7 +41,7 @@ impl Actor for Refresh {
impl Refresh {
fn cwd_changed() {
if CWD.load().scheme.is_virtual() {
if CWD.load().kind().is_virtual() {
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_parser::mgr::RenameOpt;
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_watcher::WATCHER;
@ -49,7 +49,10 @@ impl Actor for Rename {
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 {
Self::r#do(tab, old, new).await.ok();
} else if ConfirmProxy::show(ConfirmCfg::overwrite(&new)).await {

View file

@ -52,7 +52,7 @@ impl Actor for SearchDo {
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;
tab.search = Some(tokio::spawn(async move {
@ -111,7 +111,7 @@ impl Actor for SearchStop {
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));
act!(mgr:hidden, cx)?;

View file

@ -29,10 +29,13 @@ impl Actor for TabCreate {
(true, wd.into_owned())
} else if let Some(h) = cx.hovered() {
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 {
tab.pref = cx.tab().pref.clone();
(true, cx.cwd().to_regular())
(true, cx.cwd().clone())
};
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> {
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) {
cx.mgr.yanked.apply_op(&op);
Self::update_tab(cx, op).ok();

View file

@ -39,7 +39,7 @@ impl Image {
})
.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> {

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);

View file

@ -1,7 +1,5 @@
#![allow(clippy::unit_arg)]
mod macros;
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) => {
$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, 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| {
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| {
use yazi_fs::FsUrl;

View file

@ -1,7 +1,7 @@
use std::ops::Deref;
use mlua::{ExternalError, FromLua, Lua, UserData, Value};
use yazi_shared::path::PathBufDyn;
use mlua::{ExternalError, FromLua, Lua, MetaMethod, UserData, UserDataMethods, Value};
use yazi_shared::path::{PathBufDyn, PathBufLike};
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 {
pub fn new(scheme: &yazi_shared::scheme::Scheme) -> Self {
Self { inner: scheme.clone(), v_kind: None, v_cache: None }
pub fn new(scheme: impl Into<yazi_shared::scheme::Scheme>) -> Self {
Self { inner: scheme.into(), v_kind: None, v_cache: None }
}
}
impl UserData for Scheme {
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)));
fields.add_field_method_get("is_virtual", |_, me| Ok(me.is_virtual()));

View file

@ -1,8 +1,8 @@
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_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};
@ -99,26 +99,28 @@ impl FromLua for Url {
impl UserData for Url {
fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
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| {
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| {
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, 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| {
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| {
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()));
@ -138,42 +140,60 @@ impl UserData for Url {
});
methods.add_method("join", |_, me, other: Value| {
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) => {
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());
}
me.join(&url.loc)
me.try_join(url.loc()).into_lua_err()?
}
_ => Err("must be a string or Url".into_lua_err())?,
}))
});
methods.add_method("starts_with", |_, me, base: Value| {
Ok(match base {
Value::String(s) => me.loc.starts_with(s.as_bytes().into_os_str()?),
Value::UserData(ud) => me.starts_with(&*ud.borrow::<Self>()?),
Value::String(s) => {
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())?,
})
});
methods.add_method("ends_with", |_, me, child: Value| {
Ok(match child {
Value::String(s) => me.loc.ends_with(s.as_bytes().into_os_str()?),
Value::UserData(ud) => me.ends_with(&*ud.borrow::<Self>()?),
Value::String(s) => {
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())?,
})
});
methods.add_method("strip_prefix", |_, me, base: Value| {
let path = match base {
Value::String(s) => me.loc().strip_prefix(&s.as_bytes().into_os_str()?).map(Into::into),
Value::UserData(ud) => me.strip_prefix(&*ud.borrow::<Self>()?),
let strip = match base {
Value::String(s) => {
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())?,
};
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)| {
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));

View file

@ -4,13 +4,13 @@ use futures::executor::block_on;
use hashbrown::HashSet;
use serde::Serialize;
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;
#[derive(Debug, Default, Serialize)]
pub struct Boot {
pub cwds: Vec<UrlBuf>,
pub files: Vec<PathBufDyn>,
pub files: Vec<StrandBuf>,
pub local_events: HashSet<String>,
pub remote_events: HashSet<String>,
@ -22,25 +22,28 @@ pub struct 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() {
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);
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();
}
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()) {
(parent.into(), child.owned())
(parent.into(), child.into())
} else {
(entry, PathBufDyn::os_default())
(entry, Default::default())
}
}

View file

@ -1,5 +1,5 @@
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 super::Dependency;
@ -23,9 +23,9 @@ impl Dependency {
pub(super) async fn delete_assets(&self) -> Result<()> {
let assets = self.target().join("assets");
match Local.read_dir(&assets).await {
match tokio::fs::read_dir(&assets).await {
Ok(mut it) => {
while let Some(entry) = it.next().await? {
while let Some(entry) = it.next_entry().await? {
remove_sealed(&entry.path())
.await
.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()))?,
};
Local.remove_dir_clean(assets).await;
Local::regular(&assets).remove_dir_clean().await;
Ok(())
}
@ -49,7 +49,7 @@ impl Dependency {
.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!")?;
} else {
outln!(

View file

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

View file

@ -1,7 +1,7 @@
use std::path::{Path, PathBuf};
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 super::Dependency;
@ -20,7 +20,7 @@ impl Dependency {
self.hash_check().await?;
}
Local.create_dir_all(&to).await?;
Local::regular(&to).create_dir_all().await?;
self.delete_assets().await?;
let res1 = Self::deploy_assets(from.join("assets"), to.join("assets")).await;
@ -30,7 +30,7 @@ impl Dependency {
self.delete_sources().await?;
}
Local.remove_dir_clean(to).await;
Local::regular(&to).remove_dir_clean().await;
self.hash = self.hash().await?;
res2?;
res1?;
@ -40,11 +40,11 @@ impl Dependency {
}
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) => {
Local.create_dir_all(&to).await?;
while let Some(entry) = it.next().await? {
let (src, dist) = (entry.path(), to.join(entry.name()));
Local::regular(&to).create_dir_all().await?;
while let Some(entry) = it.next_entry().await? {
let (src, dist) = (entry.path(), to.join(entry.file_name()));
copy_and_seal(&src, &dist).await.with_context(|| {
format!("failed to copy `{}` to `{}`", src.display(), dist.display())
})?;

View file

@ -1,6 +1,6 @@
use anyhow::{Context, Result, bail};
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 super::Dependency;
@ -15,17 +15,17 @@ impl Dependency {
for file in files {
h.write(file.as_bytes());
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![];
match Local.read_dir(dir.join("assets")).await {
match tokio::fs::read_dir(dir.join("assets")).await {
Ok(mut it) => {
while let Some(entry) = it.next().await? {
let Ok(name) = entry.name().into_owned().into_string() else {
while let Some(entry) = it.next_entry().await? {
let Ok(name) = entry.file_name().into_string() else {
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 => {}

View file

@ -15,7 +15,7 @@ pub(crate) struct Package {
impl Package {
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)?)
}
@ -132,7 +132,7 @@ impl Package {
async fn save(&self) -> Result<()> {
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") }

View file

@ -6,19 +6,19 @@ use yazi_macro::ok_or_not_found;
#[inline]
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]
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,
Err(e) => e.kind() != std::io::ErrorKind::NotFound,
}
}
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);
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(())
}
// TODO: use `yazi_fs` instead of `tokio::fs`
pub async fn remove_sealed(p: &Path) -> io::Result<()> {
#[cfg(windows)]
{
@ -40,5 +39,5 @@ pub async fn remove_sealed(p: &Path) -> io::Result<()> {
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 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())
} else {
format!("{}", CWD.load().display())

View file

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

View file

@ -50,7 +50,7 @@ impl Preview {
self.cache_dir = if self.cache_dir.as_os_str().is_empty() {
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
} else {
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 yazi_codegen::DeserializeOver2;
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};
@ -74,7 +74,7 @@ impl Icon {
}
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() {
self.dirs.get(name).or_else(|| self.dirs.get(&name.to_ascii_lowercase()))
} else {
@ -87,7 +87,7 @@ impl Icon {
}
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()))
}
}

View file

@ -223,7 +223,7 @@ impl Theme {
self.mgr.syntect_theme = self
.flavor
.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(self)

View file

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

View file

@ -1,9 +1,4 @@
#![allow(
clippy::if_same_then_else,
clippy::len_without_is_empty,
clippy::option_map_unit_fn,
clippy::unit_arg
)]
#![allow(clippy::if_same_then_else, clippy::len_without_is_empty, clippy::option_map_unit_fn)]
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)]
mod tests {
use yazi_shared::{scheme::SchemeCow, url::UrlCow};
use std::path::Path;
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]
fn test_insert_non_conflicting() {
let mut s = Selected::default();
assert!(s.add(url("/a/b")));
assert!(s.add(url("/c/d")));
assert!(s.add(Path::new("/a/b")));
assert!(s.add(Path::new("/c/d")));
assert_eq!(s.inner.len(), 2);
}
@ -166,27 +159,27 @@ mod tests {
fn test_insert_conflicting_parent() {
let mut s = Selected::default();
assert!(s.add(url("/a")));
assert!(!s.add(url("/a/b")));
assert!(s.add(Path::new("/a")));
assert!(!s.add(Path::new("/a/b")));
}
#[test]
fn test_insert_conflicting_child() {
let mut s = Selected::default();
assert!(s.add(url("/a/b/c")));
assert!(!s.add(url("/a/b")));
assert!(s.add(url("/a/b/d")));
assert!(s.add(Path::new("/a/b/c")));
assert!(!s.add(Path::new("/a/b")));
assert!(s.add(Path::new("/a/b/d")));
}
#[test]
fn test_remove() {
let mut s = Selected::default();
assert!(s.add(url("/a/b")));
assert!(!s.remove(url("/a/c")));
assert!(s.remove(url("/a/b")));
assert!(!s.remove(url("/a/b")));
assert!(s.add(Path::new("/a/b")));
assert!(!s.remove(Path::new("/a/c")));
assert!(s.remove(Path::new("/a/b")));
assert!(!s.remove(Path::new("/a/b")));
assert!(s.inner.is_empty());
assert!(s.parents.is_empty());
}
@ -197,7 +190,11 @@ mod tests {
assert_eq!(
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() {
let mut s = Selected::default();
s.add(url("/parent"));
assert_eq!(0, s.add_same([url("/parent/child1"), url("/parent/child2")]));
s.add(Path::new("/parent"));
assert_eq!(0, s.add_same([Path::new("/parent/child1"), Path::new("/parent/child2")]));
}
#[test]
fn insert_many_with_existing_child_fails() {
let mut s = Selected::default();
s.add(url("/parent/child1"));
assert_eq!(2, s.add_same([url("/parent/child1"), url("/parent/child2")]));
s.add(Path::new("/parent/child1"));
assert_eq!(2, s.add_same([Path::new("/parent/child1"), Path::new("/parent/child2")]));
}
#[test]
@ -228,48 +225,51 @@ mod tests {
fn insert_many_with_parent_as_child_of_another_url() {
let mut s = Selected::default();
s.add(url("/parent/child"));
assert_eq!(0, s.add_same([url("/parent/child/child1"), url("/parent/child/child2")]));
s.add(Path::new("/parent/child"));
assert_eq!(
0,
s.add_same([Path::new("/parent/child/child1"), Path::new("/parent/child/child2")])
);
}
#[test]
fn insert_many_with_direct_parent_fails() {
let mut s = Selected::default();
s.add(url("/a"));
assert_eq!(0, s.add_same([url("/a/b")]));
s.add(Path::new("/a"));
assert_eq!(0, s.add_same([Path::new("/a/b")]));
}
#[test]
fn insert_many_with_nested_child_fails() {
let mut s = Selected::default();
s.add(url("/a/b"));
assert_eq!(0, s.add_same([url("/a")]));
assert_eq!(1, s.add_same([url("/b"), url("/a")]));
s.add(Path::new("/a/b"));
assert_eq!(0, s.add_same([Path::new("/a")]));
assert_eq!(1, s.add_same([Path::new("/b"), Path::new("/a")]));
}
#[test]
fn insert_many_sibling_directories_success() {
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]
fn insert_many_with_grandchild_fails() {
let mut s = Selected::default();
s.add(url("/a/b"));
assert_eq!(0, s.add_same([url("/a/b/c")]));
s.add(Path::new("/a/b"));
assert_eq!(0, s.add_same([Path::new("/a/b/c")]));
}
#[test]
fn test_insert_many_with_remove() {
let mut s = Selected::default();
let child1 = url("/parent/child1");
let child2 = url("/parent/child2");
let child3 = url("/parent/child3");
let child1 = Path::new("/parent/child1");
let child2 = Path::new("/parent/child2");
let child3 = Path::new("/parent/child3");
assert_eq!(3, s.add_same([child1, child2, child3]));
assert!(s.remove(child1));

View file

@ -8,9 +8,12 @@ use crate::mgr::Yanked;
impl Tasks {
pub fn file_cut(&self, src: &Yanked, dest: &UrlBuf, force: bool) {
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 {
debug!("file_cut: same file, skipping {:?}", to);
debug!("file_cut: same file, skip {to:?}");
} else {
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) {
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 {
debug!("file_copy: same file, skipping {:?}", to);
debug!("file_copy: same file, skip {to:?}");
} else {
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) {
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 {
debug!("file_link: same file, skipping {:?}", to);
debug!("file_link: same file, skip {to:?}");
} else {
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) {
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 {
debug!("file_hardlink: same file, skipping {:?}", to);
debug!("file_hardlink: same file, skip {to:?}");
} else {
self.scheduler.file_hardlink(u.0.clone(), to, force, follow);
}

View file

@ -1,21 +1,19 @@
use std::borrow::Cow;
use hashbrown::HashMap;
use mlua::{IntoLua, Lua, Value};
use serde::{Deserialize, Serialize};
use yazi_shared::url::UrlBuf;
use yazi_shared::url::{Url, UrlCow};
use super::Ember;
#[derive(Debug, Deserialize, Serialize)]
pub struct EmberBulk<'a> {
pub changes: HashMap<Cow<'a, UrlBuf>, Cow<'a, UrlBuf>>,
pub changes: HashMap<UrlCow<'a>, UrlCow<'a>>,
}
impl<'a> EmberBulk<'a> {
pub fn borrowed<I>(changes: I) -> Ember<'a>
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()
}
@ -24,10 +22,12 @@ impl<'a> EmberBulk<'a> {
impl EmberBulk<'static> {
pub fn owned<'a, I>(changes: I) -> Ember<'static>
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() }
.into()
Self {
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 yazi_boot::BOOT;
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}};
@ -123,7 +123,7 @@ impl Pubsub {
pub fn pub_after_bulk<'a, I>(changes: I) -> Result<()>
where
I: Iterator<Item = (&'a UrlBuf, &'a UrlBuf)> + Clone,
I: Iterator<Item = (Url<'a>, Url<'a>)> + Clone,
{
if BOOT.local_events.contains("bulk") {
EmberBulk::borrowed(changes.clone()).with_receiver(*ID).flush()?;

View file

@ -58,7 +58,7 @@ impl State {
return Ok(());
}
Local.create_dir_all(&BOOT.state_dir).await?;
Local::regular(&BOOT.state_dir).create_dir_all().await?;
let mut buf = BufWriter::new(
Gate::default()
.write(true)
@ -79,7 +79,7 @@ impl State {
}
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 inner = HashMap::new();
@ -103,7 +103,7 @@ impl State {
}
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();
Ok(modified >= self.last.load(Ordering::Relaxed) as u128)
}

View file

@ -40,7 +40,7 @@ impl Stream {
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)
}

View file

@ -3,7 +3,7 @@ use yazi_actor::Ctx;
use yazi_boot::BOOT;
use yazi_macro::act;
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;
@ -20,8 +20,8 @@ impl App {
if file.is_empty() {
act!(mgr:cd, cx, (BOOT.cwds[i].clone(), CdSource::Tab))?;
} else {
act!(mgr:reveal, cx, (BOOT.cwds[i].join(file), CdSource::Tab))?;
} else if let Ok(u) = BOOT.cwds[i].try_join(file) {
act!(mgr:reveal, cx, (u, CdSource::Tab))?;
}
}

View file

@ -26,13 +26,13 @@ impl App {
async fn cwd_to_file(&self, no: bool) {
if let Some(p) = ARGS.cwd_file.as_ref().filter(|_| !no) {
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>) {
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_config::{THEME, popup::{Offset, Position}};
use yazi_core::Core;
use yazi_shared::strand::{AsStrand, StrandLike};
pub(crate) struct Cmp<'a> {
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 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() {
item = item.style(THEME.cmp.active);
} else {

View file

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

View file

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

View file

@ -28,10 +28,7 @@ impl Default for Cwd {
}
impl Cwd {
pub fn path(&self) -> PathBuf {
let url = self.0.load();
url.cache().unwrap_or_else(|| url.loc.to_path())
}
pub fn path(&self) -> PathBuf { self.0.load().as_url().unified_path().into_owned() }
pub fn set(&self, url: &UrlBuf, callback: fn()) -> bool {
if !url.is_absolute() {
@ -50,7 +47,7 @@ impl Cwd {
use std::{io::ErrorKind::{AlreadyExists, NotADirectory, NotFound}, path::Component as C};
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)

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};
@ -8,7 +9,7 @@ use crate::cha::{Cha, ChaType};
pub struct File {
pub url: UrlBuf,
pub cha: Cha,
pub link_to: Option<PathBuf>,
pub link_to: Option<PathBufDyn>,
}
impl Deref for File {
@ -26,8 +27,8 @@ impl File {
}
#[inline]
pub fn chdir(&self, wd: &Path) -> Self {
Self { url: self.url.rebase(wd), cha: self.cha, link_to: self.link_to.clone() }
pub fn chdir(&self, wd: &Path) -> Result<Self> {
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() }
#[inline]
pub fn name(&self) -> Option<&OsStr> { self.url.name() }
pub fn name(&self) -> Option<Strand<'_>> { self.url.name() }
#[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 {

View file

@ -1,7 +1,7 @@
use std::{mem, ops::{Deref, DerefMut, Not}};
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 crate::{FILES_TICKET, File, SortBy};
@ -121,6 +121,7 @@ impl Files {
#[cfg(unix)]
pub fn update_deleting(&mut self, urns: HashSet<PathBufDyn>) -> Vec<usize> {
use yazi_shared::path::PathBufLike;
if urns.is_empty() {
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 regex::bytes::{Regex, RegexBuilder};
use yazi_shared::{event::Cmd, path::{AsPath, PathLike}};
use yazi_shared::{event::Cmd, strand::{AsStrand, StrandLike}};
pub struct Filter {
raw: String,
@ -26,14 +26,14 @@ impl Filter {
#[allow(private_bounds)]
pub fn matches<T>(&self, name: T) -> bool
where
T: AsPath,
T: AsStrand,
{
self.regex.is_match(name.as_path().encoded_bytes())
self.regex.is_match(name.as_strand().encoded_bytes())
}
#[inline]
pub fn highlighted(&self, name: impl AsRef<OsStr>) -> Option<Vec<Range<usize>>> {
self.regex.find(name.as_ref().as_encoded_bytes()).map(|m| vec![m.range()])
pub fn highlighted(&self, name: impl AsStrand) -> Option<Vec<Range<usize>>> {
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);

View file

@ -1,5 +1,6 @@
use std::path::Path;
use anyhow::Result;
use hashbrown::{HashMap, HashSet};
use yazi_macro::relay;
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 {
($files:expr) => {{ $files.iter().map(|file| file.chdir(wd)).collect() }};
($files:expr) => {{ $files.iter().map(|file| file.chdir(wd)).collect::<Result<_>>()? }};
}
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);
match self {
Ok(match self {
Self::Full(_, files, cha) => Self::Full(w, files!(files), *cha),
Self::Part(_, files, ticket) => Self::Part(w, files!(files), *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::Updating(_, map) => Self::Updating(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>) {
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
.iter()
.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))
.map(|(u, f)| (u, f.url_owned()))
.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 {
let cow: UrlCow = url.into();
let (path, uri, urn) = clean_path_impl(
&cow.loc(),
cow.loc().base().components().count(),
cow.loc().trail().components().count(),
cow.loc(),
cow.base().components().count() - 1,
cow.trail().components().count() - 1,
);
let loc =
LocBuf::<PathBuf>::with(path, uri, urn).expect("Failed to create Loc from cleaned path");
UrlBuf { loc, scheme: cow.into_scheme().into() }
match cow.as_url() {
Url::Regular(_) => UrlBuf::Regular(path.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::*;
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};
@ -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> {
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_rest = expand_variables(o_rest);
let n_urn = expand_variables(o_urn);
let rest_diff = n_rest.components().count() as isize - o_rest.components().count() as isize;
let urn_diff = n_urn.components().count() as isize - o_urn.components().count() as isize;
let rest_diff =
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 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(
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,
(urn_count + urn_diff) as usize,
)
.expect("Failed to create Loc from expanded path");
let url = UrlBuf { loc, scheme: url.scheme.into() };
match absolute_url(url.as_url()) {
UrlCow::Borrowed { .. } => url.into(),
c @ UrlCow::Owned { .. } => c.into_owned().into(),
}
let expanded = match url {
Url::Regular(_) => UrlBuf::Regular(loc),
Url::Search { domain, .. } => UrlBuf::Search { loc, domain: domain.intern() },
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
#[cfg(unix)]
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)]
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 name = caps.get(2).or_else(|| caps.get(1)).unwrap();
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())
});
unsafe {
match b {
Cow::Borrowed(b) => Path::new(OsStr::from_encoded_bytes_unchecked(b)).into(),
Cow::Owned(b) => PathBuf::from(OsString::from_encoded_bytes_unchecked(b)).into(),
match (b, p) {
(Cow::Borrowed(_), _) => p.into(),
(Cow::Owned(b), PathDyn::Os(_)) => {
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> {
if url.scheme.is_virtual() {
pub fn absolute_url<'a>(url: impl Into<UrlCow<'a>>) -> UrlCow<'a> { absolute_url_impl(url.into()) }
fn absolute_url_impl<'a>(url: UrlCow<'a>) -> UrlCow<'a> {
if url.kind().is_virtual() {
return url.into();
}
let b = url.loc.as_os_str().as_encoded_bytes();
if cfg!(windows) && b.len() == 2 && b[1] == b':' && b[0].is_ascii_alphabetic() {
let loc = LocBuf::<PathBuf>::with(
let path = url.loc().as_os().expect("must be a local path");
let b = path.as_os_str().as_encoded_bytes();
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(),
if url.has_base() { 0 } else { 2 },
if url.has_trail() { 0 } else { 2 },
)
.expect("Failed to create Loc from drive letter");
UrlBuf { loc, scheme: url.scheme.into() }.into()
} else if let Some(rest) = url.loc.strip_prefix("~/")
.expect("Failed to create Loc from drive letter")
} else if let Ok(rest) = path.strip_prefix("~/")
&& let Some(home) = dirs::home_dir()
&& home.is_absolute()
{
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),
url.uri().components().count() + if url.has_base() { 0 } else { add },
url.urn().components().count() + if url.has_trail() { 0 } else { add },
)
.expect("Failed to create Loc from home directory");
UrlBuf { loc, scheme: url.scheme.into() }.into()
.expect("Failed to create Loc from home directory")
} else if !url.is_absolute() {
let cwd = CWD.path();
let loc = LocBuf::<PathBuf>::with(
cwd.join(url.loc),
LocBuf::<PathBuf>::with(
cwd.join(path),
url.uri().components().count(),
url.urn().components().count(),
)
.expect("Failed to create Loc from relative path");
UrlBuf { loc, scheme: url.scheme.into() }.into()
.expect("Failed to create Loc from relative path")
} 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()
}
#[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)]
mod tests {
use yazi_shared::url::{AsUrl, UrlCow};

View file

@ -1,7 +1,7 @@
use std::{borrow::Cow, path::{Path, PathBuf}};
use percent_encoding::{AsciiSet, CONTROLS, percent_decode, percent_encode};
use yazi_shared::loc::Loc;
use yazi_shared::path::PathDyn;
const SET: &AsciiSet =
&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<'_> {
fn percent_encode(&self) -> Cow<'_, Path> { self.as_path().percent_encode() }
impl PercentEncoding for PathDyn<'_> {
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 yazi_shared::{loc::LocBuf, url::{UrlBuf, UrlCow, UrlLike}};
use yazi_shared::{path::PathBufDyn, url::{UrlCow, UrlLike}};
pub fn path_relative_to<'a>(
from: impl AsRef<Path>,
to: &'a impl AsRef<Path>,
) -> Result<Cow<'a, Path>> {
Ok(match url_relative_to(from.as_ref().into(), to.as_ref().into())? {
UrlCow::Borrowed { loc, .. } => Cow::Borrowed(loc.as_path()),
UrlCow::Owned { loc, .. } => Cow::Owned(loc.into_path()),
})
pub fn url_relative_to<'a, 'b, U, V>(from: U, to: V) -> Result<UrlCow<'b>>
where
U: Into<UrlCow<'a>>,
V: Into<UrlCow<'b>>,
{
url_relative_to_(from.into(), to.into())
}
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::*;
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) {
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());
@ -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 rest = t_head.into_iter().chain(t_it);
let buf: PathBuf = dots.chain(rest).collect();
Ok(UrlBuf { loc: LocBuf::<PathBuf>::zeroed(buf), scheme: to.scheme().into() }.into())
let buf: PathBuf = dots.chain(rest).collect(); // FIXME: remove PathBuf
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};
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 {
fn path(&self) -> PathBuf { self.0.path() }
fn name(&self) -> Cow<'_, OsStr> { self.0.file_name().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> {
match self {
Self::Regular(entry) | Self::Others { entry, .. } => entry.file_type().await.map(Into::into),
}
}
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};
@ -33,19 +33,16 @@ impl FileBuilder for Gate {
self
}
async fn new(scheme: SchemeRef<'_>) -> io::Result<Self> {
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>
async fn open<U>(&self, url: U) -> io::Result<Self::File>
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 {

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}};
#[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 Gate = super::Gate;
type Me<'b> = Local<'b>;
type ReadDir = super::ReadDir;
type UrlCow = UrlCow<'a>;
async fn absolute<'a, U>(&self, url: &'a U) -> io::Result<UrlCow<'a>>
where
U: AsUrl,
{
let url = url.as_url();
if url.scheme.is_local() {
Ok(absolute_url(url))
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Not a local URL"))
}
async fn absolute(&self) -> io::Result<Self::UrlCow> { Ok(absolute_url(self.url)) }
#[inline]
async fn canonicalize(&self) -> io::Result<UrlBuf> {
tokio::fs::canonicalize(self.path).await.map(Into::into)
}
async fn casefold(&self) -> io::Result<UrlBuf> {
super::casefold(self.path).await.map(Into::into)
}
#[inline]
async fn canonicalize<P>(&self, path: P) -> io::Result<PathBuf>
async fn copy<P>(&self, to: P, attrs: Attrs) -> io::Result<u64>
where
P: AsRef<Path>,
P: AsPathDyn,
{
tokio::fs::canonicalize(path).await
}
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();
let to = to.as_path_dyn().to_os_owned()?;
let from = self.path.to_owned();
Self::copy_impl(from, to, attrs).await
}
#[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
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]
async fn create_dir_all<P>(&self, path: P) -> io::Result<()>
where
P: AsRef<Path>,
{
tokio::fs::create_dir_all(path).await
async fn metadata(&self) -> io::Result<Cha> {
Ok(Cha::new(self.path.file_name().unwrap_or_default(), tokio::fs::metadata(self.path).await?))
}
#[inline]
async fn gate(&self) -> io::Result<Self::Gate> { Ok(Self::Gate::default()) }
#[inline]
async fn hard_link<P, Q>(&self, original: P, link: Q) -> io::Result<()>
where
P: AsRef<Path>,
Q: AsRef<Path>,
{
tokio::fs::hard_link(original, link).await
async fn new<'b>(url: Url<'b>) -> io::Result<Self::Me<'b>> {
match url {
Url::Regular(loc) | Url::Search { loc, .. } => Ok(Self::Me { url, path: loc.as_path() }),
Url::Archive { .. } | Url::Sftp { .. } => {
Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Not a local URL: {url:?}")))
}
}
}
#[inline]
async fn metadata<P>(&self, path: P) -> io::Result<Cha>
where
P: AsRef<Path>,
{
let path = path.as_ref();
Ok(Cha::new(path.file_name().unwrap_or_default(), tokio::fs::metadata(path).await?))
async fn read_dir(self) -> io::Result<Self::ReadDir> {
Ok(match self.url.kind() {
SchemeKind::Regular => Self::ReadDir::Regular(tokio::fs::read_dir(self.path).await?),
SchemeKind::Search => Self::ReadDir::Others {
reader: tokio::fs::read_dir(self.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]
async fn read_dir<P>(&self, path: P) -> io::Result<Self::ReadDir>
where
P: AsRef<Path>,
{
tokio::fs::read_dir(path).await.map(super::ReadDir)
async fn read_link(&self) -> io::Result<PathBufDyn> {
Ok(tokio::fs::read_link(self.path).await?.into())
}
#[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
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]
async fn remove_dir<P>(&self, path: P) -> io::Result<()>
async fn symlink<P, F>(&self, original: P, _is_dir: F) -> io::Result<()>
where
P: AsRef<Path>,
{
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>,
P: AsPathDyn,
F: AsyncFnOnce() -> io::Result<bool>,
{
#[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)]
if _is_dir().await? {
self.symlink_dir(original, link).await
self.symlink_dir(original).await
} else {
self.symlink_file(original, link).await
self.symlink_file(original).await
}
}
#[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
P: AsRef<Path>,
Q: AsRef<Path>,
P: AsPathDyn,
{
let original = original.as_path_dyn().as_os()?;
#[cfg(unix)]
{
tokio::fs::symlink(original, link).await
tokio::fs::symlink(original, self.path).await
}
#[cfg(windows)]
{
tokio::fs::symlink_dir(original, link).await
tokio::fs::symlink_dir(original, self.path).await
}
}
#[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
P: AsRef<Path>,
Q: AsRef<Path>,
P: AsPathDyn,
{
let original = original.as_path_dyn().as_os()?;
#[cfg(unix)]
{
tokio::fs::symlink(original, link).await
tokio::fs::symlink(original, self.path).await
}
#[cfg(windows)]
{
tokio::fs::symlink_file(original, link).await
tokio::fs::symlink_file(original, self.path).await
}
}
#[inline]
async fn symlink_metadata<P>(&self, path: P) -> io::Result<Cha>
where
P: AsRef<Path>,
{
let path = path.as_ref();
Ok(Cha::new(path.file_name().unwrap_or_default(), tokio::fs::symlink_metadata(path).await?))
async fn symlink_metadata(&self) -> io::Result<Cha> {
Ok(Cha::new(
self.path.file_name().unwrap_or_default(),
tokio::fs::symlink_metadata(self.path).await?,
))
}
async fn trash<P>(&self, path: P) -> io::Result<()>
where
P: AsRef<Path>,
{
let path = path.as_ref().to_owned();
async fn trash(&self) -> io::Result<()> {
let path = self.path.to_owned();
tokio::task::spawn_blocking(move || {
#[cfg(target_os = "android")]
{
@ -222,16 +192,18 @@ impl Provider for Local {
}
#[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
P: AsRef<Path>,
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> {
#[cfg(any(target_os = "linux", target_os = "android"))]
{
@ -273,18 +245,18 @@ impl Local {
}
#[inline]
pub async fn read<P>(&self, path: P) -> io::Result<Vec<u8>>
where
P: AsRef<Path>,
{
tokio::fs::read(path).await
pub async fn read(&self) -> io::Result<Vec<u8>> { tokio::fs::read(self.path).await }
#[inline]
pub async fn read_to_string(&self) -> io::Result<String> {
tokio::fs::read_to_string(self.path).await
}
#[inline]
pub async fn read_to_string<P>(&self, path: P) -> io::Result<String>
pub fn regular<P>(path: &'a P) -> Self
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;
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 {
type Entry = super::DirEntry;
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 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};
pub trait Provider {
pub trait Provider: Sized {
type File: AsyncRead + AsyncWrite + Unpin;
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>>>
where
U: AsUrl;
fn absolute(&self) -> impl Future<Output = io::Result<Self::UrlCow>>;
fn canonicalize<P>(&self, path: P) -> impl Future<Output = io::Result<PathBuf>>
where
P: AsRef<Path>;
fn canonicalize(&self) -> impl Future<Output = io::Result<UrlBuf>>;
fn casefold<P>(&self, path: P) -> impl Future<Output = io::Result<PathBuf>>
where
P: AsRef<Path>;
fn casefold(&self) -> impl Future<Output = io::Result<UrlBuf>>;
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
P: AsRef<Path>,
Q: AsRef<Path>;
P: AsPathDyn;
fn create<P>(&self, path: P) -> impl Future<Output = io::Result<Self::File>>
where
P: AsRef<Path>,
{
async move { self.gate().await?.write(true).create(true).truncate(true).open(path).await }
fn create(&self) -> impl Future<Output = io::Result<Self::File>> {
async move { self.gate().write(true).create(true).truncate(true).open(self.url()).await }
}
fn create_dir<P>(&self, path: P) -> impl Future<Output = io::Result<()>>
where
P: AsRef<Path>;
fn create_dir(&self) -> impl Future<Output = io::Result<()>>;
fn create_dir_all<P>(&self, path: P) -> impl Future<Output = io::Result<()>>
where
P: AsRef<Path>,
{
fn create_dir_all(&self) -> impl Future<Output = io::Result<()>> {
async move {
let mut path = path.as_ref();
if path == Path::new("") {
let mut url = self.url();
if url.loc().is_empty() {
return Ok(());
}
let mut stack = Vec::new();
loop {
match self.create_dir(path).await {
match Self::new(url).await?.create_dir().await {
Ok(()) => break,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
if let Some(parent) = path.parent() {
stack.push(path);
path = parent;
if let Some(parent) = url.parent() {
stack.push(url);
url = parent;
} else {
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),
}
}
while let Some(p) = stack.pop() {
match self.create_dir(p).await {
while let Some(u) = stack.pop() {
match Self::new(u).await?.create_dir().await {
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),
}
}
@ -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
P: AsRef<Path>,
Q: AsRef<Path>;
P: AsPathDyn;
fn metadata<P>(&self, path: P) -> impl Future<Output = io::Result<Cha>>
where
P: AsRef<Path>;
fn metadata(&self) -> impl Future<Output = io::Result<Cha>>;
fn open<P>(&self, path: P) -> impl Future<Output = io::Result<Self::File>>
where
P: AsRef<Path>,
{
async move { self.gate().await?.read(true).open(path).await }
fn new<'a>(url: Url<'a>) -> impl Future<Output = io::Result<Self::Me<'a>>>;
fn open(&self) -> impl Future<Output = io::Result<Self::File>> {
async move { self.gate().read(true).open(self.url()).await }
}
fn read_dir<P>(&self, path: P) -> impl Future<Output = io::Result<Self::ReadDir>>
where
P: AsRef<Path>;
fn read_dir(self) -> impl Future<Output = io::Result<Self::ReadDir>>;
fn read_link<P>(&self, path: P) -> impl Future<Output = io::Result<PathBuf>>
where
P: AsRef<Path>;
fn read_link(&self) -> impl Future<Output = io::Result<PathBufDyn>>;
fn remove_dir<P>(&self, path: P) -> impl Future<Output = io::Result<()>>
where
P: AsRef<Path>;
fn remove_dir(&self) -> impl Future<Output = io::Result<()>>;
fn remove_dir_all<P>(&self, path: P) -> impl Future<Output = io::Result<()>>
where
P: AsRef<Path>,
{
async fn remove_dir_all_impl<P>(me: &P, path: &Path) -> io::Result<()>
fn remove_dir_all(&self) -> impl Future<Output = io::Result<()>> {
async fn remove_dir_all_impl<P>(url: Url<'_>) -> io::Result<()>
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? {
let ft = ok_or_not_found!(child.file_type().await, continue);
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 {
me.remove_file(&child.path()).await
P::new(child.url().as_url()).await?.remove_file().await
};
() = 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 {
let path = path.as_ref();
let cha = ok_or_not_found!(self.symlink_metadata(path).await, return Ok(()));
let cha = ok_or_not_found!(self.symlink_metadata().await, return Ok(()));
if cha.is_link() {
self.remove_file(path).await
self.remove_file().await
} 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 = ()>
where
P: AsRef<Path>,
{
let root = root.as_ref().to_path_buf();
fn remove_dir_clean(&self) -> impl Future<Output = ()> {
let root = self.url().to_owned();
async move {
let mut stack = vec![(root, false)];
while let Some((dir, visited)) = stack.pop() {
let Ok(provider) = Self::new(dir.as_url()).await else {
continue;
};
if visited {
self.remove_dir(&dir).await.ok();
} else if let Ok(mut it) = self.read_dir(&dir).await {
provider.remove_dir().await.ok();
} else if let Ok(mut it) = provider.read_dir().await {
stack.push((dir, true));
while let Ok(Some(ent)) = it.next().await {
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<()>>
where
P: AsRef<Path>;
fn remove_file(&self) -> impl Future<Output = io::Result<()>>;
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
P: AsRef<Path>,
Q: AsRef<Path>;
P: AsPathDyn;
fn symlink<P, Q, F>(
&self,
original: P,
link: Q,
_is_dir: F,
) -> impl Future<Output = io::Result<()>>
fn symlink<P, F>(&self, original: P, _is_dir: F) -> impl Future<Output = io::Result<()>>
where
P: AsRef<Path>,
Q: AsRef<Path>,
P: AsPathDyn,
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
P: AsRef<Path>,
Q: AsRef<Path>,
P: AsPathDyn,
{
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
P: AsRef<Path>,
Q: AsRef<Path>,
P: AsPathDyn,
{
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>>
where
P: AsRef<Path>;
fn symlink_metadata(&self) -> impl Future<Output = io::Result<Cha>>;
fn trash<P>(&self, path: P) -> impl Future<Output = io::Result<()>>
where
P: AsRef<Path>;
fn trash(&self) -> impl Future<Output = io::Result<()>>;
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
P: AsRef<Path>,
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 {
type Entry: FileHolder;
#[must_use]
fn next(&mut self) -> impl Future<Output = io::Result<Option<Self::Entry>>>;
}
// --- FileHolder
pub trait FileHolder {
#[must_use]
fn path(&self) -> PathBuf;
fn file_type(&self) -> impl Future<Output = io::Result<ChaType>>;
#[must_use]
fn name(&self) -> Cow<'_, OsStr>;
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
pub trait FileBuilder {
// --- FileBuilder
pub trait FileBuilder: Sized + Default {
type File: AsyncRead + AsyncWrite + Unpin;
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 new(scheme: SchemeRef) -> impl Future<Output = io::Result<Self>>
fn open<U>(&self, url: U) -> impl Future<Output = io::Result<Self::File>>
where
Self: Sized;
fn open<P>(&self, path: P) -> impl Future<Output = io::Result<Self::File>>
where
P: AsRef<Path>;
U: AsUrl;
fn read(&mut self, read: bool) -> &mut Self;

View file

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

View file

@ -1,7 +1,7 @@
use std::cmp::Ordering;
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};
@ -43,8 +43,8 @@ impl FilesSorter {
self.cmp(a.url.ext(), b.url.ext(), self.promote(a, b))
} else {
self.cmp_insensitive(
a.url.ext().map_or(&[], |s| s.as_encoded_bytes()),
b.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.encoded_bytes()),
self.promote(a, b),
)
};

View file

@ -1,6 +1,6 @@
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};
@ -24,22 +24,22 @@ pub trait FsUrl<'a> {
impl<'a> FsUrl<'a> for Url<'a> {
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();
if it.next() == Some(std::path::Component::RootDir) {
path.push(it.as_path().percent_encode());
root.push(it.as_path().percent_encode());
} else {
path.push(".%2F");
path.push(loc.percent_encode());
root.push(".%2F");
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> {
self.scheme.cache().map(|mut root| {
self.scheme().cache().map(|mut root| {
root.push("%lock");
root.push(format!("{:x}", self.hash_u128()));
root
@ -47,7 +47,12 @@ impl<'a> FsUrl<'a> for Url<'a> {
}
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 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 unified_path(self) -> Cow<'a, Path> {
match (self.cache(), self) {
(None, UrlCow::Borrowed { loc, .. }) => loc.as_path().into(),
(None, UrlCow::Owned { loc, .. }) => loc.into_path().into(),
(Some(cache), _) => cache.into(),
match self {
Self::Regular(loc) | Self::Search { loc, .. } => loc.into_path().into(),
Self::RegularRef(loc) | Self::SearchRef { loc, .. } => loc.as_path().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 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 cache: Vec<CmpItem>,
pub cache_name: UrlBuf,
pub word: PathBuf,
pub word: PathBufDyn,
pub ticket: Id,
}
@ -35,7 +35,7 @@ impl IntoLua for ShowOpt {
// --- Item
#[derive(Debug, Clone)]
pub struct CmpItem {
pub name: OsString,
pub name: StrandBuf,
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 serde::Deserialize;
use yazi_shared::{SStr, event::CmdCow};
use yazi_shared::{SStr, event::CmdCow, strand::{AsStrandDyn, StrandLike}};
#[derive(Debug)]
pub struct CopyOpt {
@ -47,14 +47,18 @@ impl FromStr for 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)]
if self == Self::Unix {
return match yazi_fs::path::backslash_to_slash(p.as_ref()) {
Cow::Owned(p) => Cow::Owned(p.into_os_string()),
Cow::Borrowed(p) => Cow::Borrowed(p.as_os_str()),
use yazi_shared::strand::{StrandBufLike, StrandCow};
return match s.as_strand_dyn().backslash_to_slash() {
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 {
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();
}
}
@ -31,7 +34,7 @@ pub fn fd(opt: FdOpt) -> Result<UnboundedReceiver<File>> {
}
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(
std::io::ErrorKind::InvalidInput,
"fd can only search local filesystem",

View file

@ -44,7 +44,7 @@ impl Highlighter {
pub fn abort() { INCR.next(); }
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 mut plain = syntax.is_err();

View file

@ -14,7 +14,7 @@ pub struct RgOpt {
}
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");
};
@ -34,7 +34,10 @@ pub fn rg(opt: RgOpt) -> Result<UnboundedReceiver<File>> {
tokio::spawn(async move {
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();
}
}

View file

@ -14,7 +14,7 @@ pub struct RgaOpt {
}
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");
};
@ -34,7 +34,10 @@ pub fn rga(opt: RgaOpt) -> Result<UnboundedReceiver<File>> {
tokio::spawn(async move {
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();
}
}

View file

@ -148,7 +148,7 @@ fn read_dir(lua: &Lua) -> mlua::Result<Function> {
fn calc_size(lua: &Lua) -> mlua::Result<Function> {
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)
} else {
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);

View file

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

View file

@ -30,7 +30,7 @@ impl Utils {
pub(super) fn image_precache(lua: &Lua) -> mlua::Result<Function> {
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"))
.into_lua_multi(&lua);
};

View file

@ -91,7 +91,7 @@ impl Utils {
CLIPBOARD.set(text).await;
Ok(None)
} 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 tokio::{io::{self, ErrorKind::{AlreadyExists, NotFound}}, sync::mpsc};
use tracing::warn;
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_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 super::{FileInDelete, FileInHardlink, FileInLink, FileInPaste, FileInTrash};
@ -64,7 +64,7 @@ impl File {
let mut dirs = VecDeque::from([task.from.clone()]);
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 {
Err(e) if e.kind() != AlreadyExists => Err(e),
_ => Ok(()),
@ -80,7 +80,7 @@ impl File {
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) {
self.ops.out(task.id, FileOutPaste::New(0));
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> {
let src: Cow<_> = if task.resolve {
let src: PathCow = if task.resolve {
ok_or_not_found!(
provider::read_link(&task.from).await,
return Ok(self.ops.out(task.id, FileOutLink::Succ))
)
.into()
} else if task.from.scheme.covariant(&task.to.scheme) {
task.from.loc.as_path().into()
} else if task.from.scheme().covariant(task.to.scheme()) {
task.from.loc().into()
} else {
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 {
path_relative_to(provider::canonicalize(task.to.parent().unwrap()).await?.loc, &src)?
url_relative_to(provider::canonicalize(task.to.parent().unwrap()).await?, &src)?
} else {
src
};
@ -196,7 +197,7 @@ impl File {
let mut dirs = VecDeque::from([task.from.clone()]);
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 {
Err(e) if e.kind() != AlreadyExists => Err(e),
_ => Ok(()),
@ -212,7 +213,7 @@ impl File {
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.queue(task.spawn(from, to, cha), NORMAL);
}
@ -353,12 +354,12 @@ impl File {
while let Some(res) = it.recv().await {
match res {
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")?;
let lock = task.url.cache_lock().context("Cannot determine cache lock")?;
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;
}
@ -448,7 +449,7 @@ impl File {
pub(crate) async fn upload_do(&self, task: FileInUploadDo) -> Result<(), FileOutUploadDo> {
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")?;
if hash != task.cha.hash_u128() {
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 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;
}
@ -510,7 +511,7 @@ impl File {
url.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;

View file

@ -8,7 +8,7 @@ use yazi_config::{YAZI, plugin::{Fetcher, Preloader}};
use yazi_dds::Pump;
use yazi_parser::{app::PluginOpt, tasks::ProcessOpenOpt};
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 super::{Ongoing, TaskOp};
@ -79,7 +79,13 @@ impl Scheduler {
let mut ongoing = self.ongoing.lock();
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()));
}
@ -112,7 +118,13 @@ impl Scheduler {
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()));
}
@ -148,7 +160,14 @@ impl Scheduler {
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
.ops
.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));
}
if !url.scheme.is_remote() {
if !url.kind().is_remote() {
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 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()));
};

View file

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

View file

@ -1,16 +1,61 @@
use std::fmt::Display;
use crate::BytePredictor;
pub trait BytesExt {
fn display(&self) -> impl Display;
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] {
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 {
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 (left, right) = self.split_at(idx);
Some((left, &right[sep.len()..]))
let (a, b) = self.split_at(idx);
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 std::{borrow::Cow, ffi::OsStr};
use std::borrow::Cow;
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum CharKind {
@ -117,23 +117,3 @@ pub fn replace_to_printable(s: &[String], tab_size: u8) -> String {
}
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)]
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() {
pool::init();

View file

@ -2,7 +2,7 @@ use std::{cmp, ffi::OsStr, fmt::{self, Debug, Formatter}, hash::{Hash, Hasher},
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)]
pub struct LocBuf<P: PathBufLike = PathBuf> {
@ -65,7 +65,8 @@ where
// --- Hash
impl<P> Hash for LocBuf<P>
where
P: PathBufLike,
P: PathBufLike + PathBufUnsafeExt,
for<'a> P::Borrowed<'a>: PathUnsafeExt<'a>,
for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>,
{
fn hash<H: Hasher>(&self, state: &mut H) { self.as_loc().hash(state) }
@ -73,7 +74,8 @@ where
impl<P> Debug for LocBuf<P>
where
P: PathBufLike + Debug,
P: PathBufLike + PathBufUnsafeExt + Debug,
for<'a> P::Borrowed<'a>: PathUnsafeExt<'a>,
for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
@ -87,7 +89,8 @@ where
impl<P> From<P> for LocBuf<P>
where
P: PathBufLike,
P: PathBufLike + PathBufUnsafeExt,
for<'a> P::Borrowed<'a>: PathUnsafeExt<'a>,
for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>,
{
fn from(path: P) -> Self {
@ -106,12 +109,13 @@ impl<T: ?Sized + AsRef<OsStr>> From<&T> for LocBuf<PathBuf> {
impl<P> LocBuf<P>
where
P: PathBufLike,
P: PathBufLike + PathBufUnsafeExt,
for<'a> P::Borrowed<'a>: PathUnsafeExt<'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
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 { inner, uri, urn, _phantom } = Loc::new(&loc.inner, base, trail);
@ -142,9 +146,9 @@ where
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
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 { inner, uri, urn, _phantom } = Loc::floated(&loc.inner, base);
@ -153,6 +157,14 @@ where
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]
pub fn as_loc<'a>(&'a self) -> Loc<'a, P::Borrowed<'a>> {
Loc {
@ -174,16 +186,16 @@ where
#[inline]
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
T: for<'a> AsInnerView<'a, P::InnerRef<'a>>,
T: AsStrandView<'a, P::Strand<'a>>,
{
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();
if new == old {
return;
return Ok(());
}
if self.uri != 0 {
@ -200,31 +212,34 @@ where
self.urn -= old - new;
}
}
Ok(())
}
#[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
'a: 'b,
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
Ok(loc)
}
#[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();
f(&mut inner);
let result = f(&mut inner);
self.inner = Self::from(inner).inner;
result
}
}
// FIXME: macro
impl<P> LocBuf<P>
where
P: PathBufLike,
P: PathBufLike + PathBufUnsafeExt,
for<'a> P::Borrowed<'a>: PathUnsafeExt<'a>,
for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>,
{
#[inline]
@ -246,13 +261,17 @@ where
pub fn has_trail(&self) -> bool { self.as_loc().has_trail() }
#[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]
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]
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> {
@ -360,7 +379,7 @@ mod tests {
for (input, name, expected) in cases {
let mut a: UrlBuf = input.parse()?;
let b: UrlBuf = expected.parse()?;
a.set_name(name);
a.try_set_name(name).unwrap();
assert_eq!(
(a.name(), format!("{a:?}").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 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)]
pub struct Loc<'p, P = &'p Path> {
@ -28,6 +28,13 @@ where
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
impl AsRef<std::path::Path> for Loc<'_, &std::path::Path> {
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>
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
T: AsPathView<'p, P>,
U: AsPathView<'a, P::View<'a>>,
S: AsStrandView<'a, P::Strand<'a>>,
{
let mut loc = Self::bare(path);
loc.uri = loc.inner.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.uri = loc.inner.try_strip_prefix(base).expect("Loc must start with the given base").len();
loc.urn = loc.inner.try_strip_prefix(trail).expect("Loc must start with the given trail").len();
loc
}
@ -98,10 +105,10 @@ where
bail!("URI exceeds the entire URL");
}
if i == urn {
loc.urn = loc.strip_prefix(it.clone()).unwrap().len();
loc.urn = loc.try_strip_prefix(it.clone())?.len();
}
if i == uri {
loc.uri = loc.strip_prefix(it).unwrap().len();
loc.uri = loc.try_strip_prefix(it)?.len();
break;
}
}
@ -113,7 +120,7 @@ where
T: AsPathView<'p, P>,
{
let path = path.as_path_view();
let Some(name) = path.file_name() else {
let Some(name) = path.name() else {
let uri = path.len();
return Self { inner: path, uri, urn: 0, _phantom: PhantomData };
};
@ -140,22 +147,37 @@ where
loc
}
pub fn floated<'a, T, U>(path: T, base: U) -> Self
pub fn floated<'a, T, S>(path: T, base: S) -> Self
where
T: AsPathView<'p, P>,
U: AsPathView<'a, P::View<'a>>,
S: AsStrandView<'a, P::Strand<'a>>,
{
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
}
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]
pub fn as_loc(self) -> Self { self }
#[inline]
pub fn as_path(self) -> P { self.inner }
#[inline]
pub fn is_empty(self) -> bool { self.inner.is_empty() }
#[inline]
pub fn uri(self) -> P {
unsafe {
@ -190,18 +212,6 @@ where
#[inline]
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]
pub fn triple(self) -> (P, P, P) {
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
}
}
// --- 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 crate::path::{AsInnerView, AsPathView, PathInner, PathLike};
use crate::{path::{AsPath, AsPathView, PathBufDyn, PathLike, SetNameError, StartsWithError}, strand::{AsStrandView, StrandLike}};
pub trait PathBufLike
where
Self: 'static,
Self: 'static + AsPath,
{
type Inner: for<'a> AsInnerView<'a, Self::InnerRef<'a>>;
type InnerRef<'a>: PathInner<'a>;
type Strand<'a>: StrandLike<'a>;
type Borrowed<'a>: PathLike<'a> + AsPathView<'a, Self::Borrowed<'a>> + Debug + Hash;
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 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
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;
}
impl PathBufLike for std::path::PathBuf {
type Borrowed<'a> = &'a std::path::Path;
type Inner = std::ffi::OsString;
type InnerRef<'a> = &'a std::ffi::OsStr;
type Strand<'a> = &'a std::ffi::OsStr;
fn borrow(&self) -> Self::Borrowed<'_> { self.as_path() }
fn encoded_bytes(&self) -> &[u8] { self.as_os_str().as_encoded_bytes() }
unsafe fn from_encoded_bytes(bytes: Vec<u8>) -> Self {
Self::from(unsafe { Self::Inner::from_encoded_bytes_unchecked(bytes) })
}
fn into_dyn(self) -> PathBufDyn { PathBufDyn::Os(self) }
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
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) }

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 serde::Serialize;
use super::{AsInnerView, AsPathView};
use crate::path::{PathBufLike, PathLike};
use super::{AsPathView, RsplitOnceError, StartsWithError};
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)]
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> {
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> {
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> {
type Components<'a> = std::path::Components<'a>;
type Display<'a> = std::path::Display<'a>;
type Inner = &'p [u8];
type Owned = PathBufDyn;
type Strand<'a> = Strand<'a>;
type View<'a> = PathDyn<'a>;
fn as_dyn(self) -> PathDyn<'p> { self }
fn components(self) -> Self::Components<'p> {
match self {
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 {
Self::Os(p) => p.extension()?.as_encoded_bytes(),
Self::Os(p) => p.extension()?.into(),
})
}
fn file_name(self) -> Option<Self::Inner> {
Some(match self {
Self::Os(p) => p.file_name()?.as_encoded_bytes(),
})
}
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 has_root(self) -> bool {
match self {
Self::Os(p) => p.has_root(),
}
}
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 {
match self {
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
T: AsPathView<'a, Self::View<'a>>,
T: AsStrandView<'a, Self::Strand<'a>>,
{
Some(match (self, base.as_path_view()) {
(Self::Os(p), PathDyn::Os(q)) => Self::Os(p.strip_prefix(q).ok()?),
Ok(match (self, child.as_strand_view()) {
(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<'_> {
fn eq(&self, other: &PathBufDyn) -> bool { *self == other.borrow() }
}
impl<'a> PathDyn<'a> {
#[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 {
fn eq(&self, other: &PathDyn<'_>) -> bool { matches!(*other, PathDyn::Os(p) if p == *self) }
}
#[inline]
pub fn as_os(self) -> Result<&'a std::path::Path, PathDynError> {
match self {
Self::Os(p) => Ok(p),
}
}
impl Equivalent<PathBufDyn> for PathDyn<'_> {
fn equivalent(&self, key: &PathBufDyn) -> bool { *self == key.borrow() }
#[inline]
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
@ -126,67 +256,20 @@ pub enum PathBufDyn {
Os(std::path::PathBuf),
}
impl PathBufDyn {
pub const fn os_default() -> Self { Self::Os(std::path::PathBuf::new()) }
}
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<std::path::PathBuf> for PathBufDyn {
fn from(value: std::path::PathBuf) -> Self { Self::Os(value) }
}
impl From<&PathBufDyn> for PathBufDyn {
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 {
fn eq(&self, other: &PathDyn<'_>) -> bool { self.borrow() == *other }
}
@ -198,3 +281,131 @@ impl PartialEq<PathDyn<'_>> for &PathBufDyn {
impl Equivalent<PathDyn<'_>> for PathBufDyn {
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