add usage

This commit is contained in:
caleb 2023-04-29 15:14:11 -04:00
parent b7454d7e25
commit 1b04ea3c14

View file

@ -1,10 +1,9 @@
use std::env;
use std::fs::File;
use std::path::Path;
use nbt::{Blob, Value::{self, Compound}, Map};
use nbt::{Blob, Value, Map};
fn read_nbt(path_str: String) -> Option<Blob> {
fn read_nbt(path_str: &String) -> Option<Blob> {
let path_to_dat = Path::new(&path_str);
if let Ok(mut file) = File::open(path_to_dat) {
@ -14,11 +13,24 @@ fn read_nbt(path_str: String) -> Option<Blob> {
}
}
fn main() {
let nbt_blob = read_nbt(env::args().take(2).nth(1).expect("pls call with .dat")).expect("unable to read nbt");
print_value_map(&nbt_blob.content, &0);
fn read_key(map: &Map<String,Value>, key: &str) -> Option<Value> {
let value = key
.split('.')
.enumerate()
.fold(
None, // Option<&V>
|last_value, (index, part)| {
if index == 0 {
return map.get(part);
}
return match last_value {
None => None,
Some(Compound(inner)) => inner.get(part),
_ => None
};
}
);
value.cloned()
}
fn print_value_map(map: &Map<String, Value>, level: &usize) {
@ -36,3 +48,22 @@ fn print_value_map(map: &Map<String, Value>, level: &usize) {
fn print_formatted_key(key: &str, level: &usize) {
println!("{space:>count$}{name}", space="", count=*level*4, name=key)
}
fn main() {
let cmd_name = env::args().take(1).next().unwrap_or("nbt_reader".to_string());
let usage = format!("Usage: {name} with .dat", name=cmd_name);
let file_name = env::args().take(2).nth(1).expect(&usage);
let nbt_blob = read_nbt(&file_name).unwrap_or_else(|| panic!("no valid nbt found at {path}", path=file_name));
let key_name = env::args().take(3).nth(2);
if let Some(nbt_key) = key_name {
let value = read_key(&nbt_blob.content, nbt_key.as_str());
println!("{}", value.expect("key does not exist"));
} else {
print_value_map(&nbt_blob.content, &0);
}
}