Skip to content

Commit

Permalink
added comment removal too
Browse files Browse the repository at this point in the history
  • Loading branch information
maitrecraft1234 committed Sep 25, 2024
1 parent d8bc5e2 commit 5b98b4b
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/obfuscator/remove_comments_and_empty_lines.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,45 @@
use super::error::ObfuscatorError;
use super::Obfuscator;
use super::Result;
use super::Shiftable;
use tree_sitter::{Tree, TreeCursor};

fn get_comments(tree: &Tree) -> Vec<std::ops::Range<usize>> {
fn go(cursor: &mut TreeCursor, comments: &mut Vec<std::ops::Range<usize>>) {
let node = cursor.node();
if node.kind() == "comment" {
comments.push(node.start_byte()..node.end_byte());
}
if cursor.goto_first_child() {
go(cursor, comments);
cursor.goto_parent();
}
while cursor.goto_next_sibling() {
go(cursor, comments);
}
}
let mut comments = Vec::new();

go(&mut tree.walk(), &mut comments);

comments
}

impl Obfuscator {
pub fn remove_comments_and_empty_lines(&mut self) -> Result<()> {
let comments = get_comments(&self.tree);

let mut shift = 0;
comments.into_iter().for_each(|comment| {
let len = comment.len();

self.code.replace_range(comment.shift(shift), "");
shift -= len as i32;
});
self.code = self
.code
.lines()
.filter(|line| {!line.trim().is_empty()})
.filter(|line| !line.trim().is_empty())
.collect::<Vec<_>>()
.join("\n");
self.reparse(ObfuscatorError::RemoveCommentsAndEmptyLines)
Expand Down

0 comments on commit 5b98b4b

Please sign in to comment.