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: use Cmd instead of Exec #604

Merged
merged 2 commits into from
Jan 31, 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
2 changes: 1 addition & 1 deletion cspell.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"language":"en","words":["Punct","KEYMAP","splitn","crossterm","YAZI","unar","peekable","ratatui","syntect","pbpaste","pbcopy","ffmpegthumbnailer","oneshot","Posix","Lsar","XADDOS","zoxide","cands","Deque","precache","imageops","IFBLK","IFCHR","IFDIR","IFIFO","IFLNK","IFMT","IFSOCK","IRGRP","IROTH","IRUSR","ISGID","ISUID","ISVTX","IWGRP","IWOTH","IWUSR","IXGRP","IXOTH","IXUSR","libc","winsize","TIOCGWINSZ","xpixel","ypixel","ioerr","appender","Catppuccin","macchiato","gitmodules","Dotfiles","bashprofile","vimrc","flac","webp","exiftool","mediainfo","ripgrep","nvim","indexmap","indexmap","unwatch","canonicalize","serde","fsevent","Ueberzug","iterm","wezterm","sixel","chafa","ueberzugpp","️ Überzug","️ Überzug","Konsole","Alacritty","Überzug","pkgs","paru","unarchiver","pdftoppm","poppler","prebuild","singlefile","jpegopt","EXIF","rustfmt","mktemp","nanos","xclip","xsel","natord","Mintty","nixos","nixpkgs","SIGTSTP","SIGCONT","SIGCONT","mlua","nonstatic","userdata","metatable","natsort","backstack","luajit","Succ","Succ","cand","fileencoding","foldmethod","lightgreen","darkgray","lightred","lightyellow","lightcyan","nushell","msvc","aarch","linemode","sxyazi","rsplit","ZELLIJ","bitflags","bitflags","USERPROFILE","Neovim","vergen","gitcl","Renderable","preloaders","prec","imagesize","Upserting","prio","Ghostty","Catmull","Lanczos"],"flagWords":[],"version":"0.2"}
{"flagWords":[],"words":["Punct","KEYMAP","splitn","crossterm","YAZI","unar","peekable","ratatui","syntect","pbpaste","pbcopy","ffmpegthumbnailer","oneshot","Posix","Lsar","XADDOS","zoxide","cands","Deque","precache","imageops","IFBLK","IFCHR","IFDIR","IFIFO","IFLNK","IFMT","IFSOCK","IRGRP","IROTH","IRUSR","ISGID","ISUID","ISVTX","IWGRP","IWOTH","IWUSR","IXGRP","IXOTH","IXUSR","libc","winsize","TIOCGWINSZ","xpixel","ypixel","ioerr","appender","Catppuccin","macchiato","gitmodules","Dotfiles","bashprofile","vimrc","flac","webp","exiftool","mediainfo","ripgrep","nvim","indexmap","indexmap","unwatch","canonicalize","serde","fsevent","Ueberzug","iterm","wezterm","sixel","chafa","ueberzugpp","️ Überzug","️ Überzug","Konsole","Alacritty","Überzug","pkgs","paru","unarchiver","pdftoppm","poppler","prebuild","singlefile","jpegopt","EXIF","rustfmt","mktemp","nanos","xclip","xsel","natord","Mintty","nixos","nixpkgs","SIGTSTP","SIGCONT","SIGCONT","mlua","nonstatic","userdata","metatable","natsort","backstack","luajit","Succ","Succ","cand","fileencoding","foldmethod","lightgreen","darkgray","lightred","lightyellow","lightcyan","nushell","msvc","aarch","linemode","sxyazi","rsplit","ZELLIJ","bitflags","bitflags","USERPROFILE","Neovim","vergen","gitcl","Renderable","preloaders","prec","imagesize","Upserting","prio","Ghostty","Catmull","Lanczos","cmds"],"language":"en","version":"0.2"}
33 changes: 29 additions & 4 deletions yazi-config/src/keymap/control.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
use std::{borrow::Cow, collections::VecDeque};
use std::{borrow::Cow, collections::VecDeque, ops::Deref};

use serde::Deserialize;
use yazi_shared::event::Exec;
use yazi_shared::event::Cmd;

use super::Key;

#[derive(Debug, Deserialize)]
pub struct Control {
pub on: Vec<Key>,
#[serde(deserialize_with = "super::exec_deserialize")]
pub exec: Vec<Exec>,
pub exec: Vec<Cmd>,
pub desc: Option<String>,
}

impl Control {
pub fn to_seq(&self) -> VecDeque<Exec> {
#[inline]
pub fn to_seq(&self) -> VecDeque<Cmd> {
self.exec.iter().map(|e| e.clone_without_data()).collect()
}
}
Expand All @@ -41,3 +42,27 @@ impl Control {
|| self.on().to_lowercase().contains(&s)
}
}

pub enum ControlCow {
Owned(Control),
Borrowed(&'static Control),
}

impl From<&'static Control> for ControlCow {
fn from(c: &'static Control) -> Self { Self::Borrowed(c) }
}

impl From<Control> for ControlCow {
fn from(c: Control) -> Self { Self::Owned(c) }
}

impl Deref for ControlCow {
type Target = Control;

fn deref(&self) -> &Self::Target {
match self {
Self::Owned(c) => c,
Self::Borrowed(c) => c,
}
}
}
24 changes: 12 additions & 12 deletions yazi-config/src/keymap/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,36 @@ use std::fmt;

use anyhow::{bail, Result};
use serde::{de::{self, Visitor}, Deserializer};
use yazi_shared::event::Exec;
use yazi_shared::event::Cmd;

pub(super) fn exec_deserialize<'de, D>(deserializer: D) -> Result<Vec<Exec>, D::Error>
pub(super) fn exec_deserialize<'de, D>(deserializer: D) -> Result<Vec<Cmd>, D::Error>
where
D: Deserializer<'de>,
{
struct ExecVisitor;

fn parse(s: &str) -> Result<Exec> {
fn parse(s: &str) -> Result<Cmd> {
let s = shell_words::split(s)?;
if s.is_empty() {
bail!("`exec` cannot be empty");
}

let mut exec = Exec { cmd: s[0].clone(), ..Default::default() };
let mut cmd = Cmd { name: s[0].clone(), ..Default::default() };
for arg in s.into_iter().skip(1) {
if arg.starts_with("--") {
let mut arg = arg.splitn(2, '=');
let key = arg.next().unwrap().trim_start_matches('-');
let val = arg.next().unwrap_or("").to_string();
exec.named.insert(key.to_string(), val);
cmd.named.insert(key.to_string(), val);
} else {
exec.args.push(arg);
cmd.args.push(arg);
}
}
Ok(exec)
Ok(cmd)
}

impl<'de> Visitor<'de> for ExecVisitor {
type Value = Vec<Exec>;
type Value = Vec<Cmd>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a `exec` string or array of strings within [keymap]")
Expand All @@ -41,14 +41,14 @@ where
where
A: de::SeqAccess<'de>,
{
let mut execs = vec![];
let mut cmds = vec![];
while let Some(value) = &seq.next_element::<String>()? {
execs.push(parse(value).map_err(de::Error::custom)?);
cmds.push(parse(value).map_err(de::Error::custom)?);
}
if execs.is_empty() {
if cmds.is_empty() {
return Err(de::Error::custom("`exec` within [keymap] cannot be empty"));
}
Ok(execs)
Ok(cmds)
}

fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
Expand Down
8 changes: 4 additions & 4 deletions yazi-config/src/plugin/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ use std::fmt;

use anyhow::Result;
use serde::{de::{self, Visitor}, Deserializer};
use yazi_shared::event::Exec;
use yazi_shared::event::Cmd;

pub(super) fn exec_deserialize<'de, D>(deserializer: D) -> Result<Exec, D::Error>
pub(super) fn exec_deserialize<'de, D>(deserializer: D) -> Result<Cmd, D::Error>
where
D: Deserializer<'de>,
{
struct ExecVisitor;

impl<'de> Visitor<'de> for ExecVisitor {
type Value = Exec;
type Value = Cmd;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a `exec` string or array of strings")
Expand All @@ -31,7 +31,7 @@ where
if value.is_empty() {
return Err(de::Error::custom("`exec` within [plugin] cannot be empty"));
}
Ok(Exec { cmd: value.to_owned(), ..Default::default() })
Ok(Cmd { name: value.to_owned(), ..Default::default() })
}
}

Expand Down
5 changes: 3 additions & 2 deletions yazi-config/src/plugin/plugin.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::path::Path;

use serde::Deserialize;
use yazi_shared::{event::Exec, Condition, MIME_DIR};
use yazi_shared::{event::Cmd, Condition, MIME_DIR};

use crate::{pattern::Pattern, plugin::MAX_PRELOADERS, Preset, Priority, MERGED_YAZI};

Expand All @@ -18,8 +18,9 @@ pub struct PluginRule {
pub cond: Option<Condition>,
pub name: Option<Pattern>,
pub mime: Option<Pattern>,
#[serde(rename = "exec")]
#[serde(deserialize_with = "super::exec_deserialize")]
pub exec: Exec,
pub cmd: Cmd,
#[serde(default)]
pub sync: bool,
#[serde(default)]
Expand Down
4 changes: 2 additions & 2 deletions yazi-config/src/plugin/props.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ use crate::Priority;
#[derive(Debug, Clone)]
pub struct PluginProps {
pub id: u8,
pub cmd: String,
pub name: String,
pub multi: bool,
pub prio: Priority,
}

impl From<&PluginRule> for PluginProps {
fn from(rule: &PluginRule) -> Self {
Self { id: rule.id, cmd: rule.exec.cmd.to_owned(), multi: rule.multi, prio: rule.prio }
Self { id: rule.id, name: rule.cmd.name.to_owned(), multi: rule.multi, prio: rule.prio }
}
}
8 changes: 4 additions & 4 deletions yazi-core/src/completion/commands/arrow.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use yazi_shared::{event::Exec, render};
use yazi_shared::{event::Cmd, render};

use crate::completion::Completion;

pub struct Opt {
step: isize,
}

impl From<Exec> for Opt {
fn from(mut e: Exec) -> Self {
Self { step: e.take_first().and_then(|s| s.parse().ok()).unwrap_or(0) }
impl From<Cmd> for Opt {
fn from(mut c: Cmd) -> Self {
Self { step: c.take_first().and_then(|s| s.parse().ok()).unwrap_or(0) }
}
}

Expand Down
8 changes: 4 additions & 4 deletions yazi-core/src/completion/commands/close.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
use yazi_shared::{emit, event::Exec, render, Layer};
use yazi_shared::{emit, event::Cmd, render, Layer};

use crate::{completion::Completion, input::Input};

pub struct Opt {
submit: bool,
}

impl From<Exec> for Opt {
fn from(e: Exec) -> Self { Self { submit: e.named.contains_key("submit") } }
impl From<Cmd> for Opt {
fn from(c: Cmd) -> Self { Self { submit: c.named.contains_key("submit") } }
}

impl Completion {
#[inline]
pub fn _close() {
emit!(Call(Exec::call("close", vec![]), Layer::Completion));
emit!(Call(Cmd::new("close"), Layer::Completion));
}

pub fn close(&mut self, opt: impl Into<Opt>) {
Expand Down
14 changes: 7 additions & 7 deletions yazi-core/src/completion/commands/show.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{mem, ops::ControlFlow};

use yazi_shared::{event::Exec, render};
use yazi_shared::{event::Cmd, render};

use crate::completion::Completion;

Expand All @@ -13,13 +13,13 @@ pub struct Opt {
ticket: usize,
}

impl From<Exec> for Opt {
fn from(mut e: Exec) -> Self {
impl From<Cmd> for Opt {
fn from(mut c: Cmd) -> Self {
Self {
cache: mem::take(&mut e.args),
cache_name: e.take_name("cache-name").unwrap_or_default(),
word: e.take_name("word").unwrap_or_default(),
ticket: e.take_name("ticket").and_then(|v| v.parse().ok()).unwrap_or(0),
cache: mem::take(&mut c.args),
cache_name: c.take_name("cache-name").unwrap_or_default(),
word: c.take_name("word").unwrap_or_default(),
ticket: c.take_name("ticket").and_then(|v| v.parse().ok()).unwrap_or(0),
}
}
}
Expand Down
19 changes: 8 additions & 11 deletions yazi-core/src/completion/commands/trigger.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{mem, path::{MAIN_SEPARATOR, MAIN_SEPARATOR_STR}};

use tokio::fs;
use yazi_shared::{emit, event::Exec, render, Layer};
use yazi_shared::{emit, event::Cmd, render, Layer};

use crate::completion::Completion;

Expand All @@ -10,11 +10,11 @@ pub struct Opt {
ticket: usize,
}

impl From<Exec> for Opt {
fn from(mut e: Exec) -> Self {
impl From<Cmd> for Opt {
fn from(mut c: Cmd) -> Self {
Self {
word: e.take_first().unwrap_or_default(),
ticket: e.take_name("ticket").and_then(|s| s.parse().ok()).unwrap_or(0),
word: c.take_first().unwrap_or_default(),
ticket: c.take_name("ticket").and_then(|s| s.parse().ok()).unwrap_or(0),
}
}
}
Expand All @@ -23,7 +23,7 @@ impl Completion {
#[inline]
pub fn _trigger(word: &str, ticket: usize) {
emit!(Call(
Exec::call("trigger", vec![word.to_owned()]).with("ticket", ticket),
Cmd::args("trigger", vec![word.to_owned()]).with("ticket", ticket),
Layer::Completion
));
}
Expand All @@ -39,10 +39,7 @@ impl Completion {

if self.caches.contains_key(&parent) {
return self.show(
Exec::call("show", vec![])
.with("cache-name", parent)
.with("word", child)
.with("ticket", opt.ticket),
Cmd::new("show").with("cache-name", parent).with("word", child).with("ticket", opt.ticket),
);
}

Expand All @@ -64,7 +61,7 @@ impl Completion {

if !cache.is_empty() {
emit!(Call(
Exec::call("show", cache)
Cmd::args("show", cache)
.with("cache-name", parent)
.with("word", child)
.with("ticket", ticket),
Expand Down
8 changes: 4 additions & 4 deletions yazi-core/src/folder/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{ffi::OsStr, ops::Range};

use anyhow::Result;
use regex::bytes::{Regex, RegexBuilder};
use yazi_shared::event::Exec;
use yazi_shared::event::Cmd;

pub struct Filter {
raw: String,
Expand Down Expand Up @@ -43,9 +43,9 @@ pub enum FilterCase {
Insensitive,
}

impl From<&Exec> for FilterCase {
fn from(e: &Exec) -> Self {
match (e.named.contains_key("smart"), e.named.contains_key("insensitive")) {
impl From<&Cmd> for FilterCase {
fn from(c: &Cmd) -> Self {
match (c.named.contains_key("smart"), c.named.contains_key("insensitive")) {
(true, _) => Self::Smart,
(_, false) => Self::Sensitive,
(_, true) => Self::Insensitive,
Expand Down
8 changes: 4 additions & 4 deletions yazi-core/src/help/commands/arrow.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use yazi_shared::{event::Exec, render};
use yazi_shared::{event::Cmd, render};

use crate::help::Help;

pub struct Opt {
step: isize,
}

impl From<Exec> for Opt {
fn from(mut e: Exec) -> Self {
Self { step: e.take_first().and_then(|s| s.parse().ok()).unwrap_or(0) }
impl From<Cmd> for Opt {
fn from(mut c: Cmd) -> Self {
Self { step: c.take_first().and_then(|s| s.parse().ok()).unwrap_or(0) }
}
}
impl From<isize> for Opt {
Expand Down
4 changes: 2 additions & 2 deletions yazi-core/src/help/commands/escape.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use yazi_shared::{event::Exec, render};
use yazi_shared::{event::Cmd, render};

use crate::help::Help;

impl Help {
pub fn escape(&mut self, _: Exec) {
pub fn escape(&mut self, _: Cmd) {
if self.in_filter.is_none() {
return self.toggle(self.layer);
}
Expand Down
4 changes: 2 additions & 2 deletions yazi-core/src/help/commands/filter.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use yazi_config::popup::{Offset, Origin, Position};
use yazi_shared::{event::Exec, render};
use yazi_shared::{event::Cmd, render};

use crate::{help::Help, input::Input};

impl Help {
pub fn filter(&mut self, _: Exec) {
pub fn filter(&mut self, _: Cmd) {
let mut input = Input::default();
input.position = Position::new(Origin::BottomLeft, Offset::line());

Expand Down
6 changes: 3 additions & 3 deletions yazi-core/src/input/commands/backspace.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use yazi_shared::{event::Exec, render};
use yazi_shared::{event::Cmd, render};

use crate::input::Input;

pub struct Opt {
under: bool,
}

impl From<Exec> for Opt {
fn from(e: Exec) -> Self { Self { under: e.named.contains_key("under") } }
impl From<Cmd> for Opt {
fn from(c: Cmd) -> Self { Self { under: c.named.contains_key("under") } }
}
impl From<bool> for Opt {
fn from(under: bool) -> Self { Self { under } }
Expand Down
Loading
Loading