Skip to content

Commit 6515454

Browse files
committed
most result errors are strings
1 parent 3387e94 commit 6515454

File tree

10 files changed

+68
-64
lines changed

10 files changed

+68
-64
lines changed

git-function-history-lib/src/languages/c.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ pub struct ParentFunction {
6868
pub(crate) fn find_function_in_file(
6969
file_contents: &str,
7070
name: &str,
71-
) -> Result<Vec<CFunction>, Box<dyn Error>> {
71+
) -> Result<Vec<CFunction>, String> {
7272
println!("Finding function {} in commit {}", name, file_contents);
7373

7474
todo!("find_function_in_commit")

git-function-history-lib/src/languages/go.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::impl_function_trait;
2-
use std::{collections::HashMap, error::Error, fmt};
2+
use std::{collections::HashMap, fmt};
33

44
use super::FunctionTrait;
55

@@ -77,7 +77,7 @@ impl FunctionTrait for GoFunction {
7777
pub(crate) fn find_function_in_file(
7878
file_contents: &str,
7979
name: &str,
80-
) -> Result<Vec<GoFunction>, Box<dyn Error>> {
80+
) -> Result<Vec<GoFunction>, String> {
8181
let parsed_file = gosyn::parse_source(file_contents)
8282
.map_err(|e| format!("{e:?}"))?
8383
.decl;

git-function-history-lib/src/languages/java.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ pub enum JavaBlockType {
7272
pub(crate) fn find_function_in_file(
7373
file_contents: &str,
7474
name: &str,
75-
) -> Result<Vec<JavaFunction>, String> {
75+
) -> Result<Vec<JavaFunction>, &str> {
7676
let file = javaparser::parse::apply(file_contents, "<stdin>").map_err(|_| "Parse error")?;
7777
let parsed = file.unit.clone().items;
7878
let mut functions = Vec::new();
@@ -85,7 +85,7 @@ pub(crate) fn find_function_in_file(
8585
fn extract_methods_from_compilation_unit(
8686
unit: &CompilationUnitItem<'_>,
8787
name: &str,
88-
) -> Result<Vec<JavaFunction>, String> {
88+
) -> Result<Vec<JavaFunction>, &str> {
8989
// recursively search for items with type Method
9090
let mut methods = Vec::new();
9191

@@ -128,7 +128,7 @@ fn extract_methods_from_compilation_unit(
128128
fn extract_methods_from_class_item(
129129
item: &javaparser::parse::tree::ClassBodyItem<'_>,
130130
name: &str,
131-
) -> Result<Vec<JavaFunction>, String> {
131+
) -> Result<Vec<JavaFunction>, &str> {
132132
let mut methods = Vec::new();
133133
match item {
134134
javaparser::parse::tree::ClassBodyItem::Method(method) => {
@@ -241,7 +241,7 @@ fn extract_methods_from_class_item(
241241
fn extract_methods_from_annotation_item(
242242
item: &javaparser::parse::tree::AnnotationBodyItem<'_>,
243243
name: &str,
244-
) -> Result<Vec<JavaFunction>, String> {
244+
) -> Result<Vec<JavaFunction>, &str> {
245245
let mut methods = Vec::new();
246246
match item {
247247
javaparser::parse::tree::AnnotationBodyItem::Annotation(annotation) => {

git-function-history-lib/src/languages/mod.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use crate::{Filter, UnwrapToError};
22
use std::{
33
collections::HashMap,
4-
error::Error,
54
fmt::{self},
65
};
76
// TODO: lisp/scheme js, java?(https://github.com/tanin47/javaparser.rs) php?(https://docs.rs/tagua-parser/0.1.0/tagua_parser/)
@@ -55,7 +54,7 @@ impl Language {
5554
/// # Errors
5655
///
5756
/// `Err` will be returned if the string is not a valid language
58-
pub fn from_string(s: &str) -> Result<Self, Box<dyn Error>> {
57+
pub fn from_string(s: &str) -> Result<Self, String> {
5958
match s {
6059
"python" => Ok(Self::Python),
6160
"rust" => Ok(Self::Rust),
@@ -193,13 +192,13 @@ pub trait FileTrait: fmt::Debug + fmt::Display {
193192
///
194193
/// returns `Err` if the wrong filter is given, only `PLFilter` and `FunctionInLines` variants of `Filter` are valid.
195194
/// with `PLFilter` it will return `Err` if you mismatch the file type with the filter Ie: using `RustFile` and `PythonFilter` will return `Err`.
196-
fn filter_by(&self, filter: &Filter) -> Result<Self, Box<dyn Error>>
195+
fn filter_by(&self, filter: &Filter) -> Result<Self, String>
197196
where
198197
Self: Sized;
199198
fn get_current(&self) -> Option<Box<dyn FunctionTrait>>;
200199
}
201200

202-
fn turn_into_index(snippet: &str) -> Result<HashMap<usize, Vec<usize>>, Box<dyn Error>> {
201+
fn turn_into_index(snippet: &str) -> Result<HashMap<usize, Vec<usize>>, String> {
203202
// turn snippet into a hashmap of line number to char index
204203
// so line 1 is 0 to 10, line 2 is 11 to 20, etc
205204
let mut index = HashMap::new();
@@ -279,7 +278,7 @@ macro_rules! make_file {
279278
.map(|x| Box::new(x) as Box<dyn FunctionTrait>)
280279
.collect()
281280
}
282-
fn filter_by(&self, filter: &Filter) -> Result<Self, Box<dyn Error>> {
281+
fn filter_by(&self, filter: &Filter) -> Result<Self, String> {
283282
let mut filtered_functions = Vec::new();
284283
if let Filter::PLFilter(LanguageFilter::$filtername(_))
285284
| Filter::FunctionInLines(..) = filter

git-function-history-lib/src/languages/python.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,11 +101,14 @@ pub struct PythonParentFunction {
101101
pub(crate) fn find_function_in_file(
102102
file_contents: &str,
103103
name: &str,
104-
) -> Result<Vec<PythonFunction>, Box<dyn std::error::Error>> {
105-
let ast = parser::parse_program(file_contents, "<stdin>")?;
104+
) -> Result<Vec<PythonFunction>, String> {
105+
let ast = match parser::parse_program(file_contents, "<stdin>") {
106+
Ok(ast) => ast,
107+
Err(e) => return Err(format!("error parsing file: {e}")),
108+
};
106109
let mut functions = vec![];
107110
if ast.is_empty() {
108-
return Err("No code found")?;
111+
return Err("no code found".to_string());
109112
}
110113
let mut starts = file_contents
111114
.match_indices('\n')
@@ -244,7 +247,7 @@ pub(crate) fn find_function_in_file(
244247
}
245248
}
246249
if new.is_empty() {
247-
Err("No function found")?;
250+
return Err("no functions found".to_string());
248251
}
249252
Ok(new)
250253
}

git-function-history-lib/src/languages/ruby.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::{collections::HashMap, error::Error, fmt};
1+
use std::{collections::HashMap, fmt};
22

33
use lib_ruby_parser::{
44
nodes::{Class, Def},
@@ -115,7 +115,7 @@ impl Default for RubyParams {
115115
pub(crate) fn find_function_in_file(
116116
file_contents: &str,
117117
name: &str,
118-
) -> Result<Vec<RubyFunction>, Box<dyn Error>> {
118+
) -> Result<Vec<RubyFunction>, String> {
119119
let mut starts = file_contents
120120
.match_indices('\n')
121121
.map(|x| x.0)
@@ -128,6 +128,11 @@ pub(crate) fn find_function_in_file(
128128
.collect::<HashMap<usize, &usize>>();
129129
let parser = Parser::new(file_contents, ParserOptions::default());
130130
let parsed = parser.do_parse();
131+
for d in parsed.diagnostics {
132+
if d.is_error() {
133+
return Err(d.message.render())?;
134+
}
135+
}
131136
// POSSBLE TODO check if there is any error dianostics parsed.dadnostices and return error is so
132137
let ast = parsed.ast.unwrap_to_error("Failed to parse file")?;
133138
let fns = get_functions_from_node(&ast, &vec![], name);
@@ -175,7 +180,7 @@ pub(crate) fn find_function_in_file(
175180
let end_line = super::get_from_index(&index, f.expression_l.end)
176181
.unwrap_to_error("Failed to get end line")?;
177182
let starts = start_line + 1;
178-
Ok::<RubyFunction, Box<dyn Error>>(RubyFunction {
183+
Ok::<RubyFunction, String>(RubyFunction {
179184
name: f.name.clone(),
180185
lines: (start_line, end_line),
181186
class,

git-function-history-lib/src/languages/rust.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::{collections::HashMap, error::Error, fmt};
1+
use std::{collections::HashMap, fmt};
22

33
use ra_ap_syntax::{
44
ast::{self, HasDocComments, HasGenericParams, HasName},
@@ -207,7 +207,7 @@ impl fmt::Display for BlockType {
207207
pub(crate) fn find_function_in_file(
208208
file_contents: &str,
209209
name: &str,
210-
) -> Result<Vec<RustFunction>, Box<dyn Error>> {
210+
) -> Result<Vec<RustFunction>, String> {
211211
let mut functions = Vec::new();
212212
get_function_asts(name, file_contents, &mut functions);
213213
let mut starts = file_contents

git-function-history-lib/src/languages/umpl.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use umpl::{self, parser::Thing};
22

3-
use std::{error::Error, fmt};
3+
use std::{fmt};
44

55
use crate::impl_function_trait;
66

@@ -68,7 +68,7 @@ impl FunctionTrait for UMPLFunction {
6868
pub(crate) fn find_function_in_file(
6969
file_contents: &str,
7070
name: &str,
71-
) -> Result<Vec<UMPLFunction>, Box<dyn Error>> {
71+
) -> Result<Vec<UMPLFunction>, String> {
7272
// parse the file contents
7373
let lexed = umpl::lexer::Lexer::new(file_contents.to_string());
7474
let tokens = lexed.scan_tokens();
@@ -78,7 +78,7 @@ pub(crate) fn find_function_in_file(
7878
if !res.is_empty() {
7979
return Ok(res);
8080
}
81-
Err("no function found")?
81+
Err(String::from("Function not found"))
8282
}
8383

8484
fn find_function_recurse(

git-function-history-lib/src/lib.rs

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ macro_rules! get_item_from {
2020
($oid:expr, $repo:expr, $typs:ident) => {
2121
git_repository::hash::ObjectId::from($oid)
2222
.attach(&$repo)
23-
.object()?
24-
.$typs()?
23+
.object().map_err(|_| "Could not find object")?
24+
.$typs().map_err(|_| format!("Could not find {} from object", stringify!($typs)))?
2525
};
2626
}
2727

@@ -170,7 +170,7 @@ pub fn get_function_history(
170170
// elem.0.signed_duration_since(date)
171171
})
172172
.map(|elem| elem.hash.clone())
173-
.unwrap_to_error_sync("no commits found")?
173+
.unwrap_to_error("no commits found")?
174174
}
175175
Filter::Author(_)
176176
| Filter::AuthorEmail(_)
@@ -310,9 +310,9 @@ fn sender(
310310
name: &str,
311311
langs: Language,
312312
file: &FileFilterType,
313-
) -> Result<Vec<FileType>, Box<dyn std::error::Error>> {
314-
let object = repo.find_object(id)?;
315-
let tree = object.try_into_tree()?;
313+
) -> Result<Vec<FileType>, String> {
314+
let object = repo.find_object(id).map_err(|_| "failed to find object")?;
315+
let tree = object.try_into_tree().map_err(|_| "failed to find tree")?;
316316
traverse_tree(&tree, repo, name, "", langs, file)
317317
}
318318

@@ -323,12 +323,12 @@ fn traverse_tree(
323323
path: &str,
324324
langs: Language,
325325
filetype: &FileFilterType,
326-
) -> Result<Vec<FileType>, Box<dyn std::error::Error>> {
326+
) -> Result<Vec<FileType>, String> {
327327
let treee_iter = tree.iter();
328328
let mut files: Vec<(String, String)> = Vec::new();
329329
let mut ret = Vec::new();
330330
for i in treee_iter {
331-
let i = i?;
331+
let i = i.map_err(|_| "failed to get tree entry")?;
332332
match &i.mode() {
333333
objs::tree::EntryMode::Tree => {
334334
let new = get_item_from!(i.oid(), &repo, try_into_tree);
@@ -414,8 +414,8 @@ fn traverse_tree(
414414
}
415415
},
416416
}
417-
let obh = repo.find_object(i.oid())?;
418-
let objref = objs::ObjectRef::from_bytes(obh.kind, &obh.data)?;
417+
let obh = repo.find_object(i.oid()).map_err(|_| "failed to find object")?;
418+
let objref = objs::ObjectRef::from_bytes(obh.kind, &obh.data).map_err(|_| "failed to get object ref")?;
419419
let blob = objref.into_blob();
420420
if let Some(blob) = blob {
421421
files.push((file, String::from_utf8_lossy(blob.data).to_string()));
@@ -531,10 +531,10 @@ fn find_function_in_file_with_commit(
531531
fc: &str,
532532
name: &str,
533533
langs: Language,
534-
) -> Result<FileType, Box<dyn Error>> {
534+
) -> Result<FileType, String> {
535535
let file = match langs {
536536
Language::Rust => {
537-
let functions = rust::find_function_in_file(fc, name)?;
537+
let functions = rust::find_function_in_file(fc, name)?;
538538
FileType::Rust(RustFile::new(file_path.to_string(), functions))
539539
}
540540
// #[cfg(feature = "c_lang")]
@@ -544,24 +544,25 @@ fn find_function_in_file_with_commit(
544544
// }
545545
#[cfg(feature = "unstable")]
546546
Language::Go => {
547-
let functions = languages::go::find_function_in_file(fc, name)?;
547+
let functions = languages::go::find_function_in_file(fc, name)?;
548548
FileType::Go(GoFile::new(file_path.to_string(), functions))
549549
}
550550
Language::Python => {
551-
let functions = languages::python::find_function_in_file(fc, name)?;
551+
let functions = languages::python::find_function_in_file(fc, name)?;
552552
FileType::Python(PythonFile::new(file_path.to_string(), functions))
553553
}
554554
Language::Ruby => {
555-
let functions = languages::ruby::find_function_in_file(fc, name)?;
555+
let functions = languages::ruby::find_function_in_file(fc, name)?;
556556
FileType::Ruby(RubyFile::new(file_path.to_string(), functions))
557557
}
558558
Language::UMPL => {
559-
let functions = languages::umpl::find_function_in_file(fc, name)?;
559+
let functions = languages::umpl::find_function_in_file(fc, name)?;
560560
FileType::UMPL(UMPLFile::new(file_path.to_string(), functions))
561561
}
562562
Language::All => match file_path.split('.').last() {
563563
Some("rs") => {
564-
let functions = rust::find_function_in_file(fc, name)?;
564+
565+
let functions = rust::find_function_in_file(fc, name)?;
565566
FileType::Rust(RustFile::new(file_path.to_string(), functions))
566567
}
567568
// #[cfg(feature = "c_lang")]
@@ -570,16 +571,16 @@ fn find_function_in_file_with_commit(
570571
// FileType::C(CFile::new(file_path.to_string(), functions))
571572
// }
572573
Some("py" | "pyw") => {
573-
let functions = languages::python::find_function_in_file(fc, name)?;
574+
let functions = languages::python::find_function_in_file(fc, name)?;
574575
FileType::Python(PythonFile::new(file_path.to_string(), functions))
575576
}
576577
#[cfg(feature = "unstable")]
577578
Some("go") => {
578-
let functions = languages::go::find_function_in_file(fc, name)?;
579+
let functions = languages::go::find_function_in_file(fc, name)?;
579580
FileType::Go(GoFile::new(file_path.to_string(), functions))
580581
}
581582
Some("rb") => {
582-
let functions = languages::ruby::find_function_in_file(fc, name)?;
583+
let functions = languages::ruby::find_function_in_file(fc, name)?;
583584
FileType::Ruby(RubyFile::new(file_path.to_string(), functions))
584585
}
585586
_ => Err("unknown file type")?,
@@ -613,16 +614,13 @@ fn ends_with_cmp_no_case(filename: &str, file_ext: &str) -> bool {
613614
}
614615

615616
trait UnwrapToError<T> {
616-
fn unwrap_to_error_sync(self, message: &str) -> Result<T, Box<dyn Error + Send + Sync>>;
617-
fn unwrap_to_error(self, message: &str) -> Result<T, Box<dyn Error>>;
617+
fn unwrap_to_error(self, message: &str) -> Result<T, String>;
618618
}
619619

620620
impl<T> UnwrapToError<T> for Option<T> {
621-
fn unwrap_to_error_sync(self, message: &str) -> Result<T, Box<dyn Error + Send + Sync>> {
622-
self.map_or_else(|| Err(message)?, |val| Ok(val))
623-
}
624-
fn unwrap_to_error(self, message: &str) -> Result<T, Box<dyn Error>> {
625-
self.map_or_else(|| Err(message)?, |val| Ok(val))
621+
622+
fn unwrap_to_error(self, message: &str) -> Result<T, String> {
623+
self.map_or_else(|| Err(message.to_string()), |val| Ok(val))
626624
}
627625
}
628626

0 commit comments

Comments
 (0)