rustqual 0.5.4

Comprehensive Rust code quality analyzer — six dimensions: Complexity, Coupling, DRY, IOSP, SRP, Test Quality
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use std::collections::HashSet;
use std::path::{Path, PathBuf};

use walkdir::WalkDir;

use crate::config::Config;
use crate::findings::{parse_suppression, Suppression};

/// Collect Rust source files from a path (file or directory).
/// Operation: file system logic with filtering.
pub(crate) fn collect_rust_files(path: &Path) -> Vec<PathBuf> {
    if path.is_file() {
        if path.extension().is_some_and(|ext| ext == "rs") {
            return vec![path.to_path_buf()];
        } else {
            eprintln!("Warning: {} is not a Rust file", path.display());
            return vec![];
        }
    }

    WalkDir::new(path)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path().extension().is_some_and(|ext| ext == "rs")
                && !e.path().components().any(|c| {
                    let s = c.as_os_str().to_string_lossy();
                    s == "target" || (s.starts_with('.') && s != "." && s != "..")
                })
        })
        .map(|e| e.into_path())
        .collect()
}

/// Collect and filter Rust files for analysis.
/// Trivial: iterator chain with lenient closures.
pub(crate) fn collect_filtered_files(path: &Path, config: &Config) -> Vec<PathBuf> {
    collect_rust_files(path)
        .into_iter()
        .filter(|f| {
            let rel = f
                .strip_prefix(path)
                .unwrap_or(f)
                .to_string_lossy()
                .replace('\\', "/");
            !config.is_excluded_file(&rel)
        })
        .collect()
}

/// Read and parse all Rust files, returning parsed syntax trees with source.
/// Operation: parallel file reading with error handling logic.
pub(crate) fn read_and_parse_files(
    files: &[PathBuf],
    base_path: &Path,
) -> Vec<(String, String, syn::File)> {
    let file_contents: Vec<(String, String)> = {
        use rayon::prelude::*;
        files
            .par_iter()
            .filter_map(|file_path| {
                let source = match std::fs::read_to_string(file_path) {
                    Ok(s) => s,
                    Err(e) => {
                        eprintln!("Warning: Could not read {}: {e}", file_path.display());
                        return None;
                    }
                };
                let display_path = file_path
                    .strip_prefix(base_path)
                    .unwrap_or(file_path)
                    .to_string_lossy()
                    .replace('\\', "/");
                Some((display_path, source))
            })
            .collect()
    };

    file_contents
        .into_iter()
        .filter_map(|(path, source)| match syn::parse_file(&source) {
            Ok(syntax) => Some((path, source, syntax)),
            Err(e) => {
                eprintln!("Warning: Could not parse {path}: {e}");
                None
            }
        })
        .collect()
}

/// Get Rust files changed vs a git ref.
/// Operation: shells out to git and parses output.
pub(crate) fn get_git_changed_files(path: &Path, git_ref: &str) -> Result<Vec<PathBuf>, String> {
    let dir = if path.is_file() {
        path.parent().unwrap_or(path)
    } else {
        path
    };

    let root_output = std::process::Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(dir)
        .output()
        .map_err(|e| format!("Failed to run git: {e}"))?;
    if !root_output.status.success() {
        return Err("Not a git repository".into());
    }

    let git_root = PathBuf::from(String::from_utf8_lossy(&root_output.stdout).trim());

    let output = std::process::Command::new("git")
        .args([
            "diff",
            "--name-only",
            "--diff-filter=ACMR",
            git_ref,
            "--",
            "*.rs",
        ])
        .current_dir(&git_root)
        .output()
        .map_err(|e| format!("Failed to run git diff: {e}"))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("git diff failed: {}", stderr.trim()));
    }

    let files = String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter(|l| !l.is_empty())
        .map(|l| git_root.join(l))
        .collect();

    Ok(files)
}

/// Filter file list to only those present in the changed set.
/// Operation: set-intersection logic using canonical paths.
pub(crate) fn filter_to_changed(all: Vec<PathBuf>, changed: &[PathBuf]) -> Vec<PathBuf> {
    let changed_canonical: HashSet<PathBuf> = changed
        .iter()
        .filter_map(|c| std::fs::canonicalize(c).ok())
        .collect();

    all.into_iter()
        .filter(|f| {
            std::fs::canonicalize(f)
                .map(|c| changed_canonical.contains(&c))
                .unwrap_or(false)
        })
        .collect()
}

/// Scan source lines and collect per-file results via a closure.
/// Trivial: generic iteration infrastructure, no own calls.
fn collect_per_file<T, F>(
    parsed: &[(String, String, syn::File)],
    extract: F,
) -> std::collections::HashMap<String, Vec<T>>
where
    F: Fn(usize, &str) -> Option<T>,
{
    let mut result = std::collections::HashMap::new();
    for (path, source, _) in parsed {
        let items: Vec<T> = source
            .lines()
            .enumerate()
            .filter_map(|(i, line)| extract(i + 1, line.trim()))
            .collect();
        if !items.is_empty() {
            result.insert(path.clone(), items);
        }
    }
    result
}

/// Collect all suppression comment lines from source files.
/// Trivial: delegates to collect_per_file with parse_suppression.
pub(crate) fn collect_suppression_lines(
    parsed: &[(String, String, syn::File)],
) -> std::collections::HashMap<String, Vec<Suppression>> {
    collect_per_file(parsed, |line_num, trimmed| {
        parse_suppression(line_num, trimmed)
    })
}

/// Collect `// qual:api` marker line numbers per file.
/// Trivial: delegates to collect_per_file with is_api_marker.
pub(crate) fn collect_api_lines(
    parsed: &[(String, String, syn::File)],
) -> std::collections::HashMap<String, std::collections::HashSet<usize>> {
    collect_per_file(parsed, |line_num, trimmed| {
        crate::findings::is_api_marker(trimmed).then_some(line_num)
    })
    .into_iter()
    .map(|(k, v)| (k, v.into_iter().collect()))
    .collect()
}

/// Collect `// qual:allow(unsafe)` marker line numbers per file.
/// Trivial: delegates to collect_per_file with is_unsafe_allow_marker.
pub(crate) fn collect_unsafe_allow_lines(
    parsed: &[(String, String, syn::File)],
) -> std::collections::HashMap<String, std::collections::HashSet<usize>> {
    collect_per_file(parsed, |line_num, trimmed| {
        crate::findings::is_unsafe_allow_marker(trimmed).then_some(line_num)
    })
    .into_iter()
    .map(|(k, v)| (k, v.into_iter().collect()))
    .collect()
}

/// Collect `// qual:recursive` marker line numbers per file.
/// Trivial: delegates to collect_per_file with is_recursive_marker.
pub(crate) fn collect_recursive_lines(
    parsed: &[(String, String, syn::File)],
) -> std::collections::HashMap<String, std::collections::HashSet<usize>> {
    collect_per_file(parsed, |line_num, trimmed| {
        crate::findings::is_recursive_marker(trimmed).then_some(line_num)
    })
    .into_iter()
    .map(|(k, v)| (k, v.into_iter().collect()))
    .collect()
}

/// Collect `// qual:inverse(fn_name)` marker lines per file.
/// Trivial: delegates to collect_per_file with parse_inverse_marker.
pub(crate) fn collect_inverse_lines(
    parsed: &[(String, String, syn::File)],
) -> std::collections::HashMap<String, Vec<(usize, String)>> {
    collect_per_file(parsed, |line_num, trimmed| {
        crate::findings::parse_inverse_marker(trimmed).map(|name| (line_num, name))
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_filter_to_changed_matching() {
        let dir = tempfile::Builder::new()
            .prefix("rustqual_test_")
            .tempdir()
            .unwrap();
        let a = dir.path().join("a.rs");
        let b = dir.path().join("b.rs");
        let c = dir.path().join("c.rs");
        std::fs::write(&a, "").unwrap();
        std::fs::write(&b, "").unwrap();
        std::fs::write(&c, "").unwrap();

        let all = vec![a.clone(), b, c.clone()];
        let changed = vec![a, c];
        let result = filter_to_changed(all, &changed);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_filter_to_changed_none_matching() {
        let dir = tempfile::Builder::new()
            .prefix("rustqual_test_")
            .tempdir()
            .unwrap();
        let a = dir.path().join("a.rs");
        let d = dir.path().join("d.rs");
        std::fs::write(&a, "").unwrap();
        std::fs::write(&d, "").unwrap();

        let all = vec![a];
        let changed = vec![d];
        let result = filter_to_changed(all, &changed);
        assert!(result.is_empty());
    }

    #[test]
    fn test_filter_to_changed_empty_changed() {
        let dir = tempfile::Builder::new()
            .prefix("rustqual_test_")
            .tempdir()
            .unwrap();
        let a = dir.path().join("a.rs");
        std::fs::write(&a, "").unwrap();

        let all = vec![a];
        let changed: Vec<PathBuf> = vec![];
        let result = filter_to_changed(all, &changed);
        assert!(result.is_empty());
    }

    #[test]
    fn test_filter_to_changed_empty_all() {
        let all: Vec<PathBuf> = vec![];
        let changed: Vec<PathBuf> = vec![PathBuf::from("/tmp/x.rs")];
        let result = filter_to_changed(all, &changed);
        assert!(result.is_empty());
    }

    #[test]
    fn test_get_git_changed_files_not_git_repo() {
        let dir = tempfile::Builder::new()
            .prefix("rustqual_test_")
            .tempdir()
            .unwrap();
        let result = get_git_changed_files(dir.path(), "HEAD");
        assert!(result.is_err());
    }

    #[test]
    fn test_collect_rust_files_dot_prefix_path() {
        // Simulates `./src/` — the "." component should not be filtered as hidden
        let dir = tempfile::Builder::new()
            .prefix("rustqual_test_")
            .tempdir()
            .unwrap();
        let sub = dir.path().join("src");
        std::fs::create_dir_all(&sub).unwrap();
        std::fs::write(sub.join("main.rs"), "fn main() {}").unwrap();

        // Access via ./src by using the parent with a "." prefix
        let dot_path = dir.path().join(".");
        let dot_src = dot_path.join("src");
        let files = collect_rust_files(&dot_src);
        assert!(
            !files.is_empty(),
            "collect_rust_files should find files via ./src path"
        );
    }

    #[test]
    fn test_collect_rust_files_hidden_dir_excluded() {
        let dir = tempfile::Builder::new()
            .prefix("rustqual_test_")
            .tempdir()
            .unwrap();
        let hidden = dir.path().join(".hidden");
        std::fs::create_dir_all(&hidden).unwrap();
        std::fs::write(hidden.join("lib.rs"), "fn foo() {}").unwrap();
        // Also add a visible file
        std::fs::write(dir.path().join("main.rs"), "fn main() {}").unwrap();

        let files = collect_rust_files(dir.path());
        assert!(
            files
                .iter()
                .all(|f| !f.to_string_lossy().contains(".hidden")),
            "Hidden directories should be excluded"
        );
        assert!(!files.is_empty(), "Visible files should still be found");
    }

    #[test]
    fn test_collect_rust_files_target_dir_excluded() {
        let dir = tempfile::Builder::new()
            .prefix("rustqual_test_")
            .tempdir()
            .unwrap();
        let target = dir.path().join("target");
        std::fs::create_dir_all(&target).unwrap();
        std::fs::write(target.join("generated.rs"), "fn gen() {}").unwrap();
        std::fs::write(dir.path().join("lib.rs"), "fn lib() {}").unwrap();

        let files = collect_rust_files(dir.path());
        assert!(
            files
                .iter()
                .all(|f| !f.to_string_lossy().contains("target")),
            "target/ directory should be excluded"
        );
        assert!(!files.is_empty());
    }

    #[test]
    fn test_display_path_uses_forward_slashes() {
        let dir = tempfile::Builder::new()
            .prefix("rustqual_test_")
            .tempdir()
            .unwrap();
        let sub = dir.path().join("sub");
        std::fs::create_dir_all(&sub).unwrap();
        std::fs::write(sub.join("mod.rs"), "fn f() {}").unwrap();

        let parsed = read_and_parse_files(&collect_rust_files(dir.path()), dir.path());
        assert!(!parsed.is_empty());
        // Display path should use forward slashes, not backslashes
        assert!(
            !parsed[0].0.contains('\\'),
            "Display path should use forward slashes, got: {}",
            parsed[0].0
        );
    }

    #[test]
    fn test_collect_rust_files_dotdot_path() {
        // Simulates `../other/src` — the ".." component should not be filtered as hidden
        let dir = tempfile::Builder::new()
            .prefix("rustqual_test_")
            .tempdir()
            .unwrap();
        let sub = dir.path().join("sub");
        std::fs::create_dir_all(&sub).unwrap();
        std::fs::write(sub.join("lib.rs"), "fn f() {}").unwrap();

        // Access via parent/../sub
        let dotdot_path = dir.path().join("sub").join("..").join("sub");
        let files = collect_rust_files(&dotdot_path);
        assert!(
            !files.is_empty(),
            "collect_rust_files should find files via ../sub path"
        );
    }
}