Run a REPL if no arguments are given

This commit is contained in:
Juhani Krekelä 2023-06-01 19:39:12 +03:00
parent e8e81b4564
commit 254ac20186
2 changed files with 33 additions and 21 deletions

View File

@ -16,7 +16,7 @@ together if the units are compatible:
metrify 1 acre 15 square feet metrify 1 acre 15 square feet
You can also invoke metrify without arguments, in which case it will give you a 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 Result display
-------------- --------------

View File

@ -9,9 +9,9 @@ fn main() {
let name = args[0].clone(); let name = args[0].clone();
let args = args[1..].join(" "); let args = args[1..].join(" ");
let mut input = args;
if input.len() == 0 { if args.len() == 0 {
loop {
print!("> "); print!("> ");
match io::stdout().flush() { match io::stdout().flush() {
Ok(_) => {} Ok(_) => {}
@ -20,6 +20,7 @@ fn main() {
process::exit(1); process::exit(1);
} }
} }
let mut input = String::new();
match io::stdin().read_line(&mut input) { match io::stdin().read_line(&mut input) {
Ok(_) => {} Ok(_) => {}
Err(err) => { Err(err) => {
@ -27,9 +28,19 @@ fn main() {
process::exit(1); process::exit(1);
} }
} }
if input.len() == 0 {
println!(); // Add a newline if user pressed ^D
break;
} }
match run(&input) { match run(&input) {
Ok(str) => println!("{str}"),
Err(err) => {
eprintln!("Error: {err}");
}
}
}
} else {
match run(&args) {
Ok(str) => println!("{str}"), Ok(str) => println!("{str}"),
Err(err) => { Err(err) => {
eprintln!("{name}: Error: {err}"); eprintln!("{name}: Error: {err}");
@ -37,3 +48,4 @@ fn main() {
} }
} }
} }
}