feat(shell): expand Command APIs (#526)

Co-authored-by: Amr Bashir <amr.bashir2015@gmail.com>
pull/539/head
Lucas Fernandes Nogueira 2 years ago committed by GitHub
parent be591d2feb
commit 5b3210c224
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,5 @@
---
"shell": "patch"
---
Added `Command::arg`, `Command::env` and changed `Command::new` input type.

1027
Cargo.lock generated

File diff suppressed because it is too large Load Diff

@ -13,6 +13,8 @@
use std::{ use std::{
collections::HashMap, collections::HashMap,
ffi::OsStr,
path::Path,
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
@ -45,7 +47,7 @@ pub struct Shell<R: Runtime> {
impl<R: Runtime> Shell<R> { impl<R: Runtime> Shell<R> {
/// Creates a new Command for launching the given program. /// Creates a new Command for launching the given program.
pub fn command(&self, program: impl Into<String>) -> Command { pub fn command(&self, program: impl AsRef<OsStr>) -> Command {
Command::new(program) Command::new(program)
} }
@ -53,7 +55,7 @@ impl<R: Runtime> Shell<R> {
/// ///
/// A sidecar program is a embedded external binary in order to make your application work /// A sidecar program is a embedded external binary in order to make your application work
/// or to prevent users having to install additional dependencies (e.g. Node.js, Python, etc). /// or to prevent users having to install additional dependencies (e.g. Node.js, Python, etc).
pub fn sidecar(&self, program: impl Into<String>) -> Result<Command> { pub fn sidecar(&self, program: impl AsRef<Path>) -> Result<Command> {
Command::new_sidecar(program) Command::new_sidecar(program)
} }

@ -3,9 +3,9 @@
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
use std::{ use std::{
collections::HashMap, ffi::OsStr,
io::{BufReader, Write}, io::{BufReader, Write},
path::PathBuf, path::{Path, PathBuf},
process::{Command as StdCommand, Stdio}, process::{Command as StdCommand, Stdio},
sync::{Arc, RwLock}, sync::{Arc, RwLock},
thread::spawn, thread::spawn,
@ -53,13 +53,7 @@ pub enum CommandEvent {
/// The type to spawn commands. /// The type to spawn commands.
#[derive(Debug)] #[derive(Debug)]
pub struct Command { pub struct Command(StdCommand);
program: String,
args: Vec<String>,
env_clear: bool,
env: HashMap<String, String>,
current_dir: Option<PathBuf>,
}
/// Spawned child process. /// Spawned child process.
#[derive(Debug)] #[derive(Debug)]
@ -116,49 +110,44 @@ pub struct Output {
pub stderr: Vec<u8>, pub stderr: Vec<u8>,
} }
fn relative_command_path(command: String) -> crate::Result<String> { fn relative_command_path(command: &Path) -> crate::Result<PathBuf> {
match platform::current_exe()?.parent() { match platform::current_exe()?.parent() {
#[cfg(windows)] #[cfg(windows)]
Some(exe_dir) => Ok(format!("{}\\{command}.exe", exe_dir.display())), Some(exe_dir) => Ok(exe_dir.join(command).with_extension("exe")),
#[cfg(not(windows))] #[cfg(not(windows))]
Some(exe_dir) => Ok(format!("{}/{command}", exe_dir.display())), Some(exe_dir) => Ok(exe_dir.join(command)),
None => Err(crate::Error::CurrentExeHasNoParent), None => Err(crate::Error::CurrentExeHasNoParent),
} }
} }
impl From<Command> for StdCommand { impl From<Command> for StdCommand {
fn from(cmd: Command) -> StdCommand { fn from(cmd: Command) -> StdCommand {
let mut command = StdCommand::new(cmd.program); cmd.0
command.args(cmd.args); }
}
impl Command {
pub(crate) fn new<S: AsRef<OsStr>>(program: S) -> Self {
let mut command = StdCommand::new(program);
command.stdout(Stdio::piped()); command.stdout(Stdio::piped());
command.stdin(Stdio::piped()); command.stdin(Stdio::piped());
command.stderr(Stdio::piped()); command.stderr(Stdio::piped());
if cmd.env_clear {
command.env_clear();
}
command.envs(cmd.env);
if let Some(current_dir) = cmd.current_dir {
command.current_dir(current_dir);
}
#[cfg(windows)] #[cfg(windows)]
command.creation_flags(CREATE_NO_WINDOW); command.creation_flags(CREATE_NO_WINDOW);
command
Self(command)
} }
}
impl Command { pub(crate) fn new_sidecar<S: AsRef<Path>>(program: S) -> crate::Result<Self> {
pub(crate) fn new<S: Into<String>>(program: S) -> Self { Ok(Self::new(relative_command_path(program.as_ref())?))
Self {
program: program.into(),
args: Default::default(),
env_clear: false,
env: Default::default(),
current_dir: None,
}
} }
pub(crate) fn new_sidecar<S: Into<String>>(program: S) -> crate::Result<Self> { /// Appends an argument to the command.
Ok(Self::new(relative_command_path(program.into())?)) #[must_use]
pub fn arg<S: AsRef<OsStr>>(mut self, arg: S) -> Self {
self.0.arg(arg);
self
} }
/// Appends arguments to the command. /// Appends arguments to the command.
@ -166,32 +155,46 @@ impl Command {
pub fn args<I, S>(mut self, args: I) -> Self pub fn args<I, S>(mut self, args: I) -> Self
where where
I: IntoIterator<Item = S>, I: IntoIterator<Item = S>,
S: AsRef<str>, S: AsRef<OsStr>,
{ {
for arg in args { self.0.args(args);
self.args.push(arg.as_ref().to_string());
}
self self
} }
/// Clears the entire environment map for the child process. /// Clears the entire environment map for the child process.
#[must_use] #[must_use]
pub fn env_clear(mut self) -> Self { pub fn env_clear(mut self) -> Self {
self.env_clear = true; self.0.env_clear();
self
}
/// Inserts or updates an explicit environment variable mapping.
#[must_use]
pub fn env<K, V>(mut self, key: K, value: V) -> Self
where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.0.env(key, value);
self self
} }
/// Adds or updates multiple environment variable mappings. /// Adds or updates multiple environment variable mappings.
#[must_use] #[must_use]
pub fn envs(mut self, env: HashMap<String, String>) -> Self { pub fn envs<I, K, V>(mut self, envs: I) -> Self
self.env = env; where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.0.envs(envs);
self self
} }
/// Sets the working directory for the child process. /// Sets the working directory for the child process.
#[must_use] #[must_use]
pub fn current_dir(mut self, current_dir: PathBuf) -> Self { pub fn current_dir<P: AsRef<Path>>(mut self, current_dir: P) -> Self {
self.current_dir.replace(current_dir); self.0.current_dir(current_dir);
self self
} }

Loading…
Cancel
Save