cargo-quality 0.2.0

Professional Rust code quality analysis tool with hardcoded standards
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// SPDX-FileCopyrightText: 2025 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

//! Module for detecting and fixing `mod.rs` files.
//!
//! This module provides functionality to find `mod.rs` files in a project
//! and convert them to the modern module naming convention where modules
//! are named after their parent directory.
//!
//! # Example
//!
//! ```text
//! Before: src/analyzers/mod.rs
//! After:  src/analyzers.rs
//! ```
//!
//! The `mod.rs` file content is moved to a file named after the parent
//! directory, placed one level up in the directory hierarchy.

use std::{
    fs::{read_dir, remove_dir as remove_directory, rename},
    path::{Path, PathBuf}
};

use masterror::AppResult;

use crate::error::IoError;

/// Result of mod.rs detection.
///
/// Contains information about a found `mod.rs` file and the suggested fix.
#[derive(Debug, Clone)]
pub struct ModRsIssue {
    /// Path to the mod.rs file
    pub path:      PathBuf,
    /// Suggested new path after fix
    pub suggested: PathBuf,
    /// Human-readable message
    pub message:   String,
    /// Line number (always 1 for file-level issues)
    pub line:      usize,
    /// Column number (always 1 for file-level issues)
    pub column:    usize
}

/// Result of mod.rs analysis.
///
/// Contains all found `mod.rs` files in the analyzed path.
#[derive(Debug, Default)]
pub struct ModRsResult {
    /// List of found mod.rs issues
    pub issues: Vec<ModRsIssue>
}

impl ModRsResult {
    /// Creates new empty result.
    #[inline]
    pub fn new() -> Self {
        Self {
            issues: Vec::new()
        }
    }

    /// Returns total number of issues found.
    #[inline]
    pub fn len(&self) -> usize {
        self.issues.len()
    }

    /// Checks if no issues were found.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.issues.is_empty()
    }
}

/// Finds all `mod.rs` files in the given path.
///
/// Recursively searches for files named `mod.rs` that should be converted
/// to the modern module naming convention.
///
/// # Arguments
///
/// * `path` - Root path to search in
///
/// # Returns
///
/// `AppResult<ModRsResult>` containing all found `mod.rs` files
///
/// # Examples
///
/// ```no_run
/// use cargo_quality::mod_rs::find_mod_rs_issues;
///
/// let result = find_mod_rs_issues("src/").unwrap();
/// println!("Found {} mod.rs files", result.len());
/// ```
pub fn find_mod_rs_issues(path: &str) -> AppResult<ModRsResult> {
    let root = Path::new(path);
    let mut result = ModRsResult::new();

    if root.is_file() {
        if is_mod_rs(root)
            && let Some(issue) = create_issue(root)
        {
            result.issues.push(issue);
        }
        return Ok(result);
    }

    collect_mod_rs_recursive(root, &mut result)?;
    Ok(result)
}

/// Recursively collects mod.rs files from directory.
///
/// # Arguments
///
/// * `dir` - Directory to search in
/// * `result` - Result accumulator
fn collect_mod_rs_recursive(dir: &Path, result: &mut ModRsResult) -> AppResult<()> {
    let entries = read_dir(dir).map_err(IoError::from)?;

    for entry in entries {
        let entry = entry.map_err(IoError::from)?;
        let path = entry.path();

        if path.is_dir() {
            collect_mod_rs_recursive(&path, result)?;
        } else if is_mod_rs(&path)
            && let Some(issue) = create_issue(&path)
        {
            result.issues.push(issue);
        }
    }

    Ok(())
}

/// Checks if path points to a mod.rs file.
///
/// # Arguments
///
/// * `path` - Path to check
///
/// # Returns
///
/// `true` if the file is named `mod.rs`
#[inline]
fn is_mod_rs(path: &Path) -> bool {
    path.file_name()
        .and_then(|n| n.to_str())
        .map(|n| n == "mod.rs")
        .unwrap_or(false)
}

/// Creates an issue for a mod.rs file.
///
/// # Arguments
///
/// * `path` - Path to the mod.rs file
///
/// # Returns
///
/// `Some(ModRsIssue)` if the file has a valid parent directory
fn create_issue(path: &Path) -> Option<ModRsIssue> {
    let parent = path.parent()?;
    let module_name = parent.file_name()?.to_str()?;
    let grandparent = parent.parent()?;

    let suggested = grandparent.join(format!("{}.rs", module_name));

    Some(ModRsIssue {
        path: path.to_path_buf(),
        suggested,
        message: format!(
            "Use `{}.rs` instead of `{}/mod.rs` (modern module style)",
            module_name, module_name
        ),
        line: 1,
        column: 1
    })
}

/// Fixes a single mod.rs file by renaming and moving it.
///
/// Converts `src/foo/mod.rs` to `src/foo.rs` by:
/// 1. Reading the content of mod.rs
/// 2. Writing it to the new location (parent_name.rs)
/// 3. Removing the original mod.rs file
/// 4. Removing the empty parent directory if it becomes empty
///
/// # Arguments
///
/// * `issue` - The mod.rs issue to fix
///
/// # Returns
///
/// `AppResult<()>` - Ok if fix was successful
///
/// # Examples
///
/// ```no_run
/// use cargo_quality::mod_rs::{find_mod_rs_issues, fix_mod_rs};
///
/// let result = find_mod_rs_issues("src/").unwrap();
/// for issue in result.issues {
///     fix_mod_rs(&issue).unwrap();
/// }
/// ```
pub fn fix_mod_rs(issue: &ModRsIssue) -> AppResult<()> {
    rename(&issue.path, &issue.suggested).map_err(IoError::from)?;
    if let Some(parent) = issue.path.parent()
        && is_directory_empty(parent)?
    {
        remove_directory(parent).map_err(IoError::from)?;
    }
    Ok(())
}

/// Fixes all mod.rs files found in the given path.
///
/// # Arguments
///
/// * `path` - Root path to search and fix
///
/// # Returns
///
/// `AppResult<usize>` - Number of files fixed
///
/// # Examples
///
/// ```no_run
/// use cargo_quality::mod_rs::fix_all_mod_rs;
///
/// let fixed = fix_all_mod_rs("src/").unwrap();
/// println!("Fixed {} mod.rs files", fixed);
/// ```
pub fn fix_all_mod_rs(path: &str) -> AppResult<usize> {
    let result = find_mod_rs_issues(path)?;
    let count = result.len();

    for issue in result.issues {
        fix_mod_rs(&issue)?;
    }

    Ok(count)
}

/// Checks if a directory is empty.
///
/// # Arguments
///
/// * `dir` - Directory path to check
///
/// # Returns
///
/// `AppResult<bool>` - true if directory has no entries
fn is_directory_empty(dir: &Path) -> AppResult<bool> {
    let mut entries = read_dir(dir).map_err(IoError::from)?;
    Ok(entries.next().is_none())
}

#[cfg(test)]
mod tests {
    use std::fs::{create_dir, read_to_string, write};

    use tempfile::TempDir;

    use super::*;

    #[test]
    fn test_find_no_mod_rs() {
        let temp = TempDir::new().unwrap();
        let file = temp.path().join("lib.rs");
        write(&file, "fn main() {}").unwrap();

        let result = find_mod_rs_issues(temp.path().to_str().unwrap()).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_find_mod_rs() {
        let temp = TempDir::new().unwrap();
        let subdir = temp.path().join("analyzers");
        create_dir(&subdir).unwrap();
        let mod_rs = subdir.join("mod.rs");
        write(&mod_rs, "pub mod test;").unwrap();

        let result = find_mod_rs_issues(temp.path().to_str().unwrap()).unwrap();
        assert_eq!(result.len(), 1);
        assert!(result.issues[0].message.contains("analyzers"));
    }

    #[test]
    fn test_find_multiple_mod_rs() {
        let temp = TempDir::new().unwrap();

        let dir1 = temp.path().join("foo");
        create_dir(&dir1).unwrap();
        write(dir1.join("mod.rs"), "// foo").unwrap();

        let dir2 = temp.path().join("bar");
        create_dir(&dir2).unwrap();
        write(dir2.join("mod.rs"), "// bar").unwrap();

        let result = find_mod_rs_issues(temp.path().to_str().unwrap()).unwrap();
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_fix_mod_rs() {
        let temp = TempDir::new().unwrap();
        let subdir = temp.path().join("utils");
        create_dir(&subdir).unwrap();
        let mod_rs = subdir.join("mod.rs");
        write(&mod_rs, "pub fn helper() {}").unwrap();

        let result = find_mod_rs_issues(temp.path().to_str().unwrap()).unwrap();
        assert_eq!(result.len(), 1);

        fix_mod_rs(&result.issues[0]).unwrap();

        assert!(!mod_rs.exists());
        let new_file = temp.path().join("utils.rs");
        assert!(new_file.exists());
        assert_eq!(read_to_string(&new_file).unwrap(), "pub fn helper() {}");
        assert!(!subdir.exists());
    }

    #[test]
    fn test_fix_mod_rs_keeps_dir_with_other_files() {
        let temp = TempDir::new().unwrap();
        let subdir = temp.path().join("services");
        create_dir(&subdir).unwrap();
        write(subdir.join("mod.rs"), "pub mod api;").unwrap();
        write(subdir.join("api.rs"), "fn api() {}").unwrap();

        let result = find_mod_rs_issues(temp.path().to_str().unwrap()).unwrap();
        fix_mod_rs(&result.issues[0]).unwrap();

        assert!(subdir.exists());
        assert!(subdir.join("api.rs").exists());
        assert!(temp.path().join("services.rs").exists());
    }

    #[test]
    fn test_fix_all_mod_rs() {
        let temp = TempDir::new().unwrap();

        let dir1 = temp.path().join("module1");
        create_dir(&dir1).unwrap();
        write(dir1.join("mod.rs"), "// 1").unwrap();

        let dir2 = temp.path().join("module2");
        create_dir(&dir2).unwrap();
        write(dir2.join("mod.rs"), "// 2").unwrap();

        let fixed = fix_all_mod_rs(temp.path().to_str().unwrap()).unwrap();
        assert_eq!(fixed, 2);

        assert!(temp.path().join("module1.rs").exists());
        assert!(temp.path().join("module2.rs").exists());
    }

    #[test]
    fn test_issue_message() {
        let temp = TempDir::new().unwrap();
        let subdir = temp.path().join("handlers");
        create_dir(&subdir).unwrap();
        write(subdir.join("mod.rs"), "").unwrap();

        let result = find_mod_rs_issues(temp.path().to_str().unwrap()).unwrap();
        assert!(result.issues[0].message.contains("handlers.rs"));
        assert!(result.issues[0].message.contains("handlers/mod.rs"));
    }

    #[test]
    fn test_suggested_path() {
        let temp = TempDir::new().unwrap();
        let subdir = temp.path().join("core");
        create_dir(&subdir).unwrap();
        write(subdir.join("mod.rs"), "").unwrap();

        let result = find_mod_rs_issues(temp.path().to_str().unwrap()).unwrap();
        assert_eq!(result.issues[0].suggested, temp.path().join("core.rs"));
    }

    #[test]
    fn test_nested_mod_rs() {
        let temp = TempDir::new().unwrap();
        let level1 = temp.path().join("level1");
        let level2 = level1.join("level2");
        create_dir(&level1).unwrap();
        create_dir(&level2).unwrap();
        write(level2.join("mod.rs"), "// nested").unwrap();

        let result = find_mod_rs_issues(temp.path().to_str().unwrap()).unwrap();
        assert_eq!(result.len(), 1);
        assert!(result.issues[0].message.contains("level2"));
        assert_eq!(result.issues[0].suggested, level1.join("level2.rs"));
    }

    #[test]
    fn test_single_file_check() {
        let temp = TempDir::new().unwrap();
        let subdir = temp.path().join("single");
        create_dir(&subdir).unwrap();
        let mod_rs = subdir.join("mod.rs");
        write(&mod_rs, "").unwrap();

        let result = find_mod_rs_issues(mod_rs.to_str().unwrap()).unwrap();
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_non_mod_rs_file() {
        let temp = TempDir::new().unwrap();
        let file = temp.path().join("lib.rs");
        write(&file, "fn main() {}").unwrap();

        let result = find_mod_rs_issues(file.to_str().unwrap()).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_line_column() {
        let temp = TempDir::new().unwrap();
        let subdir = temp.path().join("pos");
        create_dir(&subdir).unwrap();
        write(subdir.join("mod.rs"), "").unwrap();

        let result = find_mod_rs_issues(temp.path().to_str().unwrap()).unwrap();
        assert_eq!(result.issues[0].line, 1);
        assert_eq!(result.issues[0].column, 1);
    }

    #[test]
    fn test_empty_directory() {
        let temp = TempDir::new().unwrap();
        let result = find_mod_rs_issues(temp.path().to_str().unwrap()).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_result_default() {
        let result = ModRsResult::default();
        assert!(result.is_empty());
        assert_eq!(result.len(), 0);
    }
}