better argument parsing

This commit is contained in:
Emma Tebibyte 2023-04-11 18:26:02 -04:00
parent 71490f7421
commit 1e69ae5e98
1 changed files with 27 additions and 16 deletions

View File

@ -19,13 +19,14 @@
use std::{
env::args,
fs::File,
io::{
Read,
stdin,
stdout,
Stdout,
Write,
},
os::fd::FromRawFd,
};
use crossterm::{
@ -353,24 +354,34 @@ fn screen_main(stdout: &mut Stdout, mut state: State) -> Result<()> {
fn main() -> Result<()> {
let argv = args().collect::<Vec<String>>();
let mut buf = Vec::new();
let text: String;
if !argv.get(1).is_some() {
text = "".to_string();
} else {
let mut buf = Vec::new();
std::fs::File::open(argv[1].clone()).unwrap_or_else(|_| {
eprintln!("{}: {}: No such file.", argv[0], argv[1]);
exit(EX_UNAVAILABLE);
}).read_to_end(&mut buf).unwrap();
text = match argv.get(1) {
Some(path) => {
match path.as_str() {
"-" => unsafe { File::from_raw_fd(0) },
_ => {
std::fs::File::open(path).unwrap_or_else(|_| {
eprintln!(
"{}: {}: No such file or directory.",
argv[0],
argv[1]
);
exit(EX_UNAVAILABLE);
})
},
}.read_to_end(&mut buf).unwrap();
text = String::from_utf8(buf).unwrap_or_else(|_| {
eprintln!(
"{}: {}: File contents are invalid UTF-8.", argv[0], argv[1]
);
exit(EX_DATAERR);
});
}
String::from_utf8(buf).unwrap_or_else(|_| {
eprintln!(
"{}: {}: File contents are invalid UTF-8.", argv[0], argv[1]
);
exit(EX_DATAERR);
})
},
None => "".to_string(),
};
let state = State::from_str(&text)?;
let mut stdout = stdout();