basefmt 0.1.0

A formatter that applies universal formatting rules to any text file
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
use crate::config::Config;
use crate::editorconfig::{EditorConfigCache, FormatRules};
use crate::find::find_files;
use crate::format::{check_file_with_rules, format_file_with_rules, CheckResult};
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};

/// Result of a formatting or checking operation on multiple files.
pub struct RunnerResult {
    /// Total number of files processed
    pub total_files: usize,
    /// Number of files that encountered errors
    pub error_count: usize,
    /// Number of files that were not properly formatted (check mode only)
    pub unformatted_count: usize,
}

impl RunnerResult {
    /// Returns the appropriate exit code based on the result.
    ///
    /// Exit codes:
    /// - 0: Success (all files formatted/checked successfully)
    /// - 1: Some files need formatting (check mode only)
    /// - 2: Errors occurred during processing
    pub fn exit_code(&self) -> u8 {
        if self.error_count > 0 {
            2
        } else if self.unformatted_count > 0 {
            1
        } else {
            0
        }
    }
}

/// A file that needs to be formatted along with its formatting rules.
///
/// This structure pre-computes and caches the formatting rules for each file
/// to avoid redundant EditorConfig lookups during parallel processing.
struct FileTask {
    /// Original path to the file (may be relative or absolute)
    path: PathBuf,
    /// Cached formatting rules from EditorConfig
    rules: FormatRules,
}

/// Formats files in the specified paths in parallel.
///
/// Finds all files in the given paths and formats them concurrently using rayon.
/// Files are only modified if formatting changes are needed.
///
/// # Arguments
///
/// * `paths` - A slice of paths (files or directories) to format
///
/// # Returns
///
/// Returns a `RunnerResult` containing statistics about the operation, or an error
/// if file discovery fails.
///
/// # Examples
///
/// ```no_run
/// use basefmt::runner::run_format;
/// use std::path::Path;
///
/// let result = run_format(&[Path::new("src")]).unwrap();
/// println!("Formatted {} files", result.total_files);
/// ```
pub fn run_format(paths: &[impl AsRef<Path>]) -> io::Result<RunnerResult> {
    let config_dir = determine_config_dir(paths);
    let config = Config::load(config_dir).unwrap_or_default();
    let files = find_files(paths)?;
    let config_dir_abs = config_dir
        .canonicalize()
        .unwrap_or_else(|_| config_dir.to_path_buf());

    let mut rule_cache = EditorConfigCache::new();
    let filtered_files = collect_tasks(files, &config, &config_dir_abs, &mut rule_cache);

    let error_count = AtomicUsize::new(0);

    // Use parallel processing only for larger file counts to avoid overhead
    const PARALLEL_THRESHOLD: usize = 10;

    if filtered_files.len() < PARALLEL_THRESHOLD {
        for task in &filtered_files {
            if let Err(err) = format_file_with_rules(&task.path, &task.rules) {
                eprintln!("{}: {}", task.path.display(), err);
                error_count.fetch_add(1, Ordering::Relaxed);
            }
        }
    } else {
        filtered_files.par_iter().for_each(|task| {
            if let Err(err) = format_file_with_rules(&task.path, &task.rules) {
                eprintln!("{}: {}", task.path.display(), err);
                error_count.fetch_add(1, Ordering::Relaxed);
            }
        });
    }

    Ok(RunnerResult {
        total_files: filtered_files.len(),
        error_count: error_count.load(Ordering::Relaxed),
        unformatted_count: 0,
    })
}

/// Checks if files in the specified paths are properly formatted, in parallel.
///
/// Finds all files in the given paths and checks them concurrently using rayon.
/// Files are not modified; only checked for proper formatting.
///
/// # Arguments
///
/// * `paths` - A slice of paths (files or directories) to check
///
/// # Returns
///
/// Returns a `RunnerResult` containing statistics about the operation, including
/// the number of files that need formatting, or an error if file discovery fails.
///
/// # Examples
///
/// ```no_run
/// use basefmt::runner::run_check;
/// use std::path::Path;
///
/// let result = run_check(&[Path::new("src")]).unwrap();
/// if result.unformatted_count > 0 {
///     println!("{} files need formatting", result.unformatted_count);
/// }
/// ```
pub fn run_check(paths: &[impl AsRef<Path>]) -> io::Result<RunnerResult> {
    let config_dir = determine_config_dir(paths);
    let config = Config::load(config_dir).unwrap_or_default();
    let files = find_files(paths)?;
    let config_dir_abs = config_dir
        .canonicalize()
        .unwrap_or_else(|_| config_dir.to_path_buf());

    let mut rule_cache = EditorConfigCache::new();
    let filtered_files = collect_tasks(files, &config, &config_dir_abs, &mut rule_cache);

    let error_count = AtomicUsize::new(0);
    let unformatted_count = AtomicUsize::new(0);

    // Use parallel processing only for larger file counts to avoid overhead
    const PARALLEL_THRESHOLD: usize = 10;

    if filtered_files.len() < PARALLEL_THRESHOLD {
        for task in &filtered_files {
            match check_file_with_rules(&task.path, &task.rules) {
                Ok(CheckResult::Formatted | CheckResult::Skipped) => {}
                Ok(CheckResult::NeedsFormatting) => {
                    eprintln!("{}: not formatted", task.path.display());
                    unformatted_count.fetch_add(1, Ordering::Relaxed);
                }
                Err(err) => {
                    eprintln!("{}: {}", task.path.display(), err);
                    error_count.fetch_add(1, Ordering::Relaxed);
                }
            }
        }
    } else {
        filtered_files.par_iter().for_each(|task| {
            match check_file_with_rules(&task.path, &task.rules) {
                Ok(CheckResult::Formatted | CheckResult::Skipped) => {}
                Ok(CheckResult::NeedsFormatting) => {
                    eprintln!("{}: not formatted", task.path.display());
                    unformatted_count.fetch_add(1, Ordering::Relaxed);
                }
                Err(err) => {
                    eprintln!("{}: {}", task.path.display(), err);
                    error_count.fetch_add(1, Ordering::Relaxed);
                }
            }
        });
    }

    Ok(RunnerResult {
        total_files: filtered_files.len(),
        error_count: error_count.load(Ordering::Relaxed),
        unformatted_count: unformatted_count.load(Ordering::Relaxed),
    })
}

fn determine_config_dir(paths: &[impl AsRef<Path>]) -> &Path {
    if let Some(first_path) = paths.first() {
        let path = first_path.as_ref();
        if path.is_dir() {
            path
        } else {
            path.parent().unwrap_or_else(|| Path::new("."))
        }
    } else {
        Path::new(".")
    }
}

fn collect_tasks(
    files: Vec<PathBuf>,
    config: &Config,
    config_dir_abs: &Path,
    rule_cache: &mut EditorConfigCache,
) -> Vec<FileTask> {
    let mut tasks = Vec::with_capacity(files.len());
    for path in files {
        let canonical = match path.canonicalize() {
            Ok(abs) => abs,
            Err(err) => {
                eprintln!("{}: failed to canonicalize: {}", path.display(), err);
                continue;
            }
        };

        let rel_path = canonical
            .strip_prefix(config_dir_abs)
            .unwrap_or(canonical.as_path());

        if config.is_excluded(rel_path) {
            continue;
        }

        let rules = rule_cache.rules_for(&canonical);
        tasks.push(FileTask { path, rules });
    }
    tasks
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    // Helper function to create a .editorconfig file with all rules enabled
    fn create_default_editorconfig(dir: &TempDir) {
        let config_path = dir.path().join(".editorconfig");
        fs::write(
            config_path,
            r#"
root = true

[*]
insert_final_newline = true
trim_trailing_whitespace = true
trim_leading_newlines = true
"#,
        )
        .unwrap();
    }

    #[test]
    fn test_runner_result_exit_code_success() {
        let result = RunnerResult {
            total_files: 5,
            error_count: 0,
            unformatted_count: 0,
        };
        assert_eq!(result.exit_code(), 0);
    }

    #[test]
    fn test_runner_result_exit_code_unformatted() {
        let result = RunnerResult {
            total_files: 5,
            error_count: 0,
            unformatted_count: 2,
        };
        assert_eq!(result.exit_code(), 1);
    }

    #[test]
    fn test_runner_result_exit_code_error() {
        let result = RunnerResult {
            total_files: 5,
            error_count: 1,
            unformatted_count: 0,
        };
        assert_eq!(result.exit_code(), 2);
    }

    #[test]
    fn test_runner_result_exit_code_error_priority() {
        let result = RunnerResult {
            total_files: 5,
            error_count: 1,
            unformatted_count: 2,
        };
        // Errors have higher priority than unformatted
        assert_eq!(result.exit_code(), 2);
    }

    #[test]
    fn test_run_format_single_file() {
        let temp_dir = TempDir::new().unwrap();
        create_default_editorconfig(&temp_dir);
        let file = temp_dir.path().join("test.txt");
        fs::write(&file, "\n\ntest content  \n\n").unwrap();

        let result = run_format(&[&file]).unwrap();

        assert_eq!(result.total_files, 1);
        assert_eq!(result.error_count, 0);
        assert_eq!(result.unformatted_count, 0);
        assert_eq!(result.exit_code(), 0);

        let content = fs::read_to_string(&file).unwrap();
        assert_eq!(content, "test content\n");
    }

    #[test]
    fn test_run_format_multiple_files() {
        let temp_dir = TempDir::new().unwrap();
        create_default_editorconfig(&temp_dir);
        let file1 = temp_dir.path().join("file1.txt");
        let file2 = temp_dir.path().join("file2.txt");
        fs::write(&file1, "\n\ntest1  \n").unwrap();
        fs::write(&file2, "test2\n").unwrap();

        let result = run_format(&[temp_dir.path()]).unwrap();

        assert_eq!(result.total_files, 2);
        assert_eq!(result.error_count, 0);
        assert_eq!(result.exit_code(), 0);

        assert_eq!(fs::read_to_string(&file1).unwrap(), "test1\n");
        assert_eq!(fs::read_to_string(&file2).unwrap(), "test2\n");
    }

    #[test]
    fn test_run_format_directory() {
        let temp_dir = TempDir::new().unwrap();
        let file1 = temp_dir.path().join("file1.txt");
        let file2 = temp_dir.path().join("file2.txt");
        fs::write(&file1, "\n\ntest1\n").unwrap();
        fs::write(&file2, "test2  \n").unwrap();

        let result = run_format(&[temp_dir.path()]).unwrap();

        assert_eq!(result.total_files, 2);
        assert_eq!(result.error_count, 0);
        assert_eq!(result.exit_code(), 0);
    }

    #[test]
    fn test_run_format_nonexistent_path() {
        let result = run_format(&["/nonexistent/path"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_run_check_clean_files() {
        let temp_dir = TempDir::new().unwrap();
        create_default_editorconfig(&temp_dir);
        let file1 = temp_dir.path().join("file1.txt");
        let file2 = temp_dir.path().join("file2.txt");
        fs::write(&file1, "test1\n").unwrap();
        fs::write(&file2, "test2\n").unwrap();

        let result = run_check(&[temp_dir.path()]).unwrap();

        assert_eq!(result.total_files, 2);
        assert_eq!(result.error_count, 0);
        assert_eq!(result.unformatted_count, 0);
        assert_eq!(result.exit_code(), 0);
    }

    #[test]
    fn test_run_check_unformatted_files() {
        let temp_dir = TempDir::new().unwrap();
        create_default_editorconfig(&temp_dir);
        let file1 = temp_dir.path().join("file1.txt");
        let file2 = temp_dir.path().join("file2.txt");
        fs::write(&file1, "\n\ntest1\n").unwrap();
        fs::write(&file2, "test2  \n").unwrap();

        let result = run_check(&[temp_dir.path()]).unwrap();

        assert_eq!(result.total_files, 2);
        assert_eq!(result.error_count, 0);
        assert_eq!(result.unformatted_count, 2);
        assert_eq!(result.exit_code(), 1);
    }

    #[test]
    fn test_run_check_mixed_files() {
        let temp_dir = TempDir::new().unwrap();
        create_default_editorconfig(&temp_dir);
        let file1 = temp_dir.path().join("file1.txt");
        let file2 = temp_dir.path().join("file2.txt");
        fs::write(&file1, "test1\n").unwrap();
        fs::write(&file2, "\n\ntest2\n").unwrap();

        let result = run_check(&[temp_dir.path()]).unwrap();

        assert_eq!(result.total_files, 2);
        assert_eq!(result.error_count, 0);
        assert_eq!(result.unformatted_count, 1);
        assert_eq!(result.exit_code(), 1);
    }

    #[test]
    fn test_run_check_nonexistent_path() {
        let result = run_check(&["/nonexistent/path"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_run_check_does_not_modify_files() {
        let temp_dir = TempDir::new().unwrap();
        let file = temp_dir.path().join("test.txt");
        let original = "\n\ntest content  \n\n";
        fs::write(&file, original).unwrap();

        let _result = run_check(&[&file]).unwrap();

        let content = fs::read_to_string(&file).unwrap();
        assert_eq!(content, original);
    }
}