Skip to content

Commit

Permalink
update dependencies and formatting (#88)
Browse files Browse the repository at this point in the history
  • Loading branch information
notJoon authored Mar 19, 2024
1 parent 742e23c commit ead19cc
Show file tree
Hide file tree
Showing 18 changed files with 404 additions and 332 deletions.
568 changes: 303 additions & 265 deletions Cargo.lock

Large diffs are not rendered by default.

19 changes: 11 additions & 8 deletions src/analyzer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ impl<'tree> Analyzer {
let node_type = current_node.kind();

// rust specific code
if node_type == "mod_item" && node_range.start_point.row == node_range.end_point.row {
if node_type == "mod_item"
&& node_range.start_point.row == node_range.end_point.row
{
while !pending_queue.is_empty() {
let decorator_line: &str = pending_queue.pop_front().unwrap();
writer_queue.push_back(decorator_line.to_owned());
Expand Down Expand Up @@ -160,18 +162,15 @@ impl<'tree> Analyzer {

if nested_traversable_symbols.contains(&node_type) {
let (_, from, to) = current_node.identifier_range();

let symbol: String;
if from.to_owned() == 0 && to.to_owned() == 0 {
if from == 0 && to == 0 {
symbol = "anonymous".to_string();
} else {
symbol = line[from.to_owned()..to.to_owned()].to_string();
}

indentation_context.push_back((
*current_node,
symbol
));
indentation_context.push_back((*current_node, symbol));
pop_node = true;
}

Expand Down Expand Up @@ -242,7 +241,11 @@ impl<'tree> Analyzer {
result.to_owned()
}

fn enqueue_child_nodes(&self, mut deq: VecDeque<Node<'tree>>, node: &Node<'tree>) -> VecDeque<Node<'tree>> {
fn enqueue_child_nodes(
&self,
mut deq: VecDeque<Node<'tree>>,
node: &Node<'tree>,
) -> VecDeque<Node<'tree>> {
let mut cursor = node.walk();
let scannable_node_types = self.language.scannable_node_types();
let node_type = node.kind();
Expand Down
70 changes: 51 additions & 19 deletions src/commands/grep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,39 +140,57 @@ impl GrepReport {
result
}

fn format_plain(&self, hide_path: bool, list_of_files: bool, count: bool, patterns_to_search: Vec<String>, colorize: bool) -> String {
fn format_plain(
&self,
hide_path: bool,
list_of_files: bool,
count: bool,
patterns_to_search: Vec<String>,
colorize: bool,
) -> String {
let mut result = String::new();
let mut counter: usize = 0;

if !count {
for dir in &self.directories {
let path = Path::new(&dir.name);

if !hide_path {
dir_path_pretty(path, &mut result);
}

for file in &dir.files {
if !hide_path {
let file_name = Path::new(&file.name);
let last_two = last_two(file_name);
result.push_str(&format!("{}\n", last_two[0]));
}

if !list_of_files {
for item in &file.items {
if colorize {
// `(?i)` is for case insensitive search
let pattern = Regex::new(&format!(r"(?i){}", patterns_to_search.join(" "))).unwrap();
let pattern =
Regex::new(&format!(r"(?i){}", patterns_to_search.join(" ")))
.unwrap();
let text = &item.content;

let colored_text = pattern.replace_all(text, |caps: &regex::Captures| {
format!("\x1b[31m{}\x1b[0m", &caps[0])
});
let colored_text = pattern
.replace_all(text, |caps: &regex::Captures| {
format!("\x1b[31m{}\x1b[0m", &caps[0])
});

result.push_str(&format!("{} {}", item.line, colored_text.trim_start()));
result.push_str(&format!(
"{} {}",
item.line,
colored_text.trim_start()
));
} else {
result.push_str(&format!("{} {}", item.line, item.content.trim_start()));
result.push_str(&format!(
"{} {}",
item.line,
item.content.trim_start()
));
}
counter += 1;
}
Expand All @@ -184,24 +202,39 @@ impl GrepReport {
}
result.push_str(&format!("\nTotal {} lines found\n", counter));
} else {
counter = self.directories
counter = self
.directories
.iter()
.map(|dir| dir.files.iter().map(|file| file.items.len())
.sum::<usize>()).sum();
.map(|dir| dir.files.iter().map(|file| file.items.len()).sum::<usize>())
.sum();
result = format!("Total {} lines found\n", counter);
}

result
}

#[allow(clippy::too_many_arguments)]
pub fn report_formatting(&mut self, format: Option<String>, hide_path: bool, list_of_files: bool, count: bool, patterns_to_search: Vec<String>, colorize: bool) -> String {
pub fn report_formatting(
&mut self,
format: Option<String>,
hide_path: bool,
list_of_files: bool,
count: bool,
patterns_to_search: Vec<String>,
colorize: bool,
) -> String {
let default = "plain".to_string();
let format = format.unwrap_or(default);

match format.as_str() {
"json" => serde_json::to_string_pretty(self).unwrap(),
"plain" => self.format_plain(hide_path, list_of_files, count, patterns_to_search, colorize),
"plain" => self.format_plain(
hide_path,
list_of_files,
count,
patterns_to_search,
colorize,
),
// "tree" => self.format_tree(4),
_ => {
let suggest = suggest_subcommand(&format).unwrap();
Expand All @@ -228,8 +261,7 @@ impl GrepReport {
}

fn last_two(path: &Path) -> Vec<&str> {
path
.iter()
path.iter()
.rev()
.take(2)
.map(|s| s.to_str().unwrap())
Expand Down
11 changes: 3 additions & 8 deletions src/language.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@ impl Language {
match self {
Language::Rust => "source_file",
Language::Python => "module",
Language::Ruby
| Language::JavaScript
| Language::TypeScript => "program",
Language::Ruby | Language::JavaScript | Language::TypeScript => "program",
Language::Cpp => "translation_unit",
_ => "",
}
Expand All @@ -53,9 +51,7 @@ impl Language {
pub fn decorator_node_type(&self) -> &str {
match self {
Language::Rust => "attribute_item",
Language::Python
| Language::Ruby
| Language::Cpp => "null",
Language::Python | Language::Ruby | Language::Cpp => "null",
Language::TypeScript | Language::JavaScript => "decorator",
_ => "",
}
Expand Down Expand Up @@ -142,8 +138,7 @@ impl Language {
Language::Python => vec!["class_definition"],
Language::Ruby => vec!["class", "module"],
Language::Cpp => vec!["namespace_definition", "class_specifier"],
Language::TypeScript
| Language::JavaScript => vec![
Language::TypeScript | Language::JavaScript => vec![
"class_declaration",
"expression_statement",
"internal_module",
Expand Down
12 changes: 7 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ enum BalpanCommand {
Analyze {
#[clap(short, long, help = "Specific file to scan")]
pattern: Option<String>,
}
},
}

fn create_runtime() -> Runtime {
Expand Down Expand Up @@ -143,10 +143,12 @@ fn main() {
}
BalpanCommand::Analyze { pattern } => {
match pattern {
Some(ref p) => if !p.starts_with('"') || !p.ends_with('"') {
panic!("Invalid file path. Please include double quotes(`\"`) in the path.")
},
None => panic!("No file specified. Please specify a file path to analyze")
Some(ref p) => {
if !p.starts_with('"') || !p.ends_with('"') {
panic!("Invalid file path. Please include double quotes(`\"`) in the path.")
}
}
None => panic!("No file specified. Please specify a file path to analyze"),
}

let runtime = create_runtime();
Expand Down
18 changes: 11 additions & 7 deletions src/tree_sitter_extended.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,19 +70,22 @@ pub trait ResolveSymbol {

impl ResolveSymbol for Node<'_> {
fn identifier_range(&self) -> (usize, usize, usize) {
let simple_cases = vec![
"attribute_item", "use_declaration", "macro_invocation",
"expression_statement", "foreign_mod_item"
let simple_cases = [
"attribute_item",
"use_declaration",
"macro_invocation",
"expression_statement",
"foreign_mod_item",
];

if simple_cases.contains(&self.kind()) {
return (0, 0, 0)
return (0, 0, 0);
}

let mut node = self.child_by_field_name("name");

if self.kind() == "namespace_definition" && node.is_none() {
return (0, 0, 0)
return (0, 0, 0);
}

if self.kind() == "function_definition" {
Expand Down Expand Up @@ -115,15 +118,16 @@ impl ResolveSymbol for Node<'_> {
// this case handles import statement especially `export * from './compiler_facade_interface';` things.
// I think this is not a good way to handle this case, but I don't know how to handle this case.
if self.child_by_field_name("source").is_some() {
return (0, 0, 0)
return (0, 0, 0);
}

if let Some(child) = self.child_by_field_name("declaration") {
node = child.child_by_field_name("name");
}
}

let identifier_node = node.unwrap_or_else(|| panic!("`{}` is an invalid identifier node type", self.kind()));
let identifier_node =
node.unwrap_or_else(|| panic!("`{}` is an invalid identifier node type", self.kind()));

let from = identifier_node.start_position().column;
let row = identifier_node.end_position().row;
Expand Down
2 changes: 1 addition & 1 deletion tests/integration_test/analyze_command_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ mod c_test;
mod typescript_test;

#[cfg(test)]
mod javascript_test;
mod javascript_test;
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ fn test_templated_function_definition() {
return d_value.apply(visitor);
}
"#};

let result = indoc! { r#"
/// [TODO] parseCommand
template <typename CMD>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
mod react_native_case_test;
#[cfg(test)]
mod svelt_cast_test;
mod react_native_case_test;
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,4 @@ fn test_class() {
}"#};

assert_analyzed_source_code(source_code, expected, "javascript")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@ fn test_arrow_function() {
});"#};

assert_analyzed_source_code(source_code, expected, "javascript")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,16 @@ fn test_declaring_enum_with_stacked_attribute() {
/// https://github.com/RustPython/RustPython/blob/bdb0c8f64557e0822f0bcfd63defbad54625c17a/vm/src/compiler.rs#L5C1-L6
#[test]
fn test_macro_above_use_declaration_should_be_ignored() {
let source_code = indoc! { r#"
let source_code = indoc! { r#"
#[cfg(feature = "rustpython-compiler")]
use rustpython_compiler::*;"#};

let result = indoc! { r#"
let result = indoc! { r#"
#[cfg(feature = "rustpython-compiler")]
use rustpython_compiler::*;"#};

assert_analyzed_source_code(source_code, result, "rust")
}

}

/// https://github.com/RustPython/RustPython/blob/bdb0c8f64557e0822f0bcfd63defbad54625c17a/wasm/lib/src/js_module.rs#L24-L55
#[test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ fn test_several_impl_declaration() {
assert_analyzed_source_code(source_code, result, "rust")
}


/// https://github.com/serde-rs/serde/blob/7b548db91ed7da81a5c0ddbd6f6f21238aacfebe/serde/src/lib.rs#L155-L156
#[test]
fn test_macro_above_extern_crate_declaration_should_be_ignored() {
Expand Down Expand Up @@ -82,7 +81,7 @@ fn test_macro_above_static_variable_should_be_ignored() {
/// https://github.com/serde-rs/serde/blob/7b548db91ed7da81a5c0ddbd6f6f21238aacfebe/serde/src/de/impls.rs#L1783-L1793
#[test]
fn test_macro_above_macro_invocation_should_be_ignored() {
let source_code = indoc! { r#"
let source_code = indoc! { r#"
#[cfg(any(feature = "std", feature = "alloc"))]
forwarded_impl!((T), Box<T>, Box::new);
Expand All @@ -95,7 +94,7 @@ fn test_macro_above_macro_invocation_should_be_ignored() {
#[cfg(all(feature = "std", any(unix, windows)))]
forwarded_impl!((), Box<OsStr>, OsString::into_boxed_os_str);"#};

let result = indoc! { r#"
let result = indoc! { r#"
#[cfg(any(feature = "std", feature = "alloc"))]
forwarded_impl!((T), Box<T>, Box::new);
Expand Down Expand Up @@ -134,5 +133,5 @@ fn test_ignore_mod_items_in_a_row() {
pub(crate) mod size_hint;
mod utf8;"#};

assert_analyzed_source_code(source_code, result, "rust");
assert_analyzed_source_code(source_code, result, "rust");
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ mod angular_case_test;
mod async_case_test;

#[cfg(test)]
mod svelt_case_test;
mod svelt_case_test;
Original file line number Diff line number Diff line change
Expand Up @@ -257,4 +257,4 @@ fn test_normal_class_statement() {
}"#};

assert_analyzed_source_code(source_code, expected, "typescript")
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use indoc::indoc;
use crate::integration_test::assert_analyzed_source_code;
use indoc::indoc;

#[test]
fn test_async_function_expression() {
Expand Down Expand Up @@ -36,4 +36,4 @@ fn test_async_arrow_function() {
}"#};

assert_analyzed_source_code(source_code, expected, "typescript")
}
}
Loading

0 comments on commit ead19cc

Please sign in to comment.