Skip to content

Commit

Permalink
Implement pipe mode for when there are no arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
lpenz committed Jun 25, 2023
1 parent d5f9f05 commit a1fb6f8
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
9 changes: 7 additions & 2 deletions src/bin/stdecor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ async fn main() -> Result<(), Box<dyn Error>> {
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
let args = stdecor::cli::Cli::parse();
let exitstatus = stdecor::runner::run(&args).await?;
process::exit(exitstatus.code().unwrap_or(0));
if args.command.is_empty() {
stdecor::runner::pipe(&args).await?;
Ok(())
} else {
let exitstatus = stdecor::runner::run(&args).await?;
process::exit(exitstatus.code().unwrap_or(0));
}
}
3 changes: 1 addition & 2 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ pub struct Cli {
#[arg(short, long, default_value_t = false)]
pub date: bool,

/// The command to run
#[clap(required = true)]
/// The command to run; use stdin if empty (pipe mode)
pub command: Vec<String>,
}
18 changes: 17 additions & 1 deletion src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ use color_eyre::{eyre::eyre, Result};
use std::convert::TryFrom;
use std::process::ExitStatus;
use std::process::Stdio;
use tokio::io::{self, AsyncWriteExt};
use tokio::io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::Command;
use tokio_process_stream as tps;
use tokio_stream::wrappers::LinesStream;
use tokio_stream::StreamExt;

use crate::cli::Cli;
Expand Down Expand Up @@ -65,3 +66,18 @@ pub async fn run(cli: &Cli) -> Result<ExitStatus> {
}
Err(eyre!("stream exhausted without a \"done\" element"))
}

#[tracing::instrument]
pub async fn pipe(cli: &Cli) -> Result<()> {
let prefix_static = if let Some(prefix) = &cli.prefix {
format!("{} ", prefix)
} else {
"".to_string()
};
let mut stdin_lines = LinesStream::new(BufReader::new(io::stdin()).lines());
let mut stdout = io::stdout();
while let Some(line) = stdin_lines.next().await {
do_write(&mut stdout, &prefix_static, cli.date, &line?).await?;
}
Ok(())
}

0 comments on commit a1fb6f8

Please sign in to comment.