Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: prefer Display over ToString #734

Merged
merged 2 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions yazi-boot/build.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[path = "src/args.rs"]
mod args;

use std::{env, error::Error, fs};
use std::{env, error::Error};

use clap::CommandFactory;
use clap_complete::{generate_to, Shell};
Expand All @@ -18,7 +18,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let bin = "yazi";
let out = "completions";

fs::create_dir_all(out)?;
std::fs::create_dir_all(out)?;
generate_to(Shell::Bash, cmd, bin, out)?;
generate_to(Shell::Fish, cmd, bin, out)?;
generate_to(Shell::Zsh, cmd, bin, out)?;
Expand Down
14 changes: 9 additions & 5 deletions yazi-boot/src/boot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pub struct Boot {
pub file: Option<OsString>,

pub config_dir: PathBuf,
pub flavor_dir: PathBuf,
pub plugin_dir: PathBuf,
pub state_dir: PathBuf,
}
Expand All @@ -36,19 +37,22 @@ impl Boot {

impl Default for Boot {
fn default() -> Self {
let config_dir = Xdg::config_dir().unwrap();
let (cwd, file) = Self::parse_entry(ARGS.entry.as_deref());

let boot = Self {
cwd,
file,

config_dir: Xdg::config_dir().unwrap(),
plugin_dir: Xdg::plugin_dir().unwrap(),
flavor_dir: config_dir.join("flavors"),
plugin_dir: config_dir.join("plugins"),
config_dir,
state_dir: Xdg::state_dir().unwrap(),
};

if !boot.state_dir.is_dir() {
fs::create_dir_all(&boot.state_dir).unwrap();
}
fs::create_dir_all(&boot.flavor_dir).expect("Failed to create flavor directory");
fs::create_dir_all(&boot.plugin_dir).expect("Failed to create plugin directory");
fs::create_dir_all(&boot.state_dir).expect("Failed to create state directory");

boot
}
Expand Down
20 changes: 10 additions & 10 deletions yazi-config/src/keymap/key.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::str::FromStr;
use std::{fmt::{Display, Write}, str::FromStr};

use anyhow::bail;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
Expand Down Expand Up @@ -132,22 +132,22 @@ impl TryFrom<String> for Key {
fn try_from(s: String) -> Result<Self, Self::Error> { Self::from_str(&s) }
}

impl ToString for Key {
fn to_string(&self) -> String {
impl Display for Key {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(c) = self.plain() {
let c = if self.shift { c.to_ascii_uppercase() } else { c };
return if c == ' ' { "<Space>".to_string() } else { c.to_string() };
return if c == ' ' { write!(f, "<Space>") } else { f.write_char(c) };
}

let mut s = "<".to_string();
write!(f, "<")?;
if self.ctrl {
s += "C-";
write!(f, "C-")?;
}
if self.alt {
s += "A-";
write!(f, "A-")?;
}
if self.shift && !matches!(self.code, KeyCode::Char(_)) {
s += "S-";
write!(f, "S-")?;
}

let code = match self.code {
Expand Down Expand Up @@ -181,12 +181,12 @@ impl ToString for Key {

KeyCode::Char(' ') => "Space",
KeyCode::Char(c) => {
s.push(if self.shift { c.to_ascii_uppercase() } else { c });
f.write_char(if self.shift { c.to_ascii_uppercase() } else { c })?;
""
}
_ => "Unknown",
};

s + code + ">"
write!(f, "{}>", code)
}
}
11 changes: 5 additions & 6 deletions yazi-config/src/manager/sorting.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::str::FromStr;
use std::{fmt::Display, str::FromStr};

use anyhow::bail;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -39,17 +39,16 @@ impl TryFrom<String> for SortBy {
fn try_from(s: String) -> Result<Self, Self::Error> { Self::from_str(&s) }
}

impl ToString for SortBy {
fn to_string(&self) -> String {
match self {
impl Display for SortBy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::None => "none",
Self::Modified => "modified",
Self::Created => "created",
Self::Extension => "extension",
Self::Alphabetical => "alphabetical",
Self::Natural => "natural",
Self::Size => "size",
}
.to_string()
})
}
}
11 changes: 5 additions & 6 deletions yazi-core/src/tab/commands/search.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{mem, time::Duration};
use std::{fmt::Display, mem, time::Duration};

use anyhow::bail;
use tokio::pin;
Expand Down Expand Up @@ -26,14 +26,13 @@ impl From<String> for OptType {
}
}

impl ToString for OptType {
fn to_string(&self) -> String {
match self {
impl Display for OptType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Rg => "rg",
Self::Fd => "fd",
Self::None => "none",
}
.to_owned()
})
}
}

Expand Down
11 changes: 5 additions & 6 deletions yazi-core/src/tab/mode.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::BTreeSet, mem};
use std::{collections::BTreeSet, fmt::Display, mem};

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum Mode {
Expand Down Expand Up @@ -37,13 +37,12 @@ impl Mode {
pub fn is_visual(&self) -> bool { matches!(self, Mode::Select(..) | Mode::Unset(..)) }
}

impl ToString for Mode {
fn to_string(&self) -> String {
match self {
impl Display for Mode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Mode::Normal => "normal",
Mode::Select(..) => "select",
Mode::Unset(..) => "unset",
}
.to_string()
})
}
}
2 changes: 1 addition & 1 deletion yazi-plugin/src/elements/bar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl UserData for Bar {
let mut me = ud.borrow_mut::<Self>()?;
match value {
Value::Nil => me.style = None,
Value::Table(tb) => me.style = Some(Style::from(tb).0),
Value::Table(tb) => me.style = Some(Style::try_from(tb)?.0),
Value::UserData(ud) => me.style = Some(ud.borrow::<Style>()?.0),
_ => return Err("expected a Style or Table or nil".into_lua_err()),
}
Expand Down
2 changes: 1 addition & 1 deletion yazi-plugin/src/elements/border.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl UserData for Border {
let mut me = ud.borrow_mut::<Self>()?;
match value {
Value::Nil => me.style = None,
Value::Table(tb) => me.style = Some(Style::from(tb).0),
Value::Table(tb) => me.style = Some(Style::try_from(tb)?.0),
Value::UserData(ud) => me.style = Some(ud.borrow::<Style>()?.0),
_ => return Err("expected a Style or Table or nil".into_lua_err()),
}
Expand Down
4 changes: 2 additions & 2 deletions yazi-plugin/src/elements/gauge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl UserData for Gauge {
methods.add_function("style", |_, (ud, value): (AnyUserData, Value)| {
ud.borrow_mut::<Self>()?.style = match value {
Value::Nil => None,
Value::Table(tb) => Some(Style::from(tb).0),
Value::Table(tb) => Some(Style::try_from(tb)?.0),
Value::UserData(ud) => Some(ud.borrow::<Style>()?.0),
_ => return Err("expected a Style or Table or nil".into_lua_err()),
};
Expand All @@ -60,7 +60,7 @@ impl UserData for Gauge {
methods.add_function("gauge_style", |_, (ud, value): (AnyUserData, Value)| {
ud.borrow_mut::<Self>()?.gauge_style = match value {
Value::Nil => None,
Value::Table(tb) => Some(Style::from(tb).0),
Value::Table(tb) => Some(Style::try_from(tb)?.0),
Value::UserData(ud) => Some(ud.borrow::<Style>()?.0),
_ => return Err("expected a Style or Table or nil".into_lua_err()),
};
Expand Down
2 changes: 1 addition & 1 deletion yazi-plugin/src/elements/line.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl UserData for Line {
let mut me = ud.borrow_mut::<Self>()?;
me.0.style = match value {
Value::Nil => me.0.style.patch(ratatui::style::Style::reset()),
Value::Table(tb) => me.0.style.patch(Style::from(tb).0),
Value::Table(tb) => me.0.style.patch(Style::try_from(tb)?.0),
Value::UserData(ud) => me.0.style.patch(ud.borrow::<Style>()?.0),
_ => return Err("expected a Style or Table or nil".into_lua_err()),
};
Expand Down
2 changes: 1 addition & 1 deletion yazi-plugin/src/elements/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ impl UserData for ListItem {
methods.add_function("style", |_, (ud, value): (AnyUserData, Value)| {
ud.borrow_mut::<Self>()?.style = match value {
Value::Nil => None,
Value::Table(tb) => Some(Style::from(tb).0),
Value::Table(tb) => Some(Style::try_from(tb)?.0),
Value::UserData(ud) => Some(ud.borrow::<Style>()?.0),
_ => return Err("expected a Style or Table or nil".into_lua_err()),
};
Expand Down
2 changes: 1 addition & 1 deletion yazi-plugin/src/elements/paragraph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl UserData for Paragraph {
let mut me = ud.borrow_mut::<Self>()?;
match value {
Value::Nil => me.style = None,
Value::Table(tb) => me.style = Some(Style::from(tb).0),
Value::Table(tb) => me.style = Some(Style::try_from(tb)?.0),
Value::UserData(ud) => me.style = Some(ud.borrow::<Style>()?.0),
_ => return Err("expected a Style or Table or nil".into_lua_err()),
}
Expand Down
2 changes: 1 addition & 1 deletion yazi-plugin/src/elements/span.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl UserData for Span {
methods.add_function("style", |_, (ud, value): (AnyUserData, Value)| {
ud.borrow_mut::<Self>()?.0.style = match value {
Value::Nil => ratatui::style::Style::default(),
Value::Table(tb) => Style::from(tb).0,
Value::Table(tb) => Style::try_from(tb)?.0,
Value::UserData(ud) => ud.borrow::<Style>()?.0,
_ => return Err("expected a Style or Table or nil".into_lua_err()),
};
Expand Down
22 changes: 13 additions & 9 deletions yazi-plugin/src/elements/style.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use mlua::{AnyUserData, ExternalError, Lua, Table, UserData, UserDataMethods, Value};
use std::str::FromStr;

use mlua::{AnyUserData, ExternalError, ExternalResult, Lua, Table, UserData, UserDataMethods, Value};
use yazi_config::theme::Color;

#[derive(Clone, Copy, Default)]
Expand All @@ -19,18 +21,20 @@ impl From<yazi_config::theme::Style> for Style {
fn from(value: yazi_config::theme::Style) -> Self { Self(value.into()) }
}

impl<'a> From<Table<'a>> for Style {
fn from(value: Table) -> Self {
impl<'a> TryFrom<Table<'a>> for Style {
type Error = mlua::Error;

fn try_from(value: Table<'a>) -> Result<Self, Self::Error> {
let mut style = ratatui::style::Style::default();
if let Ok(fg) = value.get::<_, String>("fg") {
style.fg = Color::try_from(fg).ok().map(Into::into);
if let Ok(fg) = value.raw_get::<_, mlua::String>("fg") {
style.fg = Some(Color::from_str(fg.to_str()?).into_lua_err()?.into());
}
if let Ok(bg) = value.get::<_, String>("bg") {
style.bg = Color::try_from(bg).ok().map(Into::into);
if let Ok(bg) = value.raw_get::<_, mlua::String>("bg") {
style.bg = Some(Color::from_str(bg.to_str()?).into_lua_err()?.into());
}
style.add_modifier =
ratatui::style::Modifier::from_bits_truncate(value.raw_get("modifier").unwrap_or_default());
Self(style)
Ok(Self(style))
}
}

Expand Down Expand Up @@ -84,7 +88,7 @@ impl UserData for Style {
{
let mut me = ud.borrow_mut::<Self>()?;
me.0 = me.0.patch(match value {
Value::Table(tb) => Style::from(tb).0,
Value::Table(tb) => Style::try_from(tb)?.0,
Value::UserData(ud) => ud.borrow::<Style>()?.0,
_ => return Err("expected a Style or Table".into_lua_err()),
});
Expand Down
2 changes: 1 addition & 1 deletion yazi-plugin/src/utils/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl Utils {
let (tx, mut rx) = mpsc::channel::<usize>(1);

let mut cands = Vec::with_capacity(30);
for (i, cand) in t.get::<_, Table>("cands")?.sequence_values::<Table>().enumerate() {
for (i, cand) in t.raw_get::<_, Table>("cands")?.sequence_values::<Table>().enumerate() {
let cand = cand?;
cands.push(Control {
on: Self::parse_keys(cand.raw_get("on")?)?,
Expand Down
19 changes: 11 additions & 8 deletions yazi-shared/src/fs/url.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{ffi::{OsStr, OsString}, fmt::{Debug, Formatter}, ops::{Deref, DerefMut}, path::{Path, PathBuf}};
use std::{ffi::{OsStr, OsString}, fmt::{Debug, Display, Formatter}, ops::{Deref, DerefMut}, path::{Path, PathBuf}};

use percent_encoding::{percent_decode_str, percent_encode, AsciiSet, CONTROLS};

Expand Down Expand Up @@ -95,22 +95,25 @@ impl AsRef<OsStr> for Url {
fn as_ref(&self) -> &OsStr { self.path.as_os_str() }
}

impl ToString for Url {
fn to_string(&self) -> String {
impl Display for Url {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.scheme == UrlScheme::Regular {
return self.path.to_string_lossy().into_owned();
return f.write_str(&self.path.to_string_lossy());
}

let scheme = match self.scheme {
UrlScheme::Regular => unreachable!(),
UrlScheme::Search => "search://",
UrlScheme::Archive => "archive://",
};

let path = percent_encode(self.path.as_os_str().as_encoded_bytes(), ENCODE_SET);
let frag =
Some(&self.frag).filter(|&s| !s.is_empty()).map(|s| format!("#{s}")).unwrap_or_default();
format!("{scheme}{path}{frag}")

write!(f, "{scheme}{path}")?;
if !self.frag.is_empty() {
write!(f, "#{}", self.frag)?;
}

Ok(())
}
}

Expand Down
11 changes: 5 additions & 6 deletions yazi-shared/src/layer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::str::FromStr;
use std::{fmt::Display, str::FromStr};

use anyhow::bail;

Expand All @@ -15,9 +15,9 @@ pub enum Layer {
Which,
}

impl ToString for Layer {
fn to_string(&self) -> String {
match self {
impl Display for Layer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::App => "app",
Self::Manager => "manager",
Self::Tasks => "tasks",
Expand All @@ -26,8 +26,7 @@ impl ToString for Layer {
Self::Help => "help",
Self::Completion => "completion",
Self::Which => "which",
}
.to_string()
})
}
}

Expand Down
3 changes: 0 additions & 3 deletions yazi-shared/src/xdg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,6 @@ impl Xdg {
}
}

#[inline]
pub fn plugin_dir() -> Option<PathBuf> { Self::config_dir().map(|p| p.join("plugins")) }

pub fn state_dir() -> Option<PathBuf> {
#[cfg(windows)]
{
Expand Down