summaryrefslogtreecommitdiffstats
path: root/src/commands/rename_file.rs
blob: 844b7f026796ccb7298251ce4a87584f8934335b (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
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
use std::fs;
use std::path;

use crate::commands::{CursorMove, JoshutoCommand, JoshutoRunnable, Search};
use crate::context::JoshutoContext;
use crate::error::JoshutoError;
use crate::preview;
use crate::textfield::JoshutoTextField;
use crate::ui;
use crate::window::JoshutoView;

#[derive(Clone, Debug)]
pub enum RenameFileMethod {
    Append,
    Prepend,
    Overwrite,
}

#[derive(Clone, Debug)]
pub struct RenameFile {
    method: RenameFileMethod,
}

impl RenameFile {
    pub fn new(method: RenameFileMethod) -> Self {
        RenameFile { method }
    }
    pub const fn command() -> &'static str {
        "rename_file"
    }

    pub fn rename_file(
        &self,
        path: &path::PathBuf,
        context: &mut JoshutoContext,
        view: &JoshutoView,
        start_str: String,
    ) -> Result<(), JoshutoError> {
        const PROMPT: &str = ":rename_file ";
        let (term_rows, term_cols) = ui::getmaxyx();
        let user_input: Option<String> = {
            let textfield = JoshutoTextField::new(
                1,
                term_cols,
                (term_rows as usize - 1, 0),
                PROMPT.to_string(),
            );

            match self.method {
                RenameFileMethod::Append => {
                    if let Some(ext) = start_str.rfind('.') {
                        textfield.readline_with_initial(&start_str[0..ext], &start_str[ext..])
                    } else {
                        textfield.readline_with_initial(&start_str, "")
                    }
                }
                RenameFileMethod::Prepend => textfield.readline_with_initial("", &start_str),
                RenameFileMethod::Overwrite => textfield.readline_with_initial("", ""),
            }
        };

        if let Some(s) = user_input {
            let mut new_path = path.parent().unwrap().to_path_buf();

            new_path.push(s);
            if new_path.exists() {
                let err = std::io::Error::new(
                    std::io::ErrorKind::AlreadyExists,
                    "Filename already exists",
                );
                return Err(JoshutoError::IO(err));
            }
            match fs::rename(&path, &new_path) {
                Ok(_) => {
                    let curr_tab = &mut context.tabs[context.curr_tab_index];
                    if let Some(ref mut s) = curr_tab.curr_list {
                        s.update_contents(&context.config_t.sort_option).unwrap();
                    }
                    curr_tab.refresh_curr(&view.mid_win, context.config_t.scroll_offset);
                }
                Err(e) => {
                    return Err(JoshutoError::IO(e));
                }
            }
        } else {
            let curr_tab = &context.tabs[context.curr_tab_index];
            curr_tab.refresh_file_status(&view.bot_win);
        }
        Ok(())
    }
}

impl JoshutoCommand for RenameFile {}

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

impl JoshutoRunnable for RenameFile {
    fn execute(
        &self,
        context: &mut JoshutoContext,
        view: &JoshutoView,
    ) -> Result<(), JoshutoError> {
        let mut path: Option<path::PathBuf> = None;
        let mut file_name: Option<String> = None;

        if let Some(s) = context.tabs[context.curr_tab_index].curr_list.as_ref() {
            if let Some(s) = s.get_curr_ref() {
                path = Some(s.path.clone());
                file_name = Some(s.file_name_as_string.clone());
            }
        }

        if let Some(file_name) = file_name {
            if let Some(path) = path {
                let res = self.rename_file(&path, context, view, file_name.clone());
                if let Some(index) = Search::search(context.curr_tab_ref(), &file_name) {
                    CursorMove::cursor_move(index, context, view);
                }
                preview::preview_file(
                    &mut context.tabs[context.curr_tab_index],
                    view,
                    &context.config_t,
                );
                ncurses::doupdate();
                return res;
            }
        }
        return Ok(());
    }
}