Wrap with sudo if not running as root
(mut cmd_builder: CommandBuilder)
| 100 | |
| 101 | /// Wrap with sudo if not running as root |
| 102 | pub fn wrap_with_sudo(mut cmd_builder: CommandBuilder) -> Result<CommandBuilder> { |
| 103 | if is_root_user() { |
| 104 | Ok(cmd_builder) |
| 105 | } else if is_sudo_available() { |
| 106 | debug!("Wrapping with sudo: {}", cmd_builder.as_command_line()); |
| 107 | validate_sudo_access()?; |
| 108 | |
| 109 | cmd_builder.wrap( |
| 110 | "sudo", |
| 111 | [ |
| 112 | // Password prompt should not appear here since it has already been validated |
| 113 | OsStr::new("--non-interactive"), |
| 114 | // Both forms are needed: sudo-rs ignores the bare flag, and with only the |
| 115 | // list classic sudo keeps `env_reset`, which lets variables exported by PAM |
| 116 | // session modules (e.g. HOME from pam_systemd) override the preserved ones. |
| 117 | OsStr::new("--preserve-env"), |
| 118 | &preserve_env_arg(&cmd_builder), |
| 119 | ], |
| 120 | ); |
| 121 | Ok(cmd_builder) |
| 122 | } else { |
| 123 | bail!( |
| 124 | "Sudo is not available to run the command: {}", |
| 125 | cmd_builder.as_command_line() |
| 126 | ); |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | /// Run a command with sudo after validating sudo access |
| 131 | pub fn run_with_sudo<S, I, T>(program: S, argv: I) -> Result<()> |
no test coverage detected