Skip to content

Commit b84df42

Browse files
committed
Take input either from stdin or the first argument
1 parent 2274139 commit b84df42

File tree

2 files changed

+35
-12
lines changed

2 files changed

+35
-12
lines changed

src/main.rs

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
11
use anyhow::Context;
22
use minijinja::Environment;
3-
use std::{collections::HashMap, env, fs, process};
3+
use std::{
4+
collections::HashMap,
5+
env, fs,
6+
io::{self, Read},
7+
};
48

59
fn main() -> anyhow::Result<()> {
6-
let mut args = env::args();
7-
if args.len() != 2 {
8-
let name = args.next().unwrap();
9-
eprintln!("Usage: {} <template_file>", name);
10-
process::exit(1);
11-
}
12-
13-
let path = args.nth(1).unwrap();
14-
let template = fs::read_to_string(&path)
15-
.with_context(|| format!("Failed to read template file: {}", path))?;
10+
let template = if let Some(path) = env::args().nth(1) {
11+
fs::read_to_string(&path)
12+
.with_context(|| format!("Failed to read template file: {}", path))?
13+
} else {
14+
let mut input = String::new();
15+
io::stdin().read_to_string(&mut input)?;
16+
input
17+
};
1618

1719
let mut env = Environment::new();
1820
env.add_template("template", &template)?;

tests/integration_test.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use std::fs;
2-
use std::process::Command;
2+
use std::io::Write;
3+
use std::process::{Command, Stdio};
34
use tempfile::tempdir;
45

56
#[test]
@@ -46,3 +47,23 @@ fn test_filters() -> anyhow::Result<()> {
4647

4748
Ok(())
4849
}
50+
51+
#[test]
52+
fn test_stdin_input() -> anyhow::Result<()> {
53+
let mut child = Command::new("cargo")
54+
.arg("run")
55+
.arg("--")
56+
.env("NAME", "World")
57+
.stdin(Stdio::piped())
58+
.stdout(Stdio::piped())
59+
.spawn()?;
60+
61+
let stdin = child.stdin.as_mut().unwrap();
62+
stdin.write_all(b"Hello {{NAME}}!")?;
63+
64+
let output = child.wait_with_output()?;
65+
assert!(output.status.success());
66+
assert_eq!(String::from_utf8(output.stdout)?, "Hello World!\n");
67+
68+
Ok(())
69+
}

0 commit comments

Comments
 (0)