commentective/language/
lua.rs1use crate::language::{FindResult, Finder};
2use crate::utils::path::file_name;
3use crate::utils::string::contains_all;
4use crate::utils::string::contains_any_of;
5
6use std::fs::File;
7use std::io::{BufRead, BufReader, Error};
8use std::path::PathBuf;
9use std::vec::Vec;
10
11pub struct Lua {
12 _finder: Finder,
13}
14
15#[derive(PartialEq, Eq)]
16enum LuaCommentType {
17 SingleLine,
18 MultiLineStart,
19 MultiLineEnd,
20 None,
21}
22
23impl Lua {
24 pub fn with_finder(finder: Finder) -> Self {
25 Self { _finder: finder }
26 }
27
28 pub fn find(&self, path: PathBuf) -> Result<FindResult, Error> {
29 let mut counter = 1; let mut comments = Vec::<(u32, String)>::new();
31 let mut in_multiline = false;
32
33 let file = File::open(&path)?;
34 let file_name = file_name(&path)?;
35
36 for line in BufReader::new(file).lines() {
37 match line {
38 Ok(l) => {
39 let comment_type = self.get_comment_type(&l);
40 if in_multiline {
41 comments.push((counter, l.to_string()));
43 in_multiline = comment_type != LuaCommentType::MultiLineEnd;
44 } else {
45 match self.get_comment_type(&l) {
46 LuaCommentType::SingleLine => comments.push((counter, l.to_string())),
47 LuaCommentType::MultiLineStart => {
48 in_multiline = true;
49 comments.push((counter, l.to_string()));
50 }
51 _ => (),
52 }
53 }
54 }
55 Err(_) => panic!("Could not read line"),
56 }
57 counter += 1;
58 }
59
60 Ok(FindResult {
61 file_name: file_name.to_string(),
62 lines: comments,
63 ..Default::default()
64 })
65 }
66
67 fn get_comment_type(&self, line: &str) -> LuaCommentType {
68 if contains_all(line, vec!["--[[", "]]"]) {
69 return LuaCommentType::SingleLine;
70 }
71
72 if contains_any_of(line, vec!["]]"]) {
73 return LuaCommentType::MultiLineEnd;
74 }
75
76 if contains_any_of(line, vec!["--[["]) {
77 return LuaCommentType::MultiLineStart;
78 }
79
80 if contains_any_of(line, vec!["--"]) {
81 return LuaCommentType::SingleLine;
82 }
83
84 LuaCommentType::None
85 }
86}