summaryrefslogtreecommitdiffstats
path: root/src/commands/change_directory.rs
blob: 5f30c36cbc3140fc0aacf50bf21db122d57353f6 (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
use std::path;

use crate::commands::{JoshutoCommand, JoshutoRunnable};
use crate::context::JoshutoContext;
use crate::error::JoshutoResult;
use crate::history::DirectoryHistory;
use crate::ui::TuiBackend;
use crate::util::load_child::LoadChild;

#[derive(Clone, Debug)]
pub struct ChangeDirectory {
    path: path::PathBuf,
}

impl ChangeDirectory {
    pub fn new(path: path::PathBuf) -> Self {
        ChangeDirectory { path }
    }
    pub const fn command() -> &'static str {
        "cd"
    }

    pub fn cd(path: &path::Path, context: &mut JoshutoContext) -> std::io::Result<()> {
        std::env::set_current_dir(path)?;

        let curr_tab = &mut context.tabs[context.curr_tab_index];
        curr_tab.curr_path = path.to_path_buf();

        Ok(())
    }

    pub fn change_directories(
        path: &path::Path,
        context: &mut JoshutoContext,
        backend: &mut TuiBackend,
    ) -> std::io::Result<()> {
        Self::cd(path, context)?;

        let curr_tab = &mut context.tabs[context.curr_tab_index];
        curr_tab
            .history
            .populate_to_root(&path, &context.config_t.sort_option)?;

        Ok(())
    }
}

impl JoshutoCommand for ChangeDirectory {}

impl std::fmt::Display for ChangeDirectory {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{} {}", Self::command(), self.path.to_str().unwrap())
    }
}

impl JoshutoRunnable for ChangeDirectory {
    fn execute(&self, context: &mut JoshutoContext, backend: &mut TuiBackend) -> JoshutoResult<()> {
        Self::change_directories(&self.path, context, backend)?;
        LoadChild::load_child(context, backend);

        Ok(())
    }
}