From 254ac2018627accc1e85a82552bc1a10b364b231 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juhani=20Krekel=C3=A4?= Date: Thu, 1 Jun 2023 19:39:12 +0300 Subject: [PATCH] Run a REPL if no arguments are given --- README.md | 2 +- src/main.rs | 52 ++++++++++++++++++++++++++++++++-------------------- 2 files changed, 33 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 97adf63..6f1759a 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ together if the units are compatible: metrify 1 acre 15 square feet You can also invoke metrify without arguments, in which case it will give you a -prompt to type the expression into. +prompt to type the expression into. Press ^D to exit. Result display -------------- diff --git a/src/main.rs b/src/main.rs index c13518f..8130ef7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,31 +9,43 @@ fn main() { let name = args[0].clone(); let args = args[1..].join(" "); - let mut input = args; - if input.len() == 0 { - print!("> "); - match io::stdout().flush() { - Ok(_) => {} + if args.len() == 0 { + loop { + print!("> "); + match io::stdout().flush() { + Ok(_) => {} + Err(err) => { + eprintln!("{name}: Error: {err}"); + process::exit(1); + } + } + let mut input = String::new(); + match io::stdin().read_line(&mut input) { + Ok(_) => {} + Err(err) => { + eprintln!("{name}: Error: {err}"); + process::exit(1); + } + } + if input.len() == 0 { + println!(); // Add a newline if user pressed ^D + break; + } + match run(&input) { + Ok(str) => println!("{str}"), + Err(err) => { + eprintln!("Error: {err}"); + } + } + } + } else { + match run(&args) { + Ok(str) => println!("{str}"), Err(err) => { eprintln!("{name}: Error: {err}"); process::exit(1); } } - match io::stdin().read_line(&mut input) { - Ok(_) => {} - Err(err) => { - eprintln!("{name}: Error: {err}"); - process::exit(1); - } - } - } - - match run(&input) { - Ok(str) => println!("{str}"), - Err(err) => { - eprintln!("{name}: Error: {err}"); - process::exit(1); - } } }