rust_sql_organizer/file_formatter/
mod.rs1use lazy_static::lazy_static;
2
3use crate::sql_file::SqlFile;
4use regex::Regex;
5
6type FileFormatterFunc = fn(&SqlFile) -> String;
7
8pub struct FileFormatters {
9 formatters: Vec<FileFormatterFunc>,
10}
11
12impl FileFormatters {
13 pub fn format(&self, sql_file: &SqlFile) -> String {
14 self.formatters
15 .iter()
16 .map(|&fmt| fmt(sql_file))
17 .collect::<Vec<String>>()
18 .join("\n")
19 }
20
21 #[cfg(test)]
22 pub fn test_new(formatter: FileFormatterFunc) -> FileFormatters {
23 FileFormatters {
24 formatters: vec![formatter],
25 }
26 }
27}
28
29pub fn format_name(sql_file: &SqlFile) -> String {
30 format!("-- {}", sql_file.get_file_name())
31}
32
33pub fn format_split(_: &SqlFile) -> String {
34 "\n".to_string()
35}
36
37pub fn format_plain_text(sql_file: &SqlFile) -> String {
38 sql_file.get_sql_text().to_string()
39}
40
41pub fn format_no_comments(sql_file: &SqlFile) -> String {
42 REMOVE_COMMENTS_RE
43 .replace(sql_file.get_sql_text(), "USE")
44 .to_string()
45}
46
47pub fn format_endln(sql_file: &SqlFile) -> String {
48 format!(
49 "--____________________ End of {} ____________________--",
50 sql_file.get_file_name()
51 )
52}
53
54lazy_static! {
55 static ref REMOVE_COMMENTS_RE: Regex = Regex::new(r"(?mi)--\s+use").unwrap();
56 pub static ref STANDARD_FILE_FORMATTER: FileFormatters = FileFormatters {
57 formatters: vec![
58 format_name,
59 format_split,
60 format_split,
61 format_plain_text,
62 format_split,
63 format_split,
64 format_endln,
65 format_split
66 ]
67 };
68 pub static ref FILE_FORMATTER_NO_COMMENTS: FileFormatters = FileFormatters {
69 formatters: vec![
70 format_name,
71 format_split,
72 format_split,
73 format_no_comments,
74 format_split,
75 format_split,
76 format_endln,
77 format_split
78 ]
79 };
80}
81
82#[cfg(test)]
83mod test_file_formatter {
84 use crate::sql_file::SqlFile;
85
86 use super::{format_endln, format_name, format_no_comments, format_plain_text, format_split};
87
88 #[test]
89 fn test_format_name() {
90 assert_eq!(
91 format_name(&SqlFile::test_new("test", "SELECT 1;")),
92 "-- test"
93 )
94 }
95
96 #[test]
97 fn test_format_split() {
98 assert_eq!(format_split(&SqlFile::test_new("test", "SELECT 1;")), "\n")
99 }
100
101 #[test]
102 fn test_format_plain_text() {
103 assert_eq!(
104 format_plain_text(&SqlFile::test_new("test", "SELECT 1;")),
105 "SELECT 1;"
106 )
107 }
108
109 #[test]
110 fn test_format_no_comments() {
111 assert_eq!(
112 format_no_comments(&SqlFile::test_new(
113 "test",
114 "-- use ROLE ACCOUNTADMIN;\nSELECT 1;"
115 )),
116 "USE ROLE ACCOUNTADMIN;\nSELECT 1;"
117 )
118 }
119
120 #[test]
121 fn test_format_endln() {
122 assert_eq!(
123 format_endln(&SqlFile::test_new("test", "SELECT 1;")),
124 "--____________________ End of test ____________________--"
125 )
126 }
127}