Skip to content

Commit 3c42183

Browse files
committed
Add OverSsh trait to allow conversion of std::process::Command into a openssh::Session.
Signed-off-by: Aalekh Patel <[email protected]>
1 parent 99b11c2 commit 3c42183

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

src/command.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,41 @@ macro_rules! delegate {
4949
}};
5050
}
5151

52+
/// If a command is `OverSsh` then it can be executed over an SSH session.
53+
/// Primarily a way to allow `std::process::Command` to be turned directly into an `openssh::Command`.
54+
pub trait OverSsh {
55+
/// Given a session, return a command that can be executed over that session.
56+
fn with_session<'session>(&self, session: &'session Session) -> Result<crate::Command<'session>, Error>;
57+
}
58+
59+
impl OverSsh for std::process::Command {
60+
/// Given a session, convert a std::process::Command into an `openssh::Command`
61+
/// that can be executed over that session.
62+
fn with_session<'session>(&self, session: &'session Session) -> Result<Command<'session>, Error> {
63+
let program =
64+
self
65+
.get_program()
66+
.to_str()
67+
.ok_or_else(|| Error::InvalidUtf8String(self.get_program().to_os_string()))?;
68+
69+
let args =
70+
self.
71+
get_args()
72+
.into_iter()
73+
.map(
74+
|s|
75+
s
76+
.to_str()
77+
.ok_or_else(|| Error::InvalidUtf8String(s.to_os_string()))
78+
)
79+
.collect::<Result<Vec<_>, Error>>()?;
80+
81+
let mut command = session.command(program);
82+
command.args(args);
83+
Ok(command)
84+
}
85+
}
86+
5287
/// A remote process builder, providing fine-grained control over how a new remote process should
5388
/// be spawned.
5489
///

src/error.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ pub enum Error {
3434
#[error("the remote command could not be executed")]
3535
Remote(#[source] io::Error),
3636

37+
/// Invalid UTF-8 string when trying to
38+
/// convert a `std::ffi::OsString` to a `String`.
39+
#[error("invalid string")]
40+
InvalidUtf8String(std::ffi::OsString),
41+
3742
/// The connection to the remote host was severed.
3843
///
3944
/// Note that for the process impl, this is a best-effort error, and it _may_ instead

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ pub use builder::{KnownHosts, SessionBuilder};
168168

169169
mod command;
170170
pub use command::Command;
171+
pub use command::OverSsh;
171172

172173
mod child;
173174
pub use child::RemoteChild;

0 commit comments

Comments
 (0)