/
display.rs
640 lines (571 loc) · 19.7 KB
/
display.rs
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
use crate::color::{ColoredString, Colors, Elem};
use crate::flags::{Block, Display, Flags, Layout};
use crate::icon::Icons;
use crate::meta::name::DisplayOption;
use crate::meta::{FileType, Meta};
use ansi_term::{ANSIString, ANSIStrings};
use std::collections::HashMap;
use term_grid::{Cell, Direction, Filling, Grid, GridOptions};
use terminal_size::terminal_size;
use unicode_width::UnicodeWidthStr;
const EDGE: &str = "\u{251c}\u{2500}\u{2500}"; // "├──"
const LINE: &str = "\u{2502} "; // "│ "
const CORNER: &str = "\u{2514}\u{2500}\u{2500}"; // "└──"
const BLANK: &str = " ";
pub fn grid(metas: &[Meta], flags: &Flags, colors: &Colors, icons: &Icons) -> String {
let term_width = match terminal_size() {
Some((w, _)) => Some(w.0 as usize),
None => None,
};
inner_display_grid(
&DisplayOption::None,
metas,
&flags,
colors,
icons,
0,
term_width,
)
}
pub fn tree(metas: &[Meta], flags: &Flags, colors: &Colors, icons: &Icons) -> String {
let mut grid = Grid::new(GridOptions {
filling: Filling::Spaces(1),
direction: Direction::LeftToRight,
});
let padding_rules = get_padding_rules(&metas, flags);
let mut index = 0;
for (i, block) in flags.blocks.0.iter().enumerate() {
if let Block::Name = block {
index = i;
}
}
for cell in inner_display_tree(metas, &flags, colors, icons, (0, ""), &padding_rules, index) {
grid.add(cell);
}
grid.fit_into_columns(flags.blocks.0.len()).to_string()
}
fn inner_display_grid(
display_option: &DisplayOption,
metas: &[Meta],
flags: &Flags,
colors: &Colors,
icons: &Icons,
depth: usize,
term_width: Option<usize>,
) -> String {
let mut output = String::new();
let padding_rules = get_padding_rules(&metas, flags);
let mut grid = match flags.layout {
Layout::OneLine => Grid::new(GridOptions {
filling: Filling::Spaces(1),
direction: Direction::LeftToRight,
}),
_ => Grid::new(GridOptions {
filling: Filling::Spaces(2),
direction: Direction::TopToBottom,
}),
};
// The first iteration (depth == 0) corresponds to the inputs given by the
// user. We defer displaying directories given by the user unless we've been
// asked to display the directory itself (rather than its contents).
let skip_dirs = (depth == 0) && (flags.display != Display::DirectoryOnly);
// print the files first.
for meta in metas {
// Maybe skip showing the directory meta now; show its contents later.
if skip_dirs
&& (matches!(meta.file_type, FileType::Directory{..})
|| (matches!(meta.file_type, FileType::SymLink { is_dir: true })
&& flags.layout != Layout::OneLine))
{
continue;
}
let blocks = get_output(
&meta,
&colors,
&icons,
&flags,
&display_option,
&padding_rules,
(0, ""),
);
for block in blocks {
let block_str = block.to_string();
grid.add(Cell {
width: get_visible_width(&block_str),
contents: block_str,
});
}
}
if flags.layout == Layout::Grid {
if let Some(tw) = term_width {
if let Some(gridded_output) = grid.fit_into_width(tw) {
output += &gridded_output.to_string();
} else {
//does not fit into grid, usually because (some) filename(s)
//are longer or almost as long as term_width
//print line by line instead!
output += &grid.fit_into_columns(1).to_string();
}
} else {
output += &grid.fit_into_columns(1).to_string();
}
} else {
output += &grid.fit_into_columns(flags.blocks.0.len()).to_string();
}
let should_display_folder_path = should_display_folder_path(depth, &metas, &flags);
// print the folder content
for meta in metas {
if meta.content.is_some() {
if should_display_folder_path {
output += &display_folder_path(&meta);
}
let display_option = DisplayOption::Relative {
base_path: &meta.path,
};
output += &inner_display_grid(
&display_option,
meta.content.as_ref().unwrap(),
&flags,
colors,
icons,
depth + 1,
term_width,
);
}
}
output
}
fn inner_display_tree(
metas: &[Meta],
flags: &Flags,
colors: &Colors,
icons: &Icons,
tree_depth_prefix: (usize, &str),
padding_rules: &HashMap<Block, usize>,
target_index: usize,
) -> Vec<Cell> {
let mut cells = Vec::new();
let last_idx = metas.len();
for (idx, meta) in metas.iter().enumerate() {
let current_prefix = if tree_depth_prefix.0 > 0 {
if idx + 1 != last_idx {
// is last folder elem
format!("{}{} ", tree_depth_prefix.1, EDGE)
} else {
format!("{}{} ", tree_depth_prefix.1, CORNER)
}
} else {
tree_depth_prefix.1.to_string()
};
for block in get_output(
&meta,
&colors,
&icons,
&flags,
&DisplayOption::FileName,
&padding_rules,
(target_index, ¤t_prefix),
) {
let block_str = block.to_string();
cells.push(Cell {
width: get_visible_width(&block_str),
contents: block_str,
});
}
if meta.content.is_some() {
let new_prefix = if tree_depth_prefix.0 > 0 {
if idx + 1 != last_idx {
// is last folder elem
format!("{}{}", tree_depth_prefix.1, LINE)
} else {
format!("{}{}", tree_depth_prefix.1, BLANK)
}
} else {
tree_depth_prefix.1.to_string()
};
cells.extend(inner_display_tree(
&meta.content.as_ref().unwrap(),
&flags,
colors,
icons,
(tree_depth_prefix.0 + 1, &new_prefix),
padding_rules,
target_index,
));
}
}
cells
}
fn should_display_folder_path(depth: usize, metas: &[Meta], flags: &Flags) -> bool {
if depth > 0 {
true
} else {
let folder_number = metas
.iter()
.filter(|x| {
matches!(x.file_type, FileType::Directory { .. })
|| (matches!(x.file_type, FileType::SymLink { is_dir: true })
&& flags.layout != Layout::OneLine)
})
.count();
folder_number > 1 || folder_number < metas.len()
}
}
fn display_folder_path(meta: &Meta) -> String {
let mut output = String::new();
output.push('\n');
output += &meta.path.to_string_lossy();
output += ":\n";
output
}
fn get_output<'a>(
meta: &'a Meta,
colors: &'a Colors,
icons: &'a Icons,
flags: &'a Flags,
display_option: &DisplayOption,
padding_rules: &HashMap<Block, usize>,
tree: (usize, &'a str),
) -> Vec<ANSIString<'a>> {
let mut strings: Vec<ANSIString> = Vec::new();
for (i, block) in flags.blocks.0.iter().enumerate() {
let mut block_vec = if Layout::Tree == flags.layout && tree.0 == i {
vec![colors.colorize(ANSIString::from(tree.1).to_string(), &Elem::TreeEdge)]
} else {
Vec::new()
};
match block {
Block::INode => block_vec.push(meta.inode.render(colors)),
Block::Links => block_vec.push(meta.links.render(colors)),
Block::Permission => {
block_vec.extend(vec![
meta.file_type.render(colors),
meta.permissions.render(colors),
]);
}
Block::User => block_vec.push(meta.owner.render_user(colors)),
Block::Group => block_vec.push(meta.owner.render_group(colors)),
Block::Size => {
let pad = if Layout::Tree == flags.layout && 0 == tree.0 && 0 == i {
None
} else {
Some(padding_rules[&Block::SizeValue])
};
block_vec.push(meta.size.render(colors, &flags, pad))
}
Block::SizeValue => block_vec.push(meta.size.render_value(colors, flags)),
Block::Date => block_vec.push(meta.date.render(colors, &flags)),
Block::Name => {
if flags.no_symlink.0 || flags.dereference.0 || flags.layout == Layout::Grid {
block_vec.extend(vec![
meta.name.render(colors, icons, &display_option),
meta.indicator.render(&flags),
])
} else {
block_vec.extend(vec![
meta.name.render(colors, icons, &display_option),
meta.indicator.render(&flags),
meta.symlink.render(colors, &flags),
])
};
}
};
strings.push(ColoredString::from(ANSIStrings(&block_vec).to_string()));
}
strings
}
fn get_visible_width(input: &str) -> usize {
let mut nb_invisible_char = 0;
// If the input has color, do not compute the length contributed by the color to the actual length
for (idx, _) in input.match_indices("\u{1b}[") {
let (_, s) = input.split_at(idx);
let m_pos = s.find('m');
if let Some(len) = m_pos {
nb_invisible_char += len
}
}
UnicodeWidthStr::width(input) - nb_invisible_char
}
fn detect_size_lengths(metas: &[Meta], flags: &Flags) -> usize {
let mut max_value_length: usize = 0;
for meta in metas {
let value_len = meta.size.value_string(flags).len();
if value_len > max_value_length {
max_value_length = value_len;
}
if Layout::Tree == flags.layout {
if let Some(subs) = &meta.content {
let sub_length = detect_size_lengths(&subs, flags);
if sub_length > max_value_length {
max_value_length = sub_length;
}
}
}
}
max_value_length
}
fn get_padding_rules(metas: &[Meta], flags: &Flags) -> HashMap<Block, usize> {
let mut padding_rules: HashMap<Block, usize> = HashMap::new();
if flags.blocks.0.contains(&Block::Size) {
let size_val = detect_size_lengths(&metas, &flags);
padding_rules.insert(Block::SizeValue, size_val);
}
padding_rules
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app;
use crate::color;
use crate::color::Colors;
use crate::icon;
use crate::icon::Icons;
use crate::meta::{FileType, Name};
use crate::Config;
use assert_fs::prelude::*;
use std::path::Path;
#[test]
fn test_display_get_visible_width_without_icons() {
for (s, l) in &[
("Hello,world!", 22),
("ASCII1234-_", 11),
("制作样本。", 10),
("日本語", 6),
("샘플은 무료로 드리겠습니다", 26),
("👩🐩", 4),
("🔬", 2),
] {
let path = Path::new(s);
let name = Name::new(
&path,
FileType::File {
exec: false,
uid: false,
},
);
let output = name.render(
&Colors::new(color::Theme::NoColor),
&Icons::new(icon::Theme::NoIcon, " ".to_string()),
&DisplayOption::FileName,
);
assert_eq!(get_visible_width(&output), *l);
}
}
#[test]
fn test_display_get_visible_width_with_icons() {
for (s, l) in &[
// Add 3 characters for the icons.
("Hello,world!", 24),
("ASCII1234-_", 13),
("File with space", 17),
("制作样本。", 12),
("日本語", 8),
("샘플은 무료로 드리겠습니다", 28),
("👩🐩", 6),
("🔬", 4),
] {
let path = Path::new(s);
let name = Name::new(
&path,
FileType::File {
exec: false,
uid: false,
},
);
let output = name
.render(
&Colors::new(color::Theme::NoColor),
&Icons::new(icon::Theme::Fancy, " ".to_string()),
&DisplayOption::FileName,
)
.to_string();
assert_eq!(get_visible_width(&output), *l);
}
}
#[test]
fn test_display_get_visible_width_with_colors() {
for (s, l) in &[
("Hello,world!", 22),
("ASCII1234-_", 11),
("File with space", 15),
("制作样本。", 10),
("日本語", 6),
("샘플은 무료로 드리겠습니다", 26),
("👩🐩", 4),
("🔬", 2),
] {
let path = Path::new(s);
let name = Name::new(
&path,
FileType::File {
exec: false,
uid: false,
},
);
let output = name
.render(
&Colors::new(color::Theme::NoLscolors),
&Icons::new(icon::Theme::NoIcon, " ".to_string()),
&DisplayOption::FileName,
)
.to_string();
// check if the color is present.
assert_eq!(true, output.starts_with("\u{1b}[38;5;"));
assert_eq!(true, output.ends_with("[0m"));
assert_eq!(get_visible_width(&output), *l);
}
}
#[test]
fn test_display_get_visible_width_without_colors() {
for (s, l) in &[
("Hello,world!", 22),
("ASCII1234-_", 11),
("File with space", 15),
("制作样本。", 10),
("日本語", 6),
("샘플은 무료로 드리겠습니다", 26),
("👩🐩", 4),
("🔬", 2),
] {
let path = Path::new(s);
let name = Name::new(
&path,
FileType::File {
exec: false,
uid: false,
},
);
let output = name
.render(
&Colors::new(color::Theme::NoColor),
&Icons::new(icon::Theme::NoIcon, " ".to_string()),
&DisplayOption::FileName,
)
.to_string();
// check if the color is present.
assert_eq!(false, output.starts_with("\u{1b}[38;5;"));
assert_eq!(false, output.ends_with("[0m"));
assert_eq!(get_visible_width(&output), *l);
}
}
#[test]
fn test_display_tree_with_all() {
let argv = vec!["lsd", "--tree", "--all"];
let matches = app::build().get_matches_from_safe(argv).unwrap();
let flags = Flags::configure_from(&matches, &Config::with_none()).unwrap();
let dir = assert_fs::TempDir::new().unwrap();
dir.child("one.d").create_dir_all().unwrap();
dir.child("one.d/two").touch().unwrap();
dir.child("one.d/.hidden").touch().unwrap();
let metas = Meta::from_path(Path::new(dir.path()), false)
.unwrap()
.recurse_into(42, &flags)
.unwrap()
.unwrap();
let output = tree(
&metas,
&flags,
&Colors::new(color::Theme::NoColor),
&Icons::new(icon::Theme::NoIcon, " ".to_string()),
);
assert_eq!("one.d\n├── .hidden\n└── two\n", output);
}
/// Different level of folder may form a different width
/// we must make sure it is aligned in all level
///
/// dir has a bytes size
/// empty file has an empty size
/// `---blocks size,name` can help us for this case
#[test]
fn test_tree_align_subfolder() {
let argv = vec!["lsd", "--tree", "--blocks", "size,name"];
let matches = app::build().get_matches_from_safe(argv).unwrap();
let flags = Flags::configure_from(&matches, &Config::with_none()).unwrap();
let dir = assert_fs::TempDir::new().unwrap();
dir.child("dir").create_dir_all().unwrap();
dir.child("dir/file").touch().unwrap();
let metas = Meta::from_path(Path::new(dir.path()), false)
.unwrap()
.recurse_into(42, &flags)
.unwrap()
.unwrap();
let output = tree(
&metas,
&flags,
&Colors::new(color::Theme::NoColor),
&Icons::new(icon::Theme::NoIcon, " ".to_string()),
);
let length_before_b = |i| -> usize {
output
.lines()
.nth(i)
.unwrap()
.split(|c| c == 'K' || c == 'B')
.nth(0)
.unwrap()
.len()
};
assert_eq!(length_before_b(0), length_before_b(1));
assert_eq!(
output.lines().nth(0).unwrap().find("d"),
output.lines().nth(1).unwrap().find("└")
);
}
#[test]
#[cfg(unix)]
fn test_tree_size_first_without_name() {
let argv = vec!["lsd", "--tree", "--blocks", "size,permission"];
let matches = app::build().get_matches_from_safe(argv).unwrap();
let flags = Flags::configure_from(&matches, &Config::with_none()).unwrap();
let dir = assert_fs::TempDir::new().unwrap();
dir.child("dir").create_dir_all().unwrap();
dir.child("dir/file").touch().unwrap();
let metas = Meta::from_path(Path::new(dir.path()), false)
.unwrap()
.recurse_into(42, &flags)
.unwrap()
.unwrap();
let output = tree(
&metas,
&flags,
&Colors::new(color::Theme::NoColor),
&Icons::new(icon::Theme::NoIcon, " ".to_string()),
);
assert_eq!(output.lines().nth(1).unwrap().chars().nth(0).unwrap(), '└');
assert_eq!(
output
.lines()
.nth(0)
.unwrap()
.chars()
.position(|x| x == 'd'),
output
.lines()
.nth(1)
.unwrap()
.chars()
.position(|x| x == '.'),
);
}
#[test]
fn test_tree_edge_before_name() {
let argv = vec!["lsd", "--tree", "--long"];
let matches = app::build().get_matches_from_safe(argv).unwrap();
let flags = Flags::configure_from(&matches, &Config::with_none()).unwrap();
let dir = assert_fs::TempDir::new().unwrap();
dir.child("one.d").create_dir_all().unwrap();
dir.child("one.d/two").touch().unwrap();
let metas = Meta::from_path(Path::new(dir.path()), false)
.unwrap()
.recurse_into(42, &flags)
.unwrap()
.unwrap();
let output = tree(
&metas,
&flags,
&Colors::new(color::Theme::NoColor),
&Icons::new(icon::Theme::NoIcon, " ".to_string()),
);
assert!(output.ends_with("└── two\n"));
}
}