Skip to content

Commit

Permalink
Add OverSsh trait to allow conversion of std::process::Command into a…
Browse files Browse the repository at this point in the history
… openssh::Session.

Signed-off-by: Aalekh Patel <aalekh.gwpeck.7998@icloud.com>
  • Loading branch information
aalekhpatel07 committed Jan 31, 2023
1 parent 99b11c2 commit 3c42183
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,41 @@ macro_rules! delegate {
}};
}

/// If a command is `OverSsh` then it can be executed over an SSH session.
/// Primarily a way to allow `std::process::Command` to be turned directly into an `openssh::Command`.
pub trait OverSsh {
/// Given a session, return a command that can be executed over that session.
fn with_session<'session>(&self, session: &'session Session) -> Result<crate::Command<'session>, Error>;
}

impl OverSsh for std::process::Command {
/// Given a session, convert a std::process::Command into an `openssh::Command`
/// that can be executed over that session.
fn with_session<'session>(&self, session: &'session Session) -> Result<Command<'session>, Error> {
let program =
self
.get_program()
.to_str()
.ok_or_else(|| Error::InvalidUtf8String(self.get_program().to_os_string()))?;

let args =
self.
get_args()
.into_iter()
.map(
|s|
s
.to_str()
.ok_or_else(|| Error::InvalidUtf8String(s.to_os_string()))
)
.collect::<Result<Vec<_>, Error>>()?;

let mut command = session.command(program);
command.args(args);
Ok(command)
}
}

/// A remote process builder, providing fine-grained control over how a new remote process should
/// be spawned.
///
Expand Down
5 changes: 5 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ pub enum Error {
#[error("the remote command could not be executed")]
Remote(#[source] io::Error),

/// Invalid UTF-8 string when trying to
/// convert a `std::ffi::OsString` to a `String`.
#[error("invalid string")]
InvalidUtf8String(std::ffi::OsString),

/// The connection to the remote host was severed.
///
/// Note that for the process impl, this is a best-effort error, and it _may_ instead
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ pub use builder::{KnownHosts, SessionBuilder};

mod command;
pub use command::Command;
pub use command::OverSsh;

mod child;
pub use child::RemoteChild;
Expand Down

0 comments on commit 3c42183

Please sign in to comment.