drop Jeftai Error, convert errors to anyhow

This commit is contained in:
Quaternions 2023-10-01 20:07:34 -07:00
parent a2b793fcd3
commit d6dd1b8abd
3 changed files with 28 additions and 75 deletions

View File

@ -1,21 +0,0 @@
#[derive(Debug)]
pub struct Error {
pub message: String,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for Error {}
impl Error {
// has to be Box<Self> to fit with the result in prelude.rs
pub fn new(message: &str) -> Box<Self> {
Box::new(Self {
message: message.to_string(),
})
}
}

View File

@ -1,14 +1,6 @@
use std::io::{Read, Seek}; use std::io::{Read, Seek};
use clap::{Args, Parser, Subcommand}; use clap::{Args, Parser, Subcommand};
use anyhow::Result as AResult;
mod error;
mod prelude;
// this * means we are importing everything from the prelude module and in turn we overwrite the default `Result` with our own
// if you want the original back you can use StdResult<T, E> or just std::result::Result<T, E>
// using the new result also means the error type is implicitly Box<dyn std::error::Error> (works for any errors that implement the std::error::Error trait)
use crate::prelude::*;
#[derive(Parser)] #[derive(Parser)]
#[command(author, version, about, long_about = None)] #[command(author, version, about, long_about = None)]
@ -105,25 +97,25 @@ fn get_texture_refs(dom:&rbx_dom_weak::WeakDom) -> Vec<rbx_dom_weak::types::Ref>
objects objects
} }
fn get_dom<R:Read+Seek>(input:&mut R)->Result<rbx_dom_weak::WeakDom,String>{ fn get_dom<R:Read+Seek>(input:&mut R)->AResult<rbx_dom_weak::WeakDom>{
let mut first_8=[0u8;8]; let mut first_8=[0u8;8];
if let (Ok(()),Ok(()))=(std::io::Read::read_exact(input, &mut first_8),std::io::Seek::rewind(input)){ if let (Ok(()),Ok(()))=(std::io::Read::read_exact(input, &mut first_8),std::io::Seek::rewind(input)){
match &first_8[0..4]{ match &first_8[0..4]{
b"<rob"=>{ b"<rob"=>{
match &first_8[4..8]{ match &first_8[4..8]{
b"lox!"=>rbx_binary::from_reader(input).map_err(|e|format!("{:?}",e)), b"lox!"=>return rbx_binary::from_reader(input).map_err(anyhow::Error::msg),
b"lox "=>rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()).map_err(|e|format!("{:?}",e)), b"lox "=>return rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()).map_err(anyhow::Error::msg),
other=>Err(format!("Unknown Roblox file type {:?}",other)), other=>Err(anyhow::Error::msg(format!("Unknown Roblox file type {:?}",other))),
} }
} }
_=>Err("unsupported file type".to_owned()), _=>Err(anyhow::Error::msg("unsupported file type")),
} }
}else{ }else{
Err("peek failed".to_owned()) Err(anyhow::Error::msg("peek failed"))
} }
} }
fn get_id() -> BoxResult<u32>{ fn get_id() -> AResult<u32>{
match std::fs::read_to_string("id"){ match std::fs::read_to_string("id"){
Ok(id_file)=>Ok(id_file.parse::<u32>()?), Ok(id_file)=>Ok(id_file.parse::<u32>()?),
Err(e) => match e.kind() { Err(e) => match e.kind() {
@ -133,7 +125,7 @@ fn get_id() -> BoxResult<u32>{
} }
} }
fn get_set_from_file(file:&str) -> BoxResult<std::collections::HashSet<String>>{ fn get_set_from_file(file:&str) -> AResult<std::collections::HashSet<String>>{
let mut set=std::collections::HashSet::<String>::new(); let mut set=std::collections::HashSet::<String>::new();
for entry in std::fs::read_dir(file)? { for entry in std::fs::read_dir(file)? {
set.insert(std::fs::read_to_string(entry?.path())?); set.insert(std::fs::read_to_string(entry?.path())?);
@ -141,15 +133,15 @@ fn get_set_from_file(file:&str) -> BoxResult<std::collections::HashSet<String>>{
Ok(set) Ok(set)
} }
fn get_allowed_set() -> BoxResult<std::collections::HashSet<String>>{ fn get_allowed_set() -> AResult<std::collections::HashSet<String>>{
get_set_from_file("scripts/allowed") get_set_from_file("scripts/allowed")
} }
fn get_blocked() -> BoxResult<std::collections::HashSet<String>>{ fn get_blocked() -> AResult<std::collections::HashSet<String>>{
get_set_from_file("scripts/blocked") get_set_from_file("scripts/blocked")
} }
fn get_allowed_map() -> BoxResult<std::collections::HashMap::<u32,String>>{ fn get_allowed_map() -> AResult<std::collections::HashMap::<u32,String>>{
let mut allowed_map = std::collections::HashMap::<u32,String>::new(); let mut allowed_map = std::collections::HashMap::<u32,String>::new();
for entry in std::fs::read_dir("scripts/allowed")? { for entry in std::fs::read_dir("scripts/allowed")? {
let entry=entry?; let entry=entry?;
@ -158,7 +150,7 @@ fn get_allowed_map() -> BoxResult<std::collections::HashMap::<u32,String>>{
Ok(allowed_map) Ok(allowed_map)
} }
fn get_replace_map() -> BoxResult<std::collections::HashMap::<String,u32>>{ fn get_replace_map() -> AResult<std::collections::HashMap::<String,u32>>{
let mut replace = std::collections::HashMap::<String,u32>::new(); let mut replace = std::collections::HashMap::<String,u32>::new();
for entry in std::fs::read_dir("scripts/replace")? { for entry in std::fs::read_dir("scripts/replace")? {
let entry=entry?; let entry=entry?;
@ -182,10 +174,10 @@ fn find_first_child_class<'a>(dom:&'a rbx_dom_weak::WeakDom,instance:&'a rbx_dom
None None
} }
fn get_mapinfo(dom:&rbx_dom_weak::WeakDom) -> BoxResult<(String,String,String)>{ fn get_mapinfo(dom:&rbx_dom_weak::WeakDom) -> AResult<(String,String,String)>{
let workspace_children=dom.root().children(); let workspace_children=dom.root().children();
if workspace_children.len()!=1{ if workspace_children.len()!=1{
return Err(Error::new("there can only be one model")); return Err(anyhow::Error::msg("there can only be one model"));
} }
if let Some(model_instance) = dom.get_by_ref(workspace_children[0]) { if let Some(model_instance) = dom.get_by_ref(workspace_children[0]) {
if let (Some(creator),Some(displayname))=(find_first_child_class(dom, model_instance, "Creator", "StringValue"),find_first_child_class(dom, model_instance, "DisplayName", "StringValue")){ if let (Some(creator),Some(displayname))=(find_first_child_class(dom, model_instance, "Creator", "StringValue"),find_first_child_class(dom, model_instance, "DisplayName", "StringValue")){
@ -200,10 +192,10 @@ fn get_mapinfo(dom:&rbx_dom_weak::WeakDom) -> BoxResult<(String,String,String)>{
} }
} }
} }
return Err(Error::new("no stuff in map")); return Err(anyhow::Error::msg("no stuff in map"));
} }
fn download(map_list: Vec<u64>) -> BoxResult<()>{ fn download(map_list: Vec<u64>) -> AResult<()>{
let header=format!("Cookie: .ROBLOSECURITY={}",std::env::var("RBXCOOKIE")?); let header=format!("Cookie: .ROBLOSECURITY={}",std::env::var("RBXCOOKIE")?);
let shared_args=&[ let shared_args=&[
"-q", "-q",
@ -268,7 +260,7 @@ SurfaceAppearance.NormalMap
SurfaceAppearance.RoughnessMap SurfaceAppearance.RoughnessMap
SurfaceAppearance.TexturePack SurfaceAppearance.TexturePack
*/ */
fn download_textures(paths: Vec<std::path::PathBuf>) -> BoxResult<()>{ fn download_textures(paths: Vec<std::path::PathBuf>) -> AResult<()>{
println!("download_textures paths:{:?}",paths); println!("download_textures paths:{:?}",paths);
let header=format!("Cookie: .ROBLOSECURITY={}",std::env::var("RBXCOOKIE")?); let header=format!("Cookie: .ROBLOSECURITY={}",std::env::var("RBXCOOKIE")?);
let shared_args=&[ let shared_args=&[
@ -314,7 +306,7 @@ fn download_textures(paths: Vec<std::path::PathBuf>) -> BoxResult<()>{
Ok(()) Ok(())
} }
fn convert(file_thing:std::fs::DirEntry) -> BoxResult<()>{ fn convert(file_thing:std::fs::DirEntry) -> AResult<()>{
let mut input = std::io::BufReader::new(std::fs::File::open(file_thing.path())?); let mut input = std::io::BufReader::new(std::fs::File::open(file_thing.path())?);
let mut fourcc=[0u8;4]; let mut fourcc=[0u8;4];
input.read_exact(&mut fourcc)?; input.read_exact(&mut fourcc)?;
@ -330,7 +322,7 @@ fn convert(file_thing:std::fs::DirEntry) -> BoxResult<()>{
extracted_input=Some(extracted.clone()); extracted_input=Some(extracted.clone());
image::load(std::io::Cursor::new(extracted),image::ImageFormat::Png)?.to_rgba8() image::load(std::io::Cursor::new(extracted),image::ImageFormat::Png)?.to_rgba8()
}else{ }else{
Err(error::Error::new("Unknown texture format"))? return Err(anyhow::Error::msg("Unknown texture format"));
}; };
let format=if image.width()%4!=0||image.height()%4!=0{ let format=if image.width()%4!=0||image.height()%4!=0{
@ -368,7 +360,7 @@ fn convert(file_thing:std::fs::DirEntry) -> BoxResult<()>{
} }
Ok(()) Ok(())
} }
fn convert_textures() -> BoxResult<()>{ fn convert_textures() -> AResult<()>{
let start = std::time::Instant::now(); let start = std::time::Instant::now();
let mut threads=Vec::new(); let mut threads=Vec::new();
for entry in std::fs::read_dir("textures/unprocessed")? { for entry in std::fs::read_dir("textures/unprocessed")? {
@ -401,7 +393,7 @@ enum Scan{
Flagged, Flagged,
} }
fn scan() -> BoxResult<()>{ fn scan() -> AResult<()>{
let mut id = get_id()?; let mut id = get_id()?;
//Construct allowed scripts //Construct allowed scripts
let allowed_set = get_allowed_set()?; let allowed_set = get_allowed_set()?;
@ -460,7 +452,7 @@ fn scan() -> BoxResult<()>{
Ok(()) Ok(())
} }
fn extract(paths: Vec<std::path::PathBuf>) -> BoxResult<()>{ fn extract(paths: Vec<std::path::PathBuf>) -> AResult<()>{
let mut id = 0; let mut id = 0;
//Construct allowed scripts //Construct allowed scripts
let mut script_set = std::collections::HashSet::<String>::new(); let mut script_set = std::collections::HashSet::<String>::new();
@ -495,7 +487,7 @@ fn extract(paths: Vec<std::path::PathBuf>) -> BoxResult<()>{
println!("extracted {} {}",id,if id==1 {"script"}else{"scripts"}); println!("extracted {} {}",id,if id==1 {"script"}else{"scripts"});
Ok(()) Ok(())
} }
fn replace() -> BoxResult<()>{ fn replace() -> AResult<()>{
let allowed_map=get_allowed_map()?; let allowed_map=get_allowed_map()?;
let replace_map=get_replace_map()?; let replace_map=get_replace_map()?;
@ -568,7 +560,7 @@ impl std::str::FromStr for UploadAction {
} }
} }
fn upload() -> BoxResult<()>{ fn upload() -> AResult<()>{
//interactive prompt per upload: //interactive prompt per upload:
for entry in std::fs::read_dir("maps/passed")? { for entry in std::fs::read_dir("maps/passed")? {
let file_thing=entry?; let file_thing=entry?;
@ -677,7 +669,7 @@ impl std::str::FromStr for ScriptActionParseResult {
} }
} }
fn interactive() -> BoxResult<()>{ fn interactive() -> AResult<()>{
let mut id=get_id()?; let mut id=get_id()?;
//Construct allowed scripts //Construct allowed scripts
let mut allowed_set=get_allowed_set()?; let mut allowed_set=get_allowed_set()?;
@ -824,7 +816,7 @@ fn interactive() -> BoxResult<()>{
//write workspace:GetChildren()[1] //write workspace:GetChildren()[1]
let workspace_children=dom.root().children(); let workspace_children=dom.root().children();
if workspace_children.len()!=1{ if workspace_children.len()!=1{
return Err(Error::new("there can only be one model")); return Err(anyhow::Error::msg("there can only be one model"));
} }
rbx_binary::to_writer(output, &dom, &[workspace_children[0]])?; rbx_binary::to_writer(output, &dom, &[workspace_children[0]])?;
//move original to processed folder //move original to processed folder
@ -847,7 +839,7 @@ fn interactive() -> BoxResult<()>{
Ok(()) Ok(())
} }
fn main() -> BoxResult<()> { fn main() -> AResult<()> {
let cli = Cli::parse(); let cli = Cli::parse();
match cli.command { match cli.command {
Commands::Download(map_list)=>download(map_list.maps), Commands::Download(map_list)=>download(map_list.maps),

View File

@ -1,18 +0,0 @@
pub use crate::error::Error;
pub type BoxResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
// i just wanted to mess around with macros a bit
// so heres labelprint as a macro
#[macro_export]
macro_rules! lprint {
($expr:expr) => {{
let ___this_file = std::file!();
let ___line = std::line!();
// let ___column = column!();
println!("[{}:{}] {}", ___this_file, ___line, $expr);
}};
($expr:expr, $($arg:tt)*) => {{
lprint!(format!($expr, $($arg)*));
}};
}