-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreaddir.rs
More file actions
212 lines (192 loc) · 6.02 KB
/
readdir.rs
File metadata and controls
212 lines (192 loc) · 6.02 KB
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
use jwalk::{Parallelism, WalkDir};
use napi::bindgen_prelude::*;
use napi::Task;
use napi_derive::napi;
use std::fs;
use std::path::Path;
// # nodejs readdir jsdoc:
/**
* Reads the contents of a directory.
* @param {string | Buffer | URL} path
* @param {string | {
* encoding?: string;
* withFileTypes?: boolean;
* recursive?: boolean;
* }} [options]
* @param {(
* err?: Error,
* files?: string[] | Buffer[] | Dirent[]
* ) => any} callback
* @returns {void}
*/
#[napi(object)]
#[derive(Clone)]
pub struct ReaddirOptions {
pub skip_hidden: Option<bool>,
pub concurrency: Option<u32>,
pub recursive: Option<bool>,
pub with_file_types: Option<bool>,
}
#[napi(object)] // Similar to fs.Dirent
#[derive(Clone)]
pub struct Dirent {
pub name: String,
pub parent_path: String,
pub is_dir: bool,
}
// #[napi] // marco: expose the function to Node
/// Read directory entries from `path_str` according to the provided `options`.
///
/// The function performs a non-recursive or recursive directory listing based on `options.recursive`.
/// Hidden entries may be skipped when `options.skip_hidden` is true. When `options.with_file_types`
/// is true the results include `Dirent` objects with `name`, `parent_path`, and `is_dir`; otherwise
/// the results are plain file path strings (non-recursive: entry names; recursive: paths relative
/// to the provided root).
///
/// # Returns
///
/// `Ok(Either::A(Vec<String>))` with entry names or relative paths when `with_file_types` is false,
/// or `Ok(Either::B(Vec<Dirent>))` with `Dirent` objects when `with_file_types` is true. Returns
/// `Err` when the path does not exist or an underlying IO error occurs (error message contains
/// the underlying reason).
///
/// # Examples
///
/// ```
/// // Non-recursive list of names
/// let res = ls(".".to_string(), None).unwrap();
/// match res {
/// Either::A(names) => println!("names: {:?}", names),
/// Either::B(dirents) => println!("dirents: {:?}", dirents),
/// }
/// ```
fn ls(
path_str: String,
options: Option<ReaddirOptions>,
) -> Result<Either<Vec<String>, Vec<Dirent>>> {
let search_path_str = if path_str.is_empty() { "." } else { &path_str };
let path = Path::new(search_path_str);
if !Path::new(&path).exists() {
return Err(Error::from_reason(format!(
"ENOENT: no such file or directory, readdir '{}'",
path.to_string_lossy()
)));
}
let opts = options.unwrap_or(ReaddirOptions {
skip_hidden: Some(false),
concurrency: None,
recursive: Some(false),
with_file_types: Some(false),
});
let skip_hidden = opts.skip_hidden.unwrap_or(false);
let recursive = opts.recursive.unwrap_or(false);
let with_file_types = opts.with_file_types.unwrap_or(false);
if !recursive {
let parent_path_val = search_path_str.to_string();
let entries = fs::read_dir(path).map_err(|e| Error::from_reason(e.to_string()))?;
let mut result_files = if with_file_types {
None
} else {
Some(Vec::with_capacity(64))
};
let mut result_dirents = if with_file_types {
Some(Vec::with_capacity(64))
} else {
None
};
for entry in entries {
let entry = entry.map_err(|e| Error::from_reason(e.to_string()))?;
let file_name = entry.file_name();
let name_str = file_name.to_string_lossy();
if skip_hidden && name_str.starts_with('.') {
continue;
}
if let Some(ref mut list) = result_dirents {
list.push(Dirent {
name: name_str.to_string(),
parent_path: parent_path_val.clone(),
is_dir: entry.file_type().map(|t| t.is_dir()).unwrap_or(false),
});
} else if let Some(ref mut list) = result_files {
list.push(name_str.to_string());
}
}
if with_file_types {
return Ok(Either::B(result_dirents.unwrap()));
} else {
return Ok(Either::A(result_files.unwrap()));
}
}
let walk_dir = WalkDir::new(path)
.skip_hidden(skip_hidden)
.parallelism(match opts.concurrency {
Some(n) => Parallelism::RayonNewPool(n as usize),
None => Parallelism::RayonNewPool(0),
});
// TODO: maybe we'd better limit the max number of threads?
if with_file_types {
let result = walk_dir
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.depth() > 0)
.map(|e| {
let p = e.path();
let parent = p
.parent()
.unwrap_or(Path::new(""))
.to_string_lossy()
.to_string();
Dirent {
name: e.file_name().to_string_lossy().to_string(),
parent_path: parent,
is_dir: e.file_type().is_dir(),
}
})
.collect();
Ok(Either::B(result))
} else {
// When recursive is true and withFileTypes is false, Node.js returns relative paths.
// But jwalk entries have full paths, We need to strip the root path.
let root = path;
let result = walk_dir
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.depth() > 0)
.map(|e| {
// Get path relative to root
let p = e.path();
match p.strip_prefix(root) {
Ok(relative) => relative.to_string_lossy().to_string(),
Err(_) => e.file_name().to_string_lossy().to_string(), // Fallback
}
})
.collect();
Ok(Either::A(result))
}
}
#[napi(js_name = "readdirSync")]
pub fn readdir_sync(
path: String,
options: Option<ReaddirOptions>,
) -> Result<Either<Vec<String>, Vec<Dirent>>> {
ls(path, options)
}
// ========= async version =========
pub struct ReaddirTask {
pub path: String,
pub options: Option<ReaddirOptions>,
}
impl Task for ReaddirTask {
type Output = Either<Vec<String>, Vec<Dirent>>;
type JsValue = Either<Vec<String>, Vec<Dirent>>;
fn compute(&mut self) -> Result<Self::Output> {
ls(self.path.clone(), self.options.clone())
}
fn resolve(&mut self, _env: Env, output: Self::Output) -> Result<Self::JsValue> {
Ok(output)
}
}
#[napi(js_name = "readdir")]
pub fn readdir(path: String, options: Option<ReaddirOptions>) -> AsyncTask<ReaddirTask> {
AsyncTask::new(ReaddirTask { path, options })
}