1use dictator_decree_abi::{BoxDecree, Decree, Diagnostic, Diagnostics, Span};
4use dictator_supreme::SupremeConfig;
5use memchr::memchr_iter;
6
7#[derive(Debug, Clone)]
9pub struct RubyConfig {
10 pub max_lines: usize,
11 pub ignore_comments: bool,
12}
13
14impl Default for RubyConfig {
15 fn default() -> Self {
16 Self {
17 max_lines: 300,
18 ignore_comments: false,
19 }
20 }
21}
22
23#[must_use]
25pub fn lint_source(source: &str) -> Diagnostics {
26 lint_source_with_configs(source, &RubyConfig::default(), &SupremeConfig::default())
27}
28
29#[must_use]
31pub fn lint_source_with_config(source: &str, config: &RubyConfig) -> Diagnostics {
32 let mut diags = Diagnostics::new();
33
34 diags.extend(dictator_supreme::lint_source_with_owner(
35 source,
36 &SupremeConfig::default(),
37 "ruby",
38 ));
39
40 diags.extend(lint_ruby_specific(source, config));
42
43 diags
44}
45
46#[must_use]
47pub fn lint_source_with_configs(
48 source: &str,
49 ruby_config: &RubyConfig,
50 supreme_config: &SupremeConfig,
51) -> Diagnostics {
52 let mut diags = Diagnostics::new();
53
54 let supreme_diags = dictator_supreme::lint_source_with_owner(source, supreme_config, "ruby");
55
56 if ruby_config.ignore_comments {
57 diags.extend(dictator_supreme::retain_long_line_diags(
58 source,
59 supreme_diags,
60 "ruby/line-too-long",
61 "#",
62 ));
63 } else {
64 diags.extend(supreme_diags);
65 }
66
67 diags.extend(lint_ruby_specific(source, ruby_config));
69
70 diags
71}
72
73fn lint_ruby_specific(source: &str, config: &RubyConfig) -> Diagnostics {
74 let mut diags = Diagnostics::new();
75
76 check_file_line_count(source, config.max_lines, &mut diags);
78
79 let bytes = source.as_bytes();
80 let mut line_start: usize = 0;
81 let mut line_idx: usize = 0;
82
83 for nl in memchr_iter(b'\n', bytes) {
84 process_line(source, line_start, nl, line_idx, &mut diags);
85 line_start = nl + 1;
86 line_idx += 1;
87 }
88
89 if line_start < bytes.len() {
90 process_line(source, line_start, bytes.len(), line_idx, &mut diags);
92 }
93
94 diags
95}
96
97fn check_file_line_count(source: &str, max_lines: usize, diags: &mut Diagnostics) {
99 let code_lines = dictator_supreme::count_code_lines(source, |trimmed| trimmed.starts_with('#'));
100
101 if code_lines > max_lines {
102 diags.push(Diagnostic {
103 rule: "ruby/file-too-long".to_string(),
104 message: format!("{code_lines} code lines (max {max_lines})"),
105 enforced: false,
106 span: Span::new(0, source.len().min(100)),
107 });
108 }
109}
110
111#[derive(Default)]
112pub struct RubyHygiene {
113 config: RubyConfig,
114 supreme: SupremeConfig,
115}
116
117impl RubyHygiene {
118 #[must_use]
119 pub const fn new(config: RubyConfig, supreme: SupremeConfig) -> Self {
120 Self { config, supreme }
121 }
122}
123
124impl Decree for RubyHygiene {
125 fn name(&self) -> &'static str {
126 "ruby"
127 }
128
129 fn lint(&self, _path: &str, source: &str) -> Diagnostics {
130 lint_source_with_configs(source, &self.config, &self.supreme)
131 }
132
133 fn metadata(&self) -> dictator_decree_abi::DecreeMetadata {
134 dictator_decree_abi::DecreeMetadata {
135 abi_version: dictator_decree_abi::ABI_VERSION.to_string(),
136 decree_version: env!("CARGO_PKG_VERSION").to_string(),
137 description: "Ruby code structure and hygiene".to_string(),
138 dectauthors: Some(env!("CARGO_PKG_AUTHORS").to_string()),
139 supported_extensions: vec!["rb".to_string(), "rake".to_string(), "gemspec".to_string()],
140 supported_filenames: vec![
141 "Gemfile".to_string(),
142 "Rakefile".to_string(),
143 "Guardfile".to_string(),
144 "Capfile".to_string(),
145 "Brewfile".to_string(),
146 "Dangerfile".to_string(),
147 "Podfile".to_string(),
148 "Fastfile".to_string(),
149 "Appfile".to_string(),
150 "Matchfile".to_string(),
151 "Berksfile".to_string(),
152 "Thorfile".to_string(),
153 "Vagrantfile".to_string(),
154 ".pryrc".to_string(),
155 ".irbrc".to_string(),
156 ],
157 skip_filenames: vec!["Gemfile.lock".to_string(), "Podfile.lock".to_string()],
158 capabilities: vec![dictator_decree_abi::Capability::Lint],
159 }
160 }
161}
162
163#[must_use]
165pub fn init_decree() -> BoxDecree {
166 Box::new(RubyHygiene::default())
167}
168
169#[must_use]
171pub fn init_decree_with_config(config: RubyConfig) -> BoxDecree {
172 Box::new(RubyHygiene::new(config, SupremeConfig::default()))
173}
174
175#[must_use]
177pub fn init_decree_with_configs(config: RubyConfig, supreme: SupremeConfig) -> BoxDecree {
178 Box::new(RubyHygiene::new(config, supreme))
179}
180
181#[must_use]
183pub fn config_from_decree_settings(settings: &dictator_core::DecreeSettings) -> RubyConfig {
184 RubyConfig {
185 max_lines: settings.max_lines.unwrap_or(300),
186 ignore_comments: settings.ignore_comments.unwrap_or(false),
187 }
188}
189
190fn process_line(source: &str, start: usize, end: usize, line_idx: usize, diags: &mut Diagnostics) {
191 let line = &source[start..end];
192
193 let trimmed = line.trim_start_matches(' ');
195 if let Some(stripped) = trimmed.strip_prefix('#')
196 && !is_comment_directive(stripped, line_idx)
197 && !stripped.starts_with(' ')
198 && !stripped.is_empty()
199 {
200 let hash_offset = start + (line.len() - trimmed.len());
202 diags.push(Diagnostic {
203 rule: "ruby/comment-space".to_string(),
204 message: "Comments should start with '# '".to_string(),
205 enforced: true,
206 span: Span::new(hash_offset, hash_offset + 1),
207 });
208 }
209}
210
211fn is_comment_directive(rest: &str, line_idx: usize) -> bool {
212 let rest = rest.trim_start();
213
214 rest.starts_with('!') || rest.starts_with("encoding")
216 || rest.starts_with("frozen_string_literal")
217 || rest.starts_with("rubocop")
218 || rest.starts_with("typed")
219 || (line_idx == 0 && rest.starts_with(" language"))
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 #[test]
227 fn detects_trailing_whitespace_and_tab() {
228 let src = "def foo\n bar \t\nend\n";
229 let diags = lint_source(src);
230 assert!(diags.iter().any(|d| d.rule == "ruby/trailing-whitespace"));
231 assert!(diags.iter().any(|d| d.rule == "ruby/tab-character"));
232 }
233
234 #[test]
235 fn detects_missing_final_newline() {
236 let src = "class Foo\nend";
237 let diags = lint_source(src);
238 assert!(diags.iter().any(|d| d.rule == "ruby/missing-final-newline"));
239 }
240
241 #[test]
242 fn enforces_comment_space() {
243 let src = "#bad\n# good\n";
244 let diags = lint_source(src);
245 assert!(diags.iter().any(|d| d.rule == "ruby/comment-space"));
246 }
247
248 #[test]
249 fn ignores_long_comment_lines_when_configured() {
250 let long_comment = format!("# {}\n", "x".repeat(150));
251 let src = format!("def foo\n{long_comment}end\n");
252 let config = RubyConfig {
253 ignore_comments: true,
254 ..Default::default()
255 };
256 let supreme = SupremeConfig {
257 max_line_length: Some(120),
258 ..Default::default()
259 };
260 let diags = lint_source_with_configs(&src, &config, &supreme);
261 assert!(!diags.iter().any(|d| d.rule == "ruby/line-too-long"));
262 }
263
264 #[test]
265 fn detects_long_comment_lines_when_not_configured() {
266 let long_comment = format!("# {}\n", "x".repeat(150));
267 let src = format!("def foo\n{long_comment}end\n");
268 let config = RubyConfig::default(); let supreme = SupremeConfig {
270 max_line_length: Some(120),
271 ..Default::default()
272 };
273 let diags = lint_source_with_configs(&src, &config, &supreme);
274 assert!(diags.iter().any(|d| d.rule == "ruby/line-too-long"));
275 }
276
277 #[test]
278 fn still_detects_long_code_lines_with_ignore_comments() {
279 let long_code = format!(" x = \"{}\"\n", "a".repeat(150));
280 let src = format!("def foo\n{long_code}end\n");
281 let config = RubyConfig {
282 ignore_comments: true,
283 ..Default::default()
284 };
285 let supreme = SupremeConfig {
286 max_line_length: Some(120),
287 ..Default::default()
288 };
289 let diags = lint_source_with_configs(&src, &config, &supreme);
290 assert!(diags.iter().any(|d| d.rule == "ruby/line-too-long"));
291 }
292
293 #[test]
294 fn detects_whitespace_only_blank_line() {
295 let src = "def foo\n bar\n \nend\n"; let diags = lint_source(src);
297 assert!(diags.iter().any(|d| d.rule == "ruby/blank-line-whitespace"));
298 }
299}