Skip to content

Commit d2dba45

Browse files
authored
Format directory (#47)
## Description of changes <!-- What changes did you make --> Made nufmt format recursively. Run `nufmt .` ## Relevant Issues <!-- Eg. #43 --> #11
1 parent baccee1 commit d2dba45

File tree

1 file changed

+43
-10
lines changed

1 file changed

+43
-10
lines changed

Diff for: src/main.rs

+43-10
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@
33
use clap::Parser;
44
use log::{error, info, trace};
55
use nu_formatter::config::Config;
6-
use std::io::Write;
7-
use std::path::PathBuf;
6+
use std::{
7+
fs,
8+
io::Write,
9+
path::{Path, PathBuf},
10+
};
811

912
enum ExitCode {
1013
Success,
@@ -86,20 +89,50 @@ fn format_files(files: Vec<PathBuf>, options: &Config) -> ExitCode {
8689
error!("Error: {} not found!", file.to_str().unwrap());
8790
return ExitCode::Failure;
8891
} else if file.is_dir() {
89-
error!(
90-
"Error: {} is a directory. Please pass files only.",
91-
file.to_str().unwrap()
92-
);
93-
return ExitCode::Failure;
92+
for path in recurse_files(file).unwrap() {
93+
if is_file_extension(&path, ".nu") {
94+
info!("formatting file: {:?}", &path);
95+
nu_formatter::format_single_file(&path, options);
96+
} else {
97+
info!("not nu file: skipping");
98+
}
99+
}
100+
// Files only
101+
} else {
102+
info!("formatting file: {:?}", file);
103+
nu_formatter::format_single_file(file, options);
94104
}
95-
96-
info!("formatting file: {:?}", file);
97-
nu_formatter::format_single_file(file, options);
98105
}
99106

100107
ExitCode::Success
101108
}
102109

110+
fn recurse_files(path: impl AsRef<Path>) -> std::io::Result<Vec<PathBuf>> {
111+
let mut buf = vec![];
112+
let entries = fs::read_dir(path)?;
113+
114+
for entry in entries {
115+
let entry = entry?;
116+
let meta = entry.metadata()?;
117+
118+
if meta.is_dir() {
119+
let mut subdir = recurse_files(entry.path())?;
120+
buf.append(&mut subdir);
121+
}
122+
123+
if meta.is_file() {
124+
buf.push(entry.path());
125+
}
126+
}
127+
128+
Ok(buf)
129+
}
130+
131+
/// Get the file extension
132+
fn is_file_extension(file: &Path, extension: &str) -> bool {
133+
String::from(file.to_str().unwrap()).ends_with(extension)
134+
}
135+
103136
#[cfg(test)]
104137
mod tests {
105138
use super::*;

0 commit comments

Comments
 (0)