|
3 | 3 | use clap::Parser;
|
4 | 4 | use log::{error, info, trace};
|
5 | 5 | 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 | +}; |
8 | 11 |
|
9 | 12 | enum ExitCode {
|
10 | 13 | Success,
|
@@ -86,20 +89,50 @@ fn format_files(files: Vec<PathBuf>, options: &Config) -> ExitCode {
|
86 | 89 | error!("Error: {} not found!", file.to_str().unwrap());
|
87 | 90 | return ExitCode::Failure;
|
88 | 91 | } 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); |
94 | 104 | }
|
95 |
| - |
96 |
| - info!("formatting file: {:?}", file); |
97 |
| - nu_formatter::format_single_file(file, options); |
98 | 105 | }
|
99 | 106 |
|
100 | 107 | ExitCode::Success
|
101 | 108 | }
|
102 | 109 |
|
| 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 | + |
103 | 136 | #[cfg(test)]
|
104 | 137 | mod tests {
|
105 | 138 | use super::*;
|
|
0 commit comments