summaryrefslogtreecommitdiffstats
path: root/src/commands/change_directory.rs
blob: 84d8fdb167f24ebe23873cce47c55e8b3d1937cf (plain)
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
use std::path;

use crate::commands::{reload, zoxide};
use crate::context::AppContext;
use crate::error::AppResult;
use crate::history::{generate_entries_to_root, DirectoryHistory};
use crate::util::cwd;

// ChangeDirectory command
pub fn cd(path: &path::Path, context: &mut AppContext) -> std::io::Result<()> {
    cwd::set_current_dir(path)?;
    context.tab_context_mut().curr_tab_mut().set_cwd(path);
    if context.config_ref().zoxide_update {
        debug_assert!(path.is_absolute());
        zoxide::zoxide_add(path.to_str().expect("cannot convert path to string"))?;
    }
    Ok(())
}

pub fn change_directory(context: &mut AppContext, mut path: &path::Path) -> AppResult {
    let new_cwd = if path.is_absolute() {
        path.to_path_buf()
    } else {
        while let Ok(p) = path.strip_prefix("../") {
            parent_directory(context)?;
            path = p;
        }

        let mut new_cwd = std::env::current_dir()?;
        new_cwd.push(path);
        new_cwd
    };

    cd(new_cwd.as_path(), context)?;
    let dirlists = generate_entries_to_root(
        new_cwd.as_path(),
        context.tab_context_ref().curr_tab_ref().history_ref(),
        context.ui_context_ref(),
        context.config_ref().display_options_ref(),
        context.tab_context_ref().curr_tab_ref().option_ref(),
    )?;
    context
        .tab_context_mut()
        .curr_tab_mut()
        .history_mut()
        .insert_entries(dirlists);
    Ok(())
}

// ParentDirectory command
pub fn parent_directory(context: &mut AppContext) -> AppResult {
    if let Some(parent) = context
        .tab_context_ref()
        .curr_tab_ref()
        .cwd()
        .parent()
        .map(|p| p.to_path_buf())
    {
        cwd::set_current_dir(&parent)?;
        context
            .tab_context_mut()
            .curr_tab_mut()
            .set_cwd(parent.as_path());
        reload::soft_reload_curr_tab(context)?;
    }
    Ok(())
}

// PreviousDirectory command
pub fn previous_directory(context: &mut AppContext) -> AppResult {
    if let Some(path) = context.tab_context_ref().curr_tab_ref().previous_dir() {
        let path = path.to_path_buf();
        cwd::set_current_dir(&path)?;
        context
            .tab_context_mut()
            .curr_tab_mut()
            .set_cwd(path.as_path());
        reload::soft_reload_curr_tab(context)?;
    }
    Ok(())
}