Enum broot::tree::Sort

source ·
pub enum Sort {
    None,
    Count,
    Date,
    Size,
    TypeDirsFirst,
    TypeDirsLast,
}
Expand description

A sort key. A non None sort mode implies only one level of the tree is displayed. When in None mode, paths are alpha sorted

Variants§

§

None

§

Count

§

Date

§

Size

§

TypeDirsFirst

§

TypeDirsLast

Implementations§

Examples found in repository?
src/tree_build/builder.rs (line 91)
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
    pub fn from(
        path: PathBuf,
        options: TreeOptions,
        targeted_size: usize,
        con: &'c AppContext,
    ) -> Result<TreeBuilder<'c>, TreeBuildError> {
        let mut blines = Arena::new();
        let mut git_ignorer = time!(GitIgnorer::default());
        let root_ignore_chain = git_ignorer.root_chain(&path);
        let line_status_computer = if options.filter_by_git_status || options.show_git_file_info {
            time!(
                "init line_status_computer",
                Repository::discover(&path)
                    .ok()
                    .and_then(LineStatusComputer::from),
            )
        } else {
            None
        };
        let root_id = BLine::from_root(&mut blines, path, root_ignore_chain, &options)?;
        let trim_root = match (options.trim_root, options.pattern.is_some(), options.sort.prevent_deep_display()) {
            // we never want to trim the root if there's a sort
            (_, _, true) => false,
            // if the user don't want root trimming, we don't trim
            (false, _, _) => false,
            // if there's a pattern, we try to show at least root matches
            (_, true, _) => false,
            // in other cases, as the user wants trimming, we trim
            _ => true,
        };
        Ok(TreeBuilder {
            options,
            targeted_size,
            blines,
            root_id,
            total_search: true, // we'll set it to false if we don't look at all children
            git_ignorer,
            line_status_computer,
            con,
            trim_root,
            matches_max: None,
            report: BuildReport::default(),
        })
    }

    /// Return a bline if the dir_entry directly matches the options and there's no error
    fn make_line(
        &mut self,
        parent_id: BId,
        e: &fs::DirEntry,
        depth: u16,
    ) -> Option<BLine> {
        let name = e.file_name();
        if name.is_empty() {
            self.report.error_count += 1;
            return None;
        }
        if !self.options.show_hidden && name.as_bytes()[0] == b'.' {
            self.report.hidden_count += 1;
            return None;
        }
        let name = name.to_string_lossy();
        let mut has_match = true;
        let mut score = 10000 - i32::from(depth); // we dope less deep entries
        let path = e.path();
        let file_type = match e.file_type() {
            Ok(ft) => ft,
            Err(_) => {
                self.report.error_count += 1;
                return None;
            }
        };
        let parent_subpath = &self.blines[parent_id].subpath;
        let subpath = if !parent_subpath.is_empty() {
            format!("{}/{}", parent_subpath, &name)
        } else {
            name.to_string()
        };
        let candidate = Candidate {
            name: &name,
            subpath: &subpath,
            path: &path,
            regular_file: file_type.is_file(),
        };
        let direct_match = if let Some(pattern_score) = self.options.pattern.pattern.score_of(candidate) {
            // we dope direct matches to compensate for depth doping of parent folders
            score += pattern_score + 10;
            true
        } else {
            has_match = false;
            false
        };
        let name = name.to_string();
        if has_match && self.options.filter_by_git_status {
            if let Some(line_status_computer) = &self.line_status_computer {
                if !line_status_computer.is_interesting(&path) {
                    has_match = false;
                }
            }
        }
        if file_type.is_file() {
            if !has_match {
                return None;
            }
            if self.options.only_folders {
                return None;
            }
        }
        let special_handling = self.con.special_paths.find(&path);
        if special_handling == SpecialHandling::Hide {
            return None;
        }
        if self.options.respect_git_ignore {
            let parent_chain = &self.blines[parent_id].git_ignore_chain;
            if !self
                .git_ignorer
                .accepts(parent_chain, &path, &name, file_type.is_dir())
            {
                return None;
            }
        };
        Some(BLine {
            parent_id: Some(parent_id),
            path,
            depth,
            subpath,
            name,
            file_type,
            children: None,
            next_child_idx: 0,
            has_error: false,
            has_match,
            direct_match,
            score,
            nb_kept_children: 0,
            git_ignore_chain: GitIgnoreChain::default(),
            special_handling,
        })
    }

    /// Return true when there are direct matches among children
    fn load_children(&mut self, bid: BId) -> bool {
        let mut has_child_match = false;
        match self.blines[bid].read_dir() {
            Ok(entries) => {
                let mut children: Vec<BId> = Vec::new();
                let child_depth = self.blines[bid].depth + 1;
                let mut lines = Vec::new();
                for e in entries.flatten() {
                    if let Some(line) = self.make_line(bid, &e, child_depth) {
                        lines.push(line);
                    }
                }
                for mut bl in lines {
                    if self.options.respect_git_ignore {
                        let parent_chain = &self.blines[bid].git_ignore_chain;
                        bl.git_ignore_chain = if bl.file_type.is_dir() {
                            self.git_ignorer.deeper_chain(parent_chain, &bl.path)
                        } else {
                            parent_chain.clone()
                        };
                    }
                    if bl.has_match {
                        self.blines[bid].has_match = true;
                        has_child_match = true;
                    }
                    let child_id = self.blines.alloc(bl);
                    children.push(child_id);
                }
                children.sort_by(|&a, &b| {
                    self.blines[a]
                        .name
                        .to_lowercase()
                        .cmp(&self.blines[b].name.to_lowercase())
                });
                self.blines[bid].children = Some(children);
            }
            Err(_err) => {
                self.blines[bid].has_error = true;
                self.blines[bid].children = Some(Vec::new());
            }
        }
        has_child_match
    }

    /// return the next child.
    /// load_children must have been called before on parent_id
    fn next_child(&mut self, parent_id: BId) -> Option<BId> {
        let bline = &mut self.blines[parent_id];
        if let Some(children) = &bline.children {
            if bline.next_child_idx < children.len() {
                let next_child = children[bline.next_child_idx];
                bline.next_child_idx += 1;
                Some(next_child)
            } else {
                Option::None
            }
        } else {
            unreachable!();
        }
    }

    /// first step of the build: we explore the directories and gather lines.
    /// If there's no search pattern we stop when we have enough lines to fill the screen.
    /// If there's a pattern, we try to gather more lines that will be sorted afterwards.
    fn gather_lines(&mut self, total_search: bool, dam: &Dam) -> Result<Vec<BId>, TreeBuildError> {
        let start = Instant::now();
        let mut out_blines: Vec<BId> = Vec::new(); // the blines we want to display
        let optimal_size = if self.options.pattern.pattern.has_real_scores() {
            10 * self.targeted_size
        } else {
            self.targeted_size
        };
        out_blines.push(self.root_id);
        let mut nb_lines_ok = 1; // in out_blines
        let mut open_dirs: VecDeque<BId> = VecDeque::new();
        let mut next_level_dirs: Vec<BId> = Vec::new();
        self.load_children(self.root_id);
        open_dirs.push_back(self.root_id);
        loop {
            if !total_search && (
                (nb_lines_ok > optimal_size)
                || (nb_lines_ok >= self.targeted_size && start.elapsed() > NOT_LONG)
            ) {
                self.total_search = false;
                break;
            }
            if let Some(max) = self.matches_max {
                if nb_lines_ok > max {
                    return Err(TreeBuildError::TooManyMatches{max});
                }
            }
            if let Some(open_dir_id) = open_dirs.pop_front() {
                if let Some(child_id) = self.next_child(open_dir_id) {
                    open_dirs.push_back(open_dir_id);
                    let child = &self.blines[child_id];
                    if child.has_match {
                        nb_lines_ok += 1;
                    }
                    if child.can_enter() {
                        next_level_dirs.push(child_id);
                    }
                    out_blines.push(child_id);
                }
            } else {
                // this depth is finished, we must go deeper
                if self.options.sort.prevent_deep_display() {
                    // in sort mode, only one level is displayed
                    break;
                }
                if next_level_dirs.is_empty() {
                    // except there's nothing deeper
                    break;
                }
                for next_level_dir_id in &next_level_dirs {
                    if dam.has_event() {
                        info!("task expired (core build - inner loop)");
                        return Err(TreeBuildError::Interrupted);
                    }
                    let has_child_match = self.load_children(*next_level_dir_id);
                    if has_child_match {
                        // we must ensure the ancestors are made Ok
                        let mut id = *next_level_dir_id;
                        loop {
                            let mut bline = &mut self.blines[id];
                            if !bline.has_match {
                                bline.has_match = true;
                                nb_lines_ok += 1;
                            }
                            if let Some(pid) = bline.parent_id {
                                id = pid;
                            } else {
                                break;
                            }
                        }
                    }
                    open_dirs.push_back(*next_level_dir_id);
                }
                next_level_dirs.clear();
            }
        }
        if let Some(max) = self.matches_max {
            if nb_lines_ok > max {
                return Err(TreeBuildError::TooManyMatches{max});
            }
        }
        if !self.trim_root {
            // if the root directory isn't totally read, we finished it even
            // it it goes past the bottom of the screen
            while let Some(child_id) = self.next_child(self.root_id) {
                out_blines.push(child_id);
            }
        }
        Ok(out_blines)
    }
More examples
Hide additional examples
src/display/displayable_tree.rs (line 575)
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
    pub fn write_on<W: Write>(&self, f: &mut W) -> Result<(), ProgramError> {
        #[cfg(not(any(target_family = "windows", target_os = "android")))]
        let perm_writer = super::PermWriter::for_tree(self.skin, self.tree);

        let tree = self.tree;
        let total_size = tree.total_sum();
        let scrollbar = if self.in_app {
            termimad::compute_scrollbar(
                tree.scroll,
                tree.lines.len() - 1, // the root line isn't scrolled
                self.area.height - 1, // the scrollbar doesn't cover the first line
                self.area.top + 1,
            )
        } else {
            None
        };
        if self.in_app {
            f.queue(cursor::MoveTo(self.area.left, self.area.top))?;
        }
        let mut cw = CropWriter::new(f, self.area.width as usize);
        let pattern_object = tree.options.pattern.pattern.object();
        self.write_root_line(&mut cw, self.in_app && tree.selection == 0)?;
        self.skin.queue_reset(f)?;

        let visible_cols: Vec<Col> = tree
            .options
            .cols_order
            .iter()
            .filter(|col| col.is_visible(tree, self.app_state))
            .cloned()
            .collect();

        // if necessary we compute the width of the count column
        let count_len = if tree.options.show_counts {
            tree.lines.iter()
                .skip(1) // we don't show the counts of the root
                .map(|l| l.sum.map_or(0, |s| s.to_count()))
                .max()
                .map(|c| format_count(c).len())
                .unwrap_or(0)
        } else {
            0
        };

        // we compute the length of the dates, depending on the format
        let date_len = if tree.options.show_dates {
            let date_time: DateTime<Local> = Local::now();
            date_time.format(tree.options.date_time_format).to_string().len()
        } else {
            0 // we don't care
        };

        for y in 1..self.area.height {
            if self.in_app {
                f.queue(cursor::MoveTo(self.area.left, y + self.area.top))?;
            } else {
                write!(f, "\r\n")?;
            }
            let mut line_index = y as usize;
            if line_index > 0 {
                line_index += tree.scroll as usize;
            }
            let mut selected = false;
            let mut cw = CropWriter::new(f, self.area.width as usize);
            let cw = &mut cw;
            if line_index < tree.lines.len() {
                let line = &tree.lines[line_index];
                selected = self.in_app && line_index == tree.selection;
                let label_style = self.label_style(line, selected);
                let mut in_branch = false;
                let space_style = if selected {
                    &self.skin.selected_line
                } else {
                    &self.skin.default
                };
                if visible_cols[0].needs_left_margin() {
                    cw.queue_char(space_style, ' ')?;
                }
                let staged = self.app_state
                    .map_or(false, |a| a.stage.contains(&line.path));
                for col in &visible_cols {
                    let void_len = match col {

                        Col::Mark => {
                            self.write_line_selection_mark(cw, &label_style, selected)?
                        }

                        Col::Git => {
                            self.write_line_git_status(cw, line, selected)?
                        }

                        Col::Branch => {
                            in_branch = true;
                            self.write_branch(cw, line_index, line, selected, staged)?
                        }

                        Col::DeviceId => {
                            #[cfg(not(unix))]
                            { 0 }

                            #[cfg(unix)]
                            self.write_line_device_id(cw, line, selected)?
                        }

                        Col::Permission => {
                            #[cfg(any(target_family = "windows", target_os = "android"))]
                            { 0 }

                            #[cfg(not(any(target_family = "windows", target_os = "android")))]
                            perm_writer.write_permissions(cw, line, selected)?
                        }

                        Col::Date => {
                            if let Some(seconds) = line.sum.and_then(|sum| sum.to_valid_seconds()) {
                                self.write_date(cw, seconds, selected)?
                            } else {
                                date_len + 1
                            }
                        }

                        Col::Size => {
                            if tree.options.sort.prevent_deep_display() {
                                // as soon as there's only one level displayed we can show the size bars
                                self.write_line_size_with_bar(cw, line, &label_style, total_size, selected)?
                            } else {
                                self.write_line_size(cw, line, &label_style, selected)?
                            }
                        }

                        Col::Count => {
                            self.write_line_count(cw, line, count_len, selected)?
                        }

                        Col::Staged => {
                            self.write_line_stage_mark(cw, &label_style, staged)?
                        }

                        Col::Name => {
                            in_branch = false;
                            self.write_line_label(cw, line, &label_style, pattern_object, selected)?
                        }

                    };
                    // void: intercol & replacing missing cells
                    if in_branch && void_len > 2 {
                        cond_bg!(void_style, self, selected, self.skin.tree);
                        cw.repeat(void_style, &BRANCH_FILLING, void_len)?;
                    } else {
                        cond_bg!(void_style, self, selected, self.skin.default);
                        cw.repeat(void_style, &SPACE_FILLING, void_len)?;
                    }
                }

                if cw.allowed > 8 && pattern_object.content {
                    let extract = tree.options.pattern.pattern
                        .search_content(&line.path, cw.allowed - 2);
                    if let Some(extract) = extract {
                        self.write_content_extract(cw, extract, selected)?;
                    }
                }
            }
            self.extend_line_bg(cw, selected)?;
            self.skin.queue_reset(f)?;
            if self.in_app {
                if let Some((sctop, scbottom)) = scrollbar {
                    f.queue(cursor::MoveTo(self.area.left + self.area.width - 1, y))?;
                    let style = if sctop <= y && y <= scbottom {
                        &self.skin.scrollbar_thumb
                    } else {
                        &self.skin.scrollbar_track
                    };
                    style.queue_str(f, "▐")?;
                }
            }
        }
        if !self.in_app {
            write!(f, "\r\n")?;
        }
        Ok(())
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.