Function broot::path::closest_dir

source ·
pub fn closest_dir(path: &Path) -> PathBuf
Expand description

return the closest enclosing directory

Examples found in repository?
src/verb/internal_focus.rs (line 45)
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
pub fn new_state_on_path(
    path: PathBuf,
    screen: Screen,
    tree_options: TreeOptions,
    con: &AppContext,
) -> CmdResult {
    let path = path::closest_dir(&path);
    CmdResult::from_optional_state(
        BrowserState::new(path, tree_options, screen, con, &Dam::unlimited()),
        None,
        false,
    )
}

pub fn new_panel_on_path(
    path: PathBuf,
    screen: Screen,
    tree_options: TreeOptions,
    purpose: PanelPurpose,
    con: &AppContext,
    direction: HDir,
) -> CmdResult {
    if purpose.is_preview() {
        let pattern = tree_options.pattern.tree_to_preview();
        CmdResult::NewPanel {
            state: Box::new(PreviewState::new(path, pattern, None, tree_options, con)),
            purpose,
            direction,
        }
    } else {
        let path = path::closest_dir(&path);
        match BrowserState::new(path, tree_options, screen, con, &Dam::unlimited()) {
            Ok(os) => CmdResult::NewPanel {
                state: Box::new(os),
                purpose,
                direction,
            },
            Err(e) => CmdResult::DisplayError(e.to_string()),
        }
    }
}
More examples
Hide additional examples
src/path/from.rs (line 49)
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
pub fn path_from<P: AsRef<Path> + std::fmt::Debug>(
    base_dir: P,
    anchor: PathAnchor,
    input: &str,
) -> PathBuf {
    let tilde = regex!(r"^~(/|$)");
    if input.starts_with('/') {
        // if the input starts with a `/`, we use it as is
        input.into()
    } else if tilde.is_match(input) {
        // if the input starts with `~` as first token, we replace
        // this `~` with the user home directory
        PathBuf::from(
            &*tilde
                .replace(input, |c: &Captures| {
                    if let Some(user_dirs) = UserDirs::new() {
                        format!(
                            "{}{}",
                            user_dirs.home_dir().to_string_lossy(),
                            &c[1],
                        )
                    } else {
                        warn!("no user dirs found, no expansion of ~");
                        c[0].to_string()
                    }
                })
        )
    } else {
        // we put the input behind the source (the selected directory
        // or its parent) and we normalize so that the user can type
        // paths with `../`
        let base_dir = match anchor {
            PathAnchor::Parent => base_dir
                .as_ref()
                .parent()
                .unwrap_or_else(|| base_dir.as_ref())
                .to_path_buf(),
            _ => closest_dir(base_dir.as_ref()),
        };
        normalize_path(base_dir.join(input))
    }
}
src/verb/execution_builder.rs (line 132)
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
    fn get_raw_sel_name_standard_replacement(
        &self,
        name: &str,
        sel: Option<Selection<'_>>,
    ) -> Option<String> {
        debug!("repl name : {:?}", name);
        match name {
            "root" => Some(path_to_string(self.root)),
            "line" => sel.map(|s| s.line.to_string()),
            "file" => sel.map(|s| s.path)
                .map(path_to_string),
            "file-name" => sel.map(|s| s.path)
                .and_then(|path| path.file_name())
                .and_then(|oss| oss.to_str())
                .map(|s| s.to_string()),
            "file-stem" => sel.map(|s| s.path)
                .and_then(|path| path.file_stem())
                .and_then(|oss| oss.to_str())
                .map(|s| s.to_string()),
            "file-extension" => {
                debug!("expending file extension");
                sel.map(|s| s.path)
                .and_then(|path| path.extension())
                .and_then(|oss| oss.to_str())
                .map(|s| s.to_string())
            }
            "file-dot-extension" => {
                debug!("expending file dot extension");
                sel.map(|s| s.path)
                .and_then(|path| path.extension())
                .and_then(|oss| oss.to_str())
                .map(|ext| format!(".{}", ext))
                .or_else(|| Some("".to_string()))
            }
            "directory" => sel.map(|s| path::closest_dir(s.path))
                .map(path_to_string),
            "parent" => sel.and_then(|s| s.path.parent())
                .map(path_to_string),
            "other-panel-file" => self.other_file
                .map(path_to_string),
            "other-panel-filename" => self.other_file
                .and_then(|path| path.file_name())
                .and_then(|oss| oss.to_str())
                .map(|s| s.to_string()),
            "other-panel-directory" => self
                .other_file
                .map(|p| path::closest_dir(p))
                .as_ref()
                .map(path_to_string),
            "other-panel-parent" => self
                .other_file
                .and_then(|p| p.parent())
                .map(path_to_string),
            _ => None,
        }
    }
    fn get_raw_sel_capture_replacement(
        &self,
        ec: &Captures<'_>,
        sel: Option<Selection<'_>>,
    ) -> Option<String> {
        let name = ec.get(1).unwrap().as_str();
        self.get_raw_sel_name_standard_replacement(name, sel)
            .or_else(||{
                // it's not one of the standard group names, so we'll look
                // into the ones provided by the invocation pattern
                self.invocation_values.as_ref()
                    .and_then(|map| map.get(name))
                    .and_then(|value| {
                        if let Some(fmt) = ec.get(2) {
                            match fmt.as_str() {
                                "path-from-directory" => {
                                    sel.map(|s| path::closest_dir(s.path))
                                        .map(|dir| path::path_str_from(dir, value))
                                }
                                "path-from-parent" => {
                                     sel.and_then(|s| s.path.parent())
                                        .map(|dir| path::path_str_from(dir, value))
                                }
                                _ => Some(format!("invalid format: {:?}", fmt.as_str())),
                            }
                        } else {
                            Some(value.to_string())
                        }
                    })
            })
    }
src/app/app.rs (line 389)
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
    fn apply_command(
        &mut self,
        w: &mut W,
        cmd: Command,
        panel_skin: &PanelSkin,
        app_state: &mut AppState,
        con: &mut AppContext,
    ) -> Result<(), ProgramError> {
        use CmdResult::*;
        let mut error: Option<String> = None;
        let is_input_invocation = cmd.is_verb_invocated_from_input();
        let app_cmd_context = AppCmdContext {
            panel_skin,
            preview_panel: self.preview_panel,
            stage_panel: self.stage_panel,
            screen: self.screen, // it can't change in this function
            con,
        };
        let cmd_result = self.mut_panel().apply_command(w, &cmd, app_state, &app_cmd_context)?;
        debug!("cmd_result: {:?}", &cmd_result);
        match cmd_result {
            ApplyOnPanel { id } => {
                if let Some(idx) = self.panel_id_to_idx(id) {
                    if let DisplayError(txt) = self.panels[idx].apply_command(
                        w, &cmd, app_state, &app_cmd_context
                    )? {
                        // we should probably handle other results
                        // which implies the possibility of a recursion
                        error = Some(txt);
                    } else if is_input_invocation {
                        self.mut_panel().clear_input();
                    }
                } else {
                    warn!("no panel found for ApplyOnPanel");
                }
            }
            ClosePanel { validate_purpose, panel_ref } => {
                if is_input_invocation {
                    self.mut_panel().clear_input_invocation(con);
                }
                let close_idx = self.panel_ref_to_idx(panel_ref)
                    .unwrap_or_else(||
                        // when there's a preview panel, we close it rather than the app
                        if self.panels.len().get()==2 && self.preview_panel.is_some() {
                            1
                        } else {
                            self.active_panel_idx
                        }
                    );
                let mut new_arg = None;
                if validate_purpose {
                    let purpose = &self.panels[close_idx].purpose;
                    if let PanelPurpose::ArgEdition { .. } = purpose {
                        new_arg = self.panels[close_idx]
                            .state()
                            .selected_path()
                            .map(|p| p.to_string_lossy().to_string());
                    }
                }
                if self.close_panel(close_idx) {
                    let screen = self.screen;
                    self.mut_state().refresh(screen, con);
                    if let Some(new_arg) = new_arg {
                        self.mut_panel().set_input_arg(new_arg);
                        let new_input = self.panel().get_input_content();
                        let cmd = Command::from_raw(new_input, false);
                        let app_cmd_context = AppCmdContext {
                            panel_skin,
                            preview_panel: self.preview_panel,
                            stage_panel: self.stage_panel,
                            screen,
                            con,
                        };
                        self.mut_panel().apply_command(w, &cmd, app_state, &app_cmd_context)?;
                    }
                } else {
                    self.quitting = true;
                }
            }
            DisplayError(txt) => {
                error = Some(txt);
            }
            ExecuteSequence { sequence } => {
                self.tx_seqs.send(sequence).unwrap();
            }
            HandleInApp(internal) => {
                debug!("handling internal {internal:?} at app level");
                match internal {
                    Internal::panel_left_no_open | Internal::panel_right_no_open => {
                        let new_active_panel_idx = if internal == Internal::panel_left_no_open {
                            // we're here because the state wants us to either move to the panel
                            // to the left, or close the rightest one
                            if self.active_panel_idx == 0 {
                                self.close_panel(self.panels.len().get()-1);
                                None
                            } else {
                                Some(self.active_panel_idx - 1)
                            }
                        } else { // panel_right
                            // we either move to the right or close the leftest panel
                            if self.active_panel_idx + 1 == self.panels.len().get() {
                                self.close_panel(0);
                                None
                            } else {
                                Some(self.active_panel_idx + 1)
                            }
                        };
                        if let Some(idx) = new_active_panel_idx {
                            if is_input_invocation {
                                self.mut_panel().clear_input();
                            }
                            self.active_panel_idx = idx;
                            let app_cmd_context = AppCmdContext {
                                panel_skin,
                                preview_panel: self.preview_panel,
                                stage_panel: self.stage_panel,
                                screen: self.screen,
                                con,
                            };
                            self.mut_panel().refresh_input_status(app_state, &app_cmd_context);
                        }
                    }
                    Internal::toggle_second_tree => {
                        let panels_count = self.panels.len().get();
                        let trees_count = self.panels.iter()
                            .filter(|p| p.state().get_type() == PanelStateType::Tree)
                            .count();
                        if trees_count < 2 {
                            // we open a tree, closing a (non tree) panel if necessary
                            if panels_count >= con.max_panels_count {
                                for i in (0..panels_count).rev() {
                                    if self.panels[i].state().get_type() != PanelStateType::Tree {
                                        self.close_panel(i);
                                        break;
                                    }
                                }
                            }
                            if let Some(selected_path) = self.state().selected_path() {
                                let dir = closest_dir(selected_path);
                                if let Ok(new_state) = BrowserState::new(
                                    dir,
                                    self.state().tree_options().without_pattern(),
                                    self.screen,
                                    con,
                                    &Dam::unlimited(),
                                ) {
                                    if let Err(s) = self.new_panel(
                                        Box::new(new_state),
                                        PanelPurpose::None,
                                        HDir::Right,
                                        is_input_invocation,
                                        con,
                                    ) {
                                        error = Some(s);
                                    }
                                }
                            }
                        } else {
                            // we close the rightest inactive tree
                            for i in (0..panels_count).rev() {
                                if self.panels[i].state().get_type() == PanelStateType::Tree {
                                    if i == self.active_panel_idx {
                                        continue;
                                    }
                                    self.close_panel(i);
                                    break;
                                }
                            }
                        }
                    }
                    Internal::set_syntax_theme => {
                        let arg = cmd
                            .as_verb_invocation()
                            .and_then(|vi| vi.args.as_ref());
                        match arg {
                            Some(arg) => {
                                match SyntaxTheme::from_str(arg) {
                                    Ok(theme) => {
                                        con.syntax_theme = Some(theme);
                                        self.update_preview(con, true);
                                    }
                                    Err(e) => {
                                        error = Some(e.to_string());
                                    }
                                }
                            }
                            None => {
                                error = Some("no theme provided".to_string());
                            }
                        }
                    }
                    _ => {
                        info!("unhandled propagated internal. cmd={:?}", &cmd);
                    }
                }
            }
            Keep => {
                if is_input_invocation {
                    self.mut_panel().clear_input_invocation(con);
                }
            }
            Launch(launchable) => {
                self.launch_at_end = Some(*launchable);
                self.quitting = true;
            }
            NewPanel {
                state,
                purpose,
                direction,
            } => {
                if let Err(s) = self.new_panel(state, purpose, direction, is_input_invocation, con) {
                    error = Some(s);
                }
            }
            NewState { state, message } => {
                self.mut_panel().clear_input();
                self.mut_panel().push_state(state);
                if let Some(md) = message {
                    self.mut_panel().set_message(md);
                } else {
                    self.mut_panel().refresh_input_status(app_state, &app_cmd_context);
                }
            }
            PopState => {
                if is_input_invocation {
                    self.mut_panel().clear_input();
                }
                if self.remove_state() {
                    self.mut_state().refresh(app_cmd_context.screen, con);
                    self.mut_panel().refresh_input_status(app_state, &app_cmd_context);
                } else if con.quit_on_last_cancel {
                    self.quitting = true;
                }
            }
            PopStateAndReapply => {
                if is_input_invocation {
                    self.mut_panel().clear_input();
                }
                if self.remove_state() {
                    let app_cmd_context = AppCmdContext {
                        panel_skin,
                        preview_panel: self.preview_panel,
                        stage_panel: self.stage_panel,
                        screen: self.screen,
                        con,
                    };
                    self.mut_panel().apply_command(w, &cmd, app_state, &app_cmd_context)?;
                } else if con.quit_on_last_cancel {
                    self.quitting = true;
                }
            }
            Quit => {
                self.quitting = true;
            }
            RefreshState { clear_cache } => {
                if is_input_invocation {
                    self.mut_panel().clear_input_invocation(con);
                }
                if clear_cache {
                    clear_caches();
                }
                app_state.stage.refresh();
                for i in 0..self.panels.len().get() {
                    self.panels[i].mut_state().refresh(self.screen, con);
                }
            }
        }
        if let Some(text) = error {
            self.mut_panel().set_error(text);
        }

        app_state.other_panel_path = self.get_other_panel_path();
        if let Some(path) = self.state().tree_root() {
            app_state.root = path.to_path_buf();
        }


        if let Some(shared_root) = &mut self.shared_root {
            if let Ok(mut root) = shared_root.lock() {
                *root = app_state.root.clone();
            }
        }

        self.update_preview(con, false);

        Ok(())
    }