1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
#[macro_use]
extern crate lazy_static;
use tracing::debug;
lazy_static! {
static ref GLOBAL_CONFIG: Config = Config::default();
}
/// Configuration for shell execution and error logging.
///
/// # Examples
///
/// initialize with default values:
/// ```
/// use sheller::Config;
/// let config = Config::default();
/// ```
///
/// initialize with custom values:
/// ```
/// use sheller::Config;
/// let config = Config {
/// prefix: "π¦ $ ".to_string(),
/// ..Default::default()
/// };
///
///
pub struct Config {
pub prefix: String,
pub writer: std::sync::Mutex<Box<dyn std::io::Write + Sync + Send>>,
}
impl Default for Config {
fn default() -> Self {
Config {
prefix: "π $ ".to_string(),
writer: std::sync::Mutex::new(Box::new(std::io::stdout())),
}
}
}
impl Config {
fn try_println(&self, message: &str) -> std::io::Result<()> {
let mut writer = self.writer.lock().map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::Other,
format!("Failed to lock writer: {e:?}"),
)
})?;
writeln!(writer, "{}{}", self.prefix, message)?;
writer.flush()?;
Ok(())
}
}
#[derive(Debug)]
struct Metadata<'a> {
env_key: &'a str,
program: &'a str,
args: &'a [&'a str],
}
#[cfg(windows)]
static DEFAULT_METADATA: Metadata = Metadata {
env_key: "COMSPEC",
program: "cmd.exe",
args: &["/D", "/S", "/C"],
};
#[cfg(unix)]
static DEFAULT_METADATA: Metadata = Metadata {
env_key: "SHELL",
program: "/bin/sh",
args: &["-c"],
};
fn parse_program() -> String {
std::env::var(DEFAULT_METADATA.env_key).unwrap_or_else(|e| {
debug!(
default_program = DEFAULT_METADATA.program,
env_key = DEFAULT_METADATA.env_key,
error = ?e,
"Failed to get shell environment variable, falling back to default program."
);
DEFAULT_METADATA.program.to_string()
})
}
/// Sheller is a builder for `std::process::Command` that sets the shell program and arguments.
///
/// Please see the `Sheller::new` method for more information.
#[derive(Debug)]
pub struct Sheller<'a> {
program: String,
args: Vec<&'a str>,
script: &'a str,
}
impl Default for Sheller<'_> {
fn default() -> Self {
Self {
program: parse_program(),
args: DEFAULT_METADATA.args.to_vec(),
script: "",
}
}
}
impl<'a> Sheller<'a> {
/// Create a new `Sheller` with the given `script` and platform-specific defaults.
///
/// # Platform-specific defaults
///
/// ## Windows
///
/// When `target_family` is `windows`.
///
/// Set the `COMSPEC` environment variable to `program`, and if the environment variable is not set, use `cmd.exe` as the fallback program.
///
/// Also set the `args` to `["/D", "/S", "/C"]`.
///
/// ## Unix
///
/// When `target_family` is `unix`.
///
/// Set the `SHELL` environment variable to `program`, and if the environment variable is not set, use `/bin/sh` as the fallback program.
///
/// Also set the `args` to `["-c"]`.
///
/// # Arguments
///
/// * `script` - The shell script to run. This is dependent on the shell program.
///
/// # Examples
///
/// ```
/// use sheller::Sheller;
///
/// let mut command = Sheller::new("echo hello").build();
/// assert!(command.status().unwrap().success());
/// ```
#[must_use]
pub fn new(script: &'a str) -> Self {
Self {
script,
..Default::default()
}
}
/// Returns `std::process::Command` with the shell program and arguments set.
///
/// # Examples
///
/// ```
/// use sheller::Sheller;
///
/// let mut command = Sheller::new("echo hello").build();
/// assert!(command.status().unwrap().success());
/// ```
#[must_use]
pub fn build(self) -> std::process::Command {
let mut command = std::process::Command::new(&self.program);
command.args(&self.args);
command.arg(self.script);
command
}
/// Run the shell command and panic if the command failed to run.
///
/// # Examples
/// ```
/// use sheller::{Sheller, CommandExt};
///
/// Sheller::new("echo hello").run();
/// ```
///
/// # Panics
/// Panics if the command failed to run.
pub fn run(self) {
self.build().run();
}
/// Run the shell command with the given `config` and panic if the command failed to run.
///
/// # Examples
/// ```
/// use sheller::{Sheller, Config, CommandExt};
///
/// let config = Config {
/// prefix: "π¦ $ ".to_string(),
/// ..Default::default()
/// };
/// Sheller::new("echo hello").run_with_config(&config);
/// ```
///
/// # Panics
/// Panics if the command failed to run.
///
pub fn run_with_config(self, config: &Config) {
self.build().run_with_config(config);
}
/// Run the shell command and return a `Result` with `Ok` if the command was successful, and `Err` if the command failed.
///
/// # Examples
/// ```
/// use sheller::{Sheller, CommandExt};
///
/// Sheller::new("echo hello").try_run().unwrap();
/// ```
///
/// # Errors
/// Returns an `Err` if the command failed to run.
///
pub fn try_run(self) -> Result<(), std::io::Error> {
self.build().try_run()
}
/// Run the shell command with the given `config` and return a `Result` with `Ok` if the command was successful, and `Err` if the command failed.
///
/// # Examples
/// ```
/// use sheller::{Sheller, Config, CommandExt};
///
/// let config = Config {
/// prefix: "π¦ $ ".to_string(),
/// ..Default::default()
/// };
/// Sheller::new("echo hello").try_run_with_config(&config).unwrap();
/// ```
///
/// # Errors
/// Returns an `Err` if the command failed to run.
///
pub fn try_run_with_config(self, config: &Config) -> Result<(), std::io::Error> {
self.build().try_run_with_config(config)
}
}
pub trait CommandExt {
/// Run the command and panic if the command failed to run.
///
/// # Examples
/// ```
/// use sheller::CommandExt;
/// use std::process::Command;
///
/// #[cfg(windows)]
/// fn example() {
/// let mut command = Command::new("cmd.exe");
/// command.args(["/D", "/S", "/C", "echo hello"]).run();
/// }
///
/// #[cfg(unix)]
/// fn example() {
/// let mut command = Command::new("echo");
/// command.arg("hello").run();
/// }
///
/// example();
/// ```
///
/// # Panics
/// Panics if the command failed to run.
///
fn run(&mut self);
/// Run the command with the given `config` and panic if the command failed to run.
///
/// # Examples
/// ```
/// use sheller::{CommandExt, Config};
/// use std::process::Command;
///
/// #[cfg(windows)]
/// fn example() {
/// let mut command = Command::new("cmd.exe");
/// let config = Config {
/// prefix: "π¦ $ ".to_string(),
/// ..Default::default()
/// };
/// command
/// .args(["/D", "/S", "/C", "echo hello"])
/// .run_with_config(&config);
/// }
///
/// #[cfg(unix)]
/// fn example() {
/// let mut command = Command::new("echo");
/// let config = Config {
/// prefix: "π¦ $ ".to_string(),
/// ..Default::default()
/// };
/// command.arg("hello").run_with_config(&config);
/// }
/// example();
/// ```
///
/// # Panics
/// Panics if the command failed to run.
///
fn run_with_config(&mut self, config: &Config);
/// Run the command and return a `Result` with `Ok` if the command was successful, and `Err` if the command failed.
///
/// # Examples
/// ```
/// use sheller::CommandExt;
/// use std::process::Command;
///
/// #[cfg(windows)]
/// fn example() {
/// let mut command = Command::new("cmd.exe");
/// command
/// .args(["/D", "/S", "/C", "echo hello"])
/// .try_run()
/// .unwrap();
/// }
///
/// #[cfg(unix)]
/// fn example() {
/// let mut command = Command::new("echo");
/// command.arg("hello").try_run().unwrap();
/// }
///
/// example();
/// ```
///
/// # Errors
/// Returns an `Err` if the command failed to run.
///
fn try_run(&mut self) -> Result<(), std::io::Error>;
/// Run the command with the given `config` and return a `Result` with `Ok` if the command was successful, and `Err` if the command failed.
///
/// # Examples
/// ```
/// use sheller::{CommandExt, Config};
/// use std::process::Command;
/// #[cfg(windows)]
/// fn example() {
/// let mut command = Command::new("cmd.exe");
/// let config = Config {
/// prefix: "π¦ $ ".to_string(),
/// ..Default::default()
/// };
/// command
/// .args(["/D", "/S", "/C", "echo hello"])
/// .try_run_with_config(&config)
/// .unwrap();
/// }
///
/// #[cfg(unix)]
/// fn example() {
/// let mut command = Command::new("echo");
/// let config = Config {
/// prefix: "π¦ $ ".to_string(),
/// ..Default::default()
/// };
/// command.arg("hello").try_run_with_config(&config).unwrap();
/// }
///
/// example();
/// ```
///
/// # Errors
/// Returns an `Err` if the command failed to run.
///
fn try_run_with_config(&mut self, config: &Config) -> Result<(), std::io::Error>;
}
impl CommandExt for std::process::Command {
/// Run the command and panic if the command failed to run.
///
/// # Examples
/// ```
/// use sheller::CommandExt;
/// use std::process::Command;
///
/// #[cfg(windows)]
/// fn example() {
/// let mut command = Command::new("cmd.exe");
/// command.args(["/D", "/S", "/C", "echo hello"]).run();
/// }
///
/// #[cfg(unix)]
/// fn example() {
/// let mut command = Command::new("echo");
/// command.arg("hello").run();
/// }
///
/// example();
/// ```
///
/// # Panics
/// Panics if the command failed to run.
///
fn run(&mut self) {
self.try_run().unwrap();
}
/// Run the command and panic if the command failed to run.
///
/// # Examples
/// ```
/// use sheller::{CommandExt, Config};
/// use std::process::Command;
///
/// #[cfg(windows)]
/// fn example() {
/// let mut command = Command::new("cmd.exe");
/// let config = Config {
/// prefix: "π¦ $ ".to_string(),
/// ..Default::default()
/// };
/// command
/// .args(["/D", "/S", "/C", "echo hello"])
/// .run_with_config(&config);
/// }
///
/// #[cfg(unix)]
/// fn example() {
/// let mut command = Command::new("echo");
/// let config = Config {
/// prefix: "π¦ $ ".to_string(),
/// ..Default::default()
/// };
/// command.arg("hello").run_with_config(&config);
/// }
/// example();
/// ```
///
/// # Panics
/// Panics if the command failed to run.
///
fn run_with_config(&mut self, config: &Config) {
self.try_run_with_config(config).unwrap();
}
/// Run the command and return a `Result` with `Ok` if the command was successful, and `Err` if the command failed.
///
/// # Examples
/// ```
/// use sheller::CommandExt;
/// use std::process::Command;
///
/// #[cfg(windows)]
/// fn example() {
/// let mut command = Command::new("cmd.exe");
/// command
/// .args(["/D", "/S", "/C", "echo hello"])
/// .try_run()
/// .unwrap();
/// }
///
/// #[cfg(unix)]
/// fn example() {
/// let mut command = Command::new("echo");
/// command.arg("hello").try_run().unwrap();
/// }
///
/// example();
/// ```
///
/// # Errors
/// Returns an `Err` if the command failed to run.
///
fn try_run(&mut self) -> Result<(), std::io::Error> {
self.try_run_with_config(&GLOBAL_CONFIG)
}
/// Run the command with the given `config` and return a `Result` with `Ok` if the command was successful, and `Err` if the command failed.
///
/// # Examples
/// ```
/// use sheller::{CommandExt, Config};
/// use std::process::Command;
///
/// #[cfg(windows)]
/// fn example() {
/// let mut command = Command::new("cmd.exe");
/// let config = Config {
/// prefix: "π¦ $ ".to_string(),
/// ..Default::default()
/// };
/// command
/// .args(["/D", "/S", "/C", "echo hello"])
/// .try_run_with_config(&config)
/// .unwrap();
/// }
///
/// #[cfg(unix)]
/// fn example() {
/// let mut command = Command::new("echo");
/// let config = Config {
/// prefix: "π¦ $ ".to_string(),
/// ..Default::default()
/// };
/// command.arg("hello").try_run_with_config(&config).unwrap();
/// }
///
/// example();
/// ```
///
/// # Errors
/// Returns an `Err` if the command failed to run.
///
fn try_run_with_config(&mut self, config: &Config) -> Result<(), std::io::Error> {
config.try_println(&format!("Running command: {self:?}"))?;
let mut command = self.spawn().or_else(|e| {
config.try_println(&format!("Failed to spawn command: {e:?}"))?;
Err(e)
})?;
let status = command.wait().or_else(|e| {
config.try_println(&format!("Failed to wait for command: {e:?}"))?;
Err(e)
})?;
if !status.success() {
let message = format!("Failed to run command: {self:?} with status: {status:?}");
config.try_println(&message)?;
return Err(std::io::Error::new(std::io::ErrorKind::Other, message));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_global() {
assert_eq!(GLOBAL_CONFIG.prefix, "π $ ");
}
}