fixed array matching and printing

This commit is contained in:
Emma Tebibyte 2023-03-25 02:36:38 -04:00
parent de4b897aa8
commit e3e1807656
Signed by: emma
GPG Key ID: 6D661C738815E7DD

View File

@ -39,7 +39,7 @@ fn parse_toml(
let mut out = String::new();
while let Some(item) = tabkey.next() {
let value = match root.get(item) {
let mut value = match root.get(item) {
Some(val) => val,
None => {
return Err((format!("{}: No such table or key.", item), EX_DATAERR));
@ -47,6 +47,24 @@ fn parse_toml(
};
match value {
Value::Array(array) => {
let i = match index {
Some(i) => i,
None => {
for v in array.iter() {
out.push_str(&format!("{}\n", v.to_string()));
}
continue;
},
};
match array.get(i) {
Some(val) => value = val,
None => {
return Err((format!("No value at index {}.", i), EX_DATAERR));
},
};
},
Value::Table(table) => {
if tabkey.peek().is_some() {
root = toml::Value::Table(table.to_owned());
@ -61,38 +79,20 @@ fn parse_toml(
};
match value {
Value::Array(array) => { // TODO: Split Array logic into separate function
let element: String;
match index {
Some(i) => {
element = match array.get(i) {
Some(element) => {
match element.as_str() {
Some(val) => val.to_owned(),
None => {
return Err((
format!("{:?}: No value at given key.", i),
EX_DATAERR
));
},
}
},
None => {
return Err(
(format!("{:?}: No value at given index.", i), EX_DATAERR)
);
},
};
},
None => element = format!("{:?}", array),
};
out.push_str(&element);
},
Value::Boolean(boolean) => out.push_str(&format!("{:?}", boolean)),
Value::Datetime(datetime) => out.push_str(&format!("{:?}", datetime)),
Value::Float(float) => out.push_str(&format!("{:?}", float)),
Value::Integer(int) => out.push_str(&format!("{:?}", int)),
Value::String(string) => out.push_str(string.as_str()),
Value::Array(array) => {
for v in array.iter() { out.push_str(&format!("{}\n", v.to_string())); }
},
Value::Boolean(boolean) => out.push_str(&format!("{:?}\n", boolean)),
Value::Datetime(datetime) => out.push_str(&format!("{:?}\n", datetime)),
Value::Float(float) => out.push_str(&format!("{:?}\n", float)),
Value::Integer(int) => out.push_str(&format!("{:?}\n", int)),
Value::String(string) => {
let contents = string.to_owned();
let mut lines: Vec<&str> = contents.lines().collect();
if lines.last().unwrap().is_empty() { _ = lines.pop(); }
for line in lines.iter() { out.push_str(&format!("{}\n", line)); }
},
_ => return Err((format!("{:?}: No such key.", item), EX_DATAERR)),
};
}
@ -125,11 +125,10 @@ fn rust_main(args: Args) {
exit(EX_UNAVAILABLE);
})
},
}.read_to_end(&mut content)
.unwrap_or_else(|_| {
}.read_to_end(&mut content).unwrap_or_else(|_| {
eprintln!("{}: Could not read input.", argv[0]);
exit(EX_OSERR);
});
});
let mut tabkey: Vec<&str> = argv[1].split(".").collect();
@ -164,7 +163,7 @@ fn rust_main(args: Args) {
});
let valiter = tabkey.iter().peekable();
println!(
print!(
"{}",
match parse_toml(root, valiter, index) {
Ok(val) => val,