Skip to content

Commit 7d8cf33

Browse files
Parallelize file formatting with Rayon
- Use `rayon::prelude::*` to iterate over `files_to_format` in parallel using `par_iter().for_each(...)`. - Use `std::sync::atomic::AtomicUsize` for thread-safe incrementing of `formatted_count`. - Add `rayon` as a dependency in `cli/Cargo.toml`. Co-authored-by: Tcode-Motion <188012755+Tcode-Motion@users.noreply.github.com>
1 parent 43c970d commit 7d8cf33

3 files changed

Lines changed: 12 additions & 8 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎cli/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ bincode = "1.3.3"
4242
dirs = "6.0"
4343
num_cpus = "1.15"
4444
ureq = { version = "2.9" }
45+
rayon = "1.10.0"
4546

4647
[build-dependencies]
4748
winres = "0.1.12"

‎cli/src/commands/fmt.rs‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
//! Formats TechScript source code files recursively in the specified path.
44
55
use crate::exit_code::ExitCode;
6+
use rayon::prelude::*;
67
use std::path::{Path, PathBuf};
8+
use std::sync::atomic::{AtomicUsize, Ordering};
79

810
pub fn execute(path_str: Option<&str>) -> ExitCode {
911
let current_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
@@ -41,11 +43,11 @@ pub fn execute(path_str: Option<&str>) -> ExitCode {
4143
files_to_format.push(target_path);
4244
}
4345

44-
let formatter = techscript_formatter::DocumentFormatter::new(4);
45-
let mut formatted_count = 0;
46+
let formatted_count = AtomicUsize::new(0);
4647

47-
for file in files_to_format {
48-
match std::fs::read_to_string(&file) {
48+
files_to_format.par_iter().for_each(|file| {
49+
let formatter = techscript_formatter::DocumentFormatter::new(4);
50+
match std::fs::read_to_string(file) {
4951
Ok(content) => {
5052
let formatted = formatter.format_source(&content);
5153
// In skeletal phase, if format_source returns empty, we just skip writing to avoid wiping out files.
@@ -55,20 +57,20 @@ pub fn execute(path_str: Option<&str>) -> ExitCode {
5557
&& !formatted.contains("<stmt>")
5658
&& !formatted.contains("<pat>")
5759
{
58-
if let Err(e) = std::fs::write(&file, formatted) {
60+
if let Err(e) = std::fs::write(file, formatted) {
5961
eprintln!("Error writing formatted file {:?}: {}", file, e);
6062
} else {
6163
println!("Formatted: {:?}", file);
62-
formatted_count += 1;
64+
formatted_count.fetch_add(1, Ordering::Relaxed);
6365
}
6466
}
6567
}
6668
Err(e) => {
6769
eprintln!("Error reading file {:?}: {}", file, e);
6870
}
6971
}
70-
}
72+
});
7173

72-
println!("Formatted {} files.", formatted_count);
74+
println!("Formatted {} files.", formatted_count.into_inner());
7375
ExitCode::Success
7476
}

0 commit comments

Comments
 (0)