Refactor clipboard to make it easier to feature gate std::process

pull/1872/head
Blaž Hrastnik 2 years ago
parent 4940db3e2d
commit 8611c5b84e
No known key found for this signature in database
GPG Key ID: 1238B9C4AD889640

@ -16,12 +16,12 @@ pub trait ClipboardProvider: std::fmt::Debug {
macro_rules! command_provider { macro_rules! command_provider {
(paste => $get_prg:literal $( , $get_arg:literal )* ; copy => $set_prg:literal $( , $set_arg:literal )* ; ) => {{ (paste => $get_prg:literal $( , $get_arg:literal )* ; copy => $set_prg:literal $( , $set_arg:literal )* ; ) => {{
Box::new(provider::CommandProvider { Box::new(provider::command::Provider {
get_cmd: provider::CommandConfig { get_cmd: provider::command::Config {
prg: $get_prg, prg: $get_prg,
args: &[ $( $get_arg ),* ], args: &[ $( $get_arg ),* ],
}, },
set_cmd: provider::CommandConfig { set_cmd: provider::command::Config {
prg: $set_prg, prg: $set_prg,
args: &[ $( $set_arg ),* ], args: &[ $( $set_arg ),* ],
}, },
@ -35,20 +35,20 @@ macro_rules! command_provider {
primary_paste => $pr_get_prg:literal $( , $pr_get_arg:literal )* ; primary_paste => $pr_get_prg:literal $( , $pr_get_arg:literal )* ;
primary_copy => $pr_set_prg:literal $( , $pr_set_arg:literal )* ; primary_copy => $pr_set_prg:literal $( , $pr_set_arg:literal )* ;
) => {{ ) => {{
Box::new(provider::CommandProvider { Box::new(provider::command::Provider {
get_cmd: provider::CommandConfig { get_cmd: provider::command::Config {
prg: $get_prg, prg: $get_prg,
args: &[ $( $get_arg ),* ], args: &[ $( $get_arg ),* ],
}, },
set_cmd: provider::CommandConfig { set_cmd: provider::command::Config {
prg: $set_prg, prg: $set_prg,
args: &[ $( $set_arg ),* ], args: &[ $( $set_arg ),* ],
}, },
get_primary_cmd: Some(provider::CommandConfig { get_primary_cmd: Some(provider::command::Config {
prg: $pr_get_prg, prg: $pr_get_prg,
args: &[ $( $pr_get_arg ),* ], args: &[ $( $pr_get_arg ),* ],
}), }),
set_primary_cmd: Some(provider::CommandConfig { set_primary_cmd: Some(provider::command::Config {
prg: $pr_set_prg, prg: $pr_set_prg,
args: &[ $( $pr_set_arg ),* ], args: &[ $( $pr_set_arg ),* ],
}), }),
@ -63,6 +63,8 @@ pub fn get_clipboard_provider() -> Box<dyn ClipboardProvider> {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub fn get_clipboard_provider() -> Box<dyn ClipboardProvider> { pub fn get_clipboard_provider() -> Box<dyn ClipboardProvider> {
use command::exists;
if exists("pbcopy") && exists("pbpaste") { if exists("pbcopy") && exists("pbpaste") {
command_provider! { command_provider! {
paste => "pbpaste"; paste => "pbpaste";
@ -75,6 +77,7 @@ pub fn get_clipboard_provider() -> Box<dyn ClipboardProvider> {
#[cfg(not(any(windows, target_os = "macos")))] #[cfg(not(any(windows, target_os = "macos")))]
pub fn get_clipboard_provider() -> Box<dyn ClipboardProvider> { pub fn get_clipboard_provider() -> Box<dyn ClipboardProvider> {
use provider::command::{env_var_is_set, exists, is_exit_success};
// TODO: support for user-defined provider, probably when we have plugin support by setting a // TODO: support for user-defined provider, probably when we have plugin support by setting a
// variable? // variable?
@ -116,26 +119,9 @@ pub fn get_clipboard_provider() -> Box<dyn ClipboardProvider> {
} }
} }
fn exists(executable_name: &str) -> bool {
which::which(executable_name).is_ok()
}
fn env_var_is_set(env_var_name: &str) -> bool {
std::env::var_os(env_var_name).is_some()
}
fn is_exit_success(program: &str, args: &[&str]) -> bool {
std::process::Command::new(program)
.args(args)
.output()
.ok()
.and_then(|out| out.status.success().then(|| ())) // TODO: use then_some when stabilized
.is_some()
}
mod provider { mod provider {
use super::{ClipboardProvider, ClipboardType}; use super::{ClipboardProvider, ClipboardType};
use anyhow::{bail, Context as _, Result}; use anyhow::Result;
use std::borrow::Cow; use std::borrow::Cow;
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
@ -210,94 +196,116 @@ mod provider {
} }
} }
#[derive(Debug)] pub mod command {
pub struct CommandConfig { use super::*;
pub prg: &'static str, use anyhow::{bail, Context as _, Result};
pub args: &'static [&'static str],
}
impl CommandConfig { pub fn exists(executable_name: &str) -> bool {
fn execute(&self, input: Option<&str>, pipe_output: bool) -> Result<Option<String>> { which::which(executable_name).is_ok()
use std::io::Write; }
use std::process::{Command, Stdio};
let stdin = input.map(|_| Stdio::piped()).unwrap_or_else(Stdio::null);
let stdout = pipe_output.then(Stdio::piped).unwrap_or_else(Stdio::null);
let mut child = Command::new(self.prg)
.args(self.args)
.stdin(stdin)
.stdout(stdout)
.stderr(Stdio::null())
.spawn()?;
if let Some(input) = input {
let mut stdin = child.stdin.take().context("stdin is missing")?;
stdin
.write_all(input.as_bytes())
.context("couldn't write in stdin")?;
}
// TODO: add timer? pub fn env_var_is_set(env_var_name: &str) -> bool {
let output = child.wait_with_output()?; std::env::var_os(env_var_name).is_some()
}
if !output.status.success() { pub fn is_exit_success(program: &str, args: &[&str]) -> bool {
bail!("clipboard provider {} failed", self.prg); std::process::Command::new(program)
} .args(args)
.output()
.ok()
.and_then(|out| out.status.success().then(|| ())) // TODO: use then_some when stabilized
.is_some()
}
if pipe_output { #[derive(Debug)]
Ok(Some(String::from_utf8(output.stdout)?)) pub struct Config {
} else { pub prg: &'static str,
Ok(None) pub args: &'static [&'static str],
}
} }
}
#[derive(Debug)] impl Config {
pub struct CommandProvider { fn execute(&self, input: Option<&str>, pipe_output: bool) -> Result<Option<String>> {
pub get_cmd: CommandConfig, use std::io::Write;
pub set_cmd: CommandConfig, use std::process::{Command, Stdio};
pub get_primary_cmd: Option<CommandConfig>,
pub set_primary_cmd: Option<CommandConfig>, let stdin = input.map(|_| Stdio::piped()).unwrap_or_else(Stdio::null);
} let stdout = pipe_output.then(Stdio::piped).unwrap_or_else(Stdio::null);
let mut child = Command::new(self.prg)
.args(self.args)
.stdin(stdin)
.stdout(stdout)
.stderr(Stdio::null())
.spawn()?;
if let Some(input) = input {
let mut stdin = child.stdin.take().context("stdin is missing")?;
stdin
.write_all(input.as_bytes())
.context("couldn't write in stdin")?;
}
impl ClipboardProvider for CommandProvider { // TODO: add timer?
fn name(&self) -> Cow<str> { let output = child.wait_with_output()?;
if self.get_cmd.prg != self.set_cmd.prg {
Cow::Owned(format!("{}+{}", self.get_cmd.prg, self.set_cmd.prg)) if !output.status.success() {
} else { bail!("clipboard provider {} failed", self.prg);
Cow::Borrowed(self.get_cmd.prg) }
if pipe_output {
Ok(Some(String::from_utf8(output.stdout)?))
} else {
Ok(None)
}
} }
} }
fn get_contents(&self, clipboard_type: ClipboardType) -> Result<String> { #[derive(Debug)]
match clipboard_type { pub struct Provider {
ClipboardType::Clipboard => Ok(self pub get_cmd: Config,
.get_cmd pub set_cmd: Config,
.execute(None, true)? pub get_primary_cmd: Option<Config>,
.context("output is missing")?), pub set_primary_cmd: Option<Config>,
ClipboardType::Selection => { }
if let Some(cmd) = &self.get_primary_cmd {
return cmd.execute(None, true)?.context("output is missing");
}
Ok(String::new()) impl ClipboardProvider for Provider {
fn name(&self) -> Cow<str> {
if self.get_cmd.prg != self.set_cmd.prg {
Cow::Owned(format!("{}+{}", self.get_cmd.prg, self.set_cmd.prg))
} else {
Cow::Borrowed(self.get_cmd.prg)
} }
} }
}
fn set_contents(&mut self, value: String, clipboard_type: ClipboardType) -> Result<()> { fn get_contents(&self, clipboard_type: ClipboardType) -> Result<String> {
let cmd = match clipboard_type { match clipboard_type {
ClipboardType::Clipboard => &self.set_cmd, ClipboardType::Clipboard => Ok(self
ClipboardType::Selection => { .get_cmd
if let Some(cmd) = &self.set_primary_cmd { .execute(None, true)?
cmd .context("output is missing")?),
} else { ClipboardType::Selection => {
return Ok(()); if let Some(cmd) = &self.get_primary_cmd {
return cmd.execute(None, true)?.context("output is missing");
}
Ok(String::new())
} }
} }
}; }
cmd.execute(Some(&value), false).map(|_| ())
fn set_contents(&mut self, value: String, clipboard_type: ClipboardType) -> Result<()> {
let cmd = match clipboard_type {
ClipboardType::Clipboard => &self.set_cmd,
ClipboardType::Selection => {
if let Some(cmd) = &self.set_primary_cmd {
cmd
} else {
return Ok(());
}
}
};
cmd.execute(Some(&value), false).map(|_| ())
}
} }
} }
} }

Loading…
Cancel
Save