Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cli): return immediately when stdin is empty #15

Merged
merged 1 commit into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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