summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorqkzk <qu3nt1n@gmail.com>2023-10-08 21:57:39 +0200
committerqkzk <qu3nt1n@gmail.com>2023-10-08 21:57:39 +0200
commit1b353b1a3a6d8b56a1591b3bf574de6b5151b46d (patch)
tree4075736dbfb32555a10735a50cf277cb8e77589c
parent552f7ca40b65395f126132deb13ceaf398c4a274 (diff)
refactor sudo commands creation and execution
-rw-r--r--src/password.rs28
1 files changed, 20 insertions, 8 deletions
diff --git a/src/password.rs b/src/password.rs
index 2638eb1..1cd0158 100644
--- a/src/password.rs
+++ b/src/password.rs
@@ -86,9 +86,12 @@ impl PasswordHolder {
}
/// Spawn a sudo command with stdin, stdout and stderr piped.
+/// sudo is run with -S argument to read the passworo from stdin
/// Args are sent.
/// CWD is set to `path`.
-fn new_sudo_command<S, P>(args: &[S], path: P) -> Result<std::process::Child>
+/// No password is set yet.
+/// A password should be sent with `inject_password`.
+fn new_sudo_command_awaiting_password<S, P>(args: &[S], path: P) -> Result<std::process::Child>
where
S: AsRef<std::ffi::OsStr> + std::fmt::Debug,
P: AsRef<std::path::Path> + std::fmt::Debug,
@@ -128,7 +131,7 @@ where
info!("sudo_with_password {args:?} CWD {path:?}");
let log_line = format!("running sudo command with password. args: {args:?}, CWD: {path:?}");
write_log_line(log_line);
- let mut child = new_sudo_command(args, path)?;
+ let mut child = new_sudo_command_awaiting_password(args, path)?;
inject_password(password, &mut child)?;
let output = child.wait_with_output()?;
Ok((
@@ -138,6 +141,20 @@ where
))
}
+/// Spawn a sudo command which shouldn't require a password.
+/// The command is executed immediatly and we return an handle to it.
+fn new_sudo_command_passwordless<S>(args: &[S]) -> Result<std::process::Child>
+where
+ S: AsRef<std::ffi::OsStr> + std::fmt::Debug,
+{
+ Ok(Command::new("sudo")
+ .args(args)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()?)
+}
+
/// Runs a passwordless sudo command.
/// Returns stdout & stderr
pub fn execute_sudo_command<S>(args: &[S]) -> Result<(bool, String, String)>
@@ -147,12 +164,7 @@ where
info!("running sudo {:?}", args);
let log_line = format!("running sudo command. {args:?}");
write_log_line(log_line);
- let child = Command::new("sudo")
- .args(args)
- .stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()?;
+ let child = new_sudo_command_passwordless(args)?;
let output = child.wait_with_output()?;
Ok((
output.status.success(),