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
|
use crate::interactive::{app_test::FIXTURE_PATH, Interaction, TerminalApp};
use anyhow::{Context, Error, Result};
use dua::{
traverse::{EntryData, Tree, TreeIndex},
ByteFormat, Color, TraversalSorting, WalkOptions,
};
use itertools::Itertools;
use jwalk::{DirEntry, WalkDir};
use petgraph::prelude::NodeIndex;
use std::{
env::temp_dir,
ffi::OsStr,
fmt,
fs::{copy, create_dir_all, remove_dir, remove_file},
io::ErrorKind,
path::{Path, PathBuf},
};
use tui::backend::TestBackend;
use tui_react::Terminal;
pub fn adapt(
keys: impl Iterator<Item = std::io::Result<termion::event::Key>>,
) -> impl Iterator<Item = crosstermion::input::Key> {
use std::convert::TryFrom;
keys.filter_map(Result::ok)
.filter_map(|k| crosstermion::input::Key::try_from(k).ok())
}
pub fn node_by_index(app: &TerminalApp, id: TreeIndex) -> &EntryData {
app.traversal.tree.node_weight(id).unwrap()
}
pub fn node_by_name(app: &TerminalApp, name: impl AsRef<OsStr>) -> &EntryData {
node_by_index(app, index_by_name(&app, name))
}
pub fn index_by_name_and_size(
app: &TerminalApp,
name: impl AsRef<OsStr>,
size: Option<u128>,
) -> TreeIndex {
let name = name.as_ref();
let t: Vec<_> = app
.traversal
.tree
.node_indices()
.map(|idx| (idx, node_by_index(app, idx)))
.filter_map(|(idx, e)| {
if e.name == name && size.map(|s| s == e.size).unwrap_or(true) {
Some(idx)
} else {
None
}
})
.collect();
match t.len() {
1 => t[0],
0 => panic!("Node named '{}' not found in tree", name.to_string_lossy()),
n => panic!("Node named '{}' found {} times", name.to_string_lossy(), n),
}
}
pub fn index_by_name(app: &TerminalApp, name: impl AsRef<OsStr>) -> TreeIndex {
index_by_name_and_size(app, name, None)
}
pub struct WritableFixture {
pub root: PathBuf,
}
impl Drop for WritableFixture {
fn drop(&mut self) {
delete_recursive(&self.root).ok();
}
}
fn delete_recursive(path: impl AsRef<Path>) -> Result<()> {
let mut files: Vec<_> = Vec::new();
let mut dirs: Vec<_> = Vec::new();
for entry in WalkDir::new(&path)
.parallelism(jwalk::Parallelism::Serial)
.into_iter()
{
let entry: DirEntry<_> = entry?;
let p = entry.path();
match p.is_dir() {
true => dirs.push(p),
false => files.push(p),
}
}
files
.iter()
.map(|f| remove_file(f).map_err(Error::from))
.chain(
dirs.iter()
.sorted_by_key(|p| p.components().count())
.rev()
.map(|d| {
remove_dir(d)
.with_context(|| format!("Could not delete '{}'", d.display()))
.map_err(Error::from)
}),
)
.collect::<Result<_, _>>()
}
fn copy_recursive(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<(), Error> {
for entry in WalkDir::new(&src)
.parallelism(jwalk::Parallelism::Serial)
.into_iter()
{
let entry: DirEntry<_> = entry?;
let entry_path = entry.path();
entry_path
.strip_prefix(&src)
.map_err(Error::from)
.and_then(|relative_entry_path| {
let dst = dst.as_ref().join(relative_entry_path);
if entry_path.is_dir() {
create_dir_all(dst).map_err(Into::into)
} else {
copy(&entry_path, dst)
.map(|_| ())
.or_else(|e| match e.kind() {
ErrorKind::AlreadyExists => Ok(()),
_ => Err(e),
})
.map_err(Into::into)
}
})?;
}
Ok(())
}
impl From<&'static str> for WritableFixture {
fn from(fixture_name: &str) -> Self {
const TEMP_TLD_DIRNAME: &'static str = "dua-unit";
let src = fixture(fixture_name);
let dst = temp_dir().join(TEMP_TLD_DIRNAME);
create_dir_all(&dst).unwrap();
let dst = dst.join(fixture_name);
copy_recursive(src, &dst).unwrap();
WritableFixture { root: dst }
}
}
impl AsRef<Path> for WritableFixture {
fn as_ref(&self) -> &Path {
&self.root
}
}
pub fn fixture(p: impl AsRef<Path>) -> PathBuf {
Path::new(FIXTURE_PATH).join(p)
}
pub fn fixture_str(p: impl AsRef<Path>) -> String {
fixture(p).to_str().unwrap().to_owned()
}
pub fn initialized_app_and_terminal_with_closure<P: AsRef<Path>>(
fixture_paths: &[P],
mut convert: impl FnMut(&Path) -> PathBuf,
) -> Result<(Terminal<TestBackend>, TerminalApp), Error> {
let mut terminal = new_test_terminal()?;
std::env::set_current_dir(Path::new(env!("CARGO_MANIFEST_DIR")))?;
let input = fixture_paths.iter().map(|c| convert(c.as_ref())).collect();
let app = TerminalApp::initialize(
&mut terminal,
WalkOptions {
threads: 1,
byte_format: ByteFormat::Metric,
apparent_size: true,
count_hard_links: false,
color: Color::None,
sorting: TraversalSorting::AlphabeticalByFileName,
cross_filesystems: false,
},
input,
Interaction::None,
)?
.map(|(_, app)| app);
Ok((
terminal,
app.expect("app that didn't try to abort iteration"),
))
}
pub fn new_test_terminal() -> std::io::Result<Terminal<TestBackend>> {
Terminal::new(TestBackend::new(40, 20))
}
pub fn initialized_app_and_terminal_from_paths(
fixture_paths: &[PathBuf],
) -> Result<(Terminal<TestBackend>, TerminalApp), Error> {
fn to_path_buf(p: &Path) -> PathBuf {
p.to_path_buf()
}
initialized_app_and_terminal_with_closure(fixture_paths, to_path_buf)
}
pub fn initialized_app_and_terminal_from_fixture(
fixture_paths: &[&str],
) -> Result<(Terminal<TestBackend>, TerminalApp), Error> {
initialized_app_and_terminal_with_closure(fixture_paths, |p| fixture(p))
}
pub fn sample_01_tree() -> Tree {
let mut t = Tree::new();
{
let mut add_node = make_add_node(&mut t);
let root_size = 1259070;
let r = add_node("", root_size, None);
{
let s = add_node(&fixture_str("sample-01"), root_size, Some(r));
{
add_node(".hidden.666", 666, Some(s));
add_node("a", 256, Some(s));
add_node("b.empty", 0, Some(s));
add_node("c.lnk", 1, Some(s));
let d = add_node("dir"
|