Skip to content

Commit

Permalink
feat(cli): return immediately when stdin is empty
Browse files Browse the repository at this point in the history
With this change, calling `bitcli` (or `bitcli shorten`) without any
arguments will no longer wait for the standard input indefinitely if
it's empty and its handle does not refer to a terminal/tty.
  • Loading branch information
matyama committed Jul 24, 2024
1 parent c268230 commit ba6e0ad
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
19 changes: 15 additions & 4 deletions src/io.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use std::error::Error;
use std::io::IsTerminal as _;
use std::os::fd::AsFd as _;
use std::str::FromStr;

use async_stream::try_stream;
Expand All @@ -7,13 +9,22 @@ use tokio::io::{self, AsyncBufReadExt as _, BufReader};

use crate::error::Result;

pub fn read_input<T>() -> impl TryStream<Item = Result<T>>
/// Read standard input as a [`TryStream`] of parsed lines of type `T`.
///
/// Returns `None` if the stdin handle does not refer to a terminal/tty.
pub fn read_input<T>() -> Option<impl TryStream<Item = Result<T>>>
where
T: FromStr + 'static,
<T as FromStr>::Err: Error + Send + Sync,
{
try_stream! {
let mut stdin = BufReader::new(io::stdin());
let stdin = io::stdin();

if stdin.as_fd().is_terminal() {
return None;
}

Some(try_stream! {
let mut stdin = BufReader::new(stdin);
let mut buf = String::new();

loop {
Expand All @@ -27,7 +38,7 @@ where

buf.clear();
}
}
})
}

#[inline]
Expand Down
7 changes: 4 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,10 @@ async fn main() {
match cmd {
Command::Shorten(args) => {
let urls = if args.urls.is_empty() {
io::read_input::<url::Url>()
.map(|url| crash_if_err!(url))
.boxed()
let Some(urls) = io::read_input::<url::Url>() else {
return;
};
urls.map(|url| crash_if_err!(url)).boxed()
} else {
stream::iter(args.urls).boxed()
};
Expand Down

0 comments on commit ba6e0ad

Please sign in to comment.