~elchenberg/not-envsubst

not-envsubst/src/stdin.rs -rw-r--r-- 1.3 KiB
f4ab9be4elchenberg Initial commit 8 months ago
                                                                                
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
use std::io::stdin;
use std::process::exit;
use std::sync::mpsc::channel;
use std::sync::mpsc::Receiver;
use std::sync::mpsc::TryRecvError;
use std::thread::sleep;
use std::thread::spawn;
use std::time::Duration;

pub fn get_lines_or_exit() -> Vec<String> {
    match get_lines() {
        Ok(lines) => lines,
        Err(TryRecvError::Empty) => {
            eprintln!("ERROR: Please provide some input via STDIN");
            exit(1)
        }
        Err(error) => {
            eprintln!("ERROR: {}", error);
            exit(1)
        }
    }
}

pub fn get_lines() -> Result<Vec<String>, TryRecvError> {
    let stdin_channel = spawn_stdin_channel();
    sleep(Duration::from_millis(10));
    stdin_channel.try_recv()
}

// Spawning a channel is a workaround that allows us to catch missing STDIN input with a TryRecvError.
fn spawn_stdin_channel() -> Receiver<Vec<String>> {
    let (sender, receiver) = channel::<Vec<String>>();
    spawn(move || {
        let mut input_lines: Vec<String> = Vec::new();
        let mut line = String::new();
        let stdin = stdin();
        while stdin.read_line(&mut line).unwrap() > 0 {
            input_lines.push(line.clone());
            line.clear();
        }
        sender.send(input_lines).unwrap();
    });
    receiver
}