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

use crate::commands::{CommandLine, JoshutoCommand, JoshutoRunnable};
use crate::context::JoshutoContext;
use crate::error::JoshutoError;
use crate::window::JoshutoView;

use rustyline::completion::{escape, Quote};

#[cfg(unix)]
static DEFAULT_BREAK_CHARS: [u8; 18] = [
    b' ', b'\t', b'\n', b'"', b'\\', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&',
    b'{', b'(', b'\0',
];
#[cfg(unix)]
static ESCAPE_CHAR: Option<char> = Some('\\');

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

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

    pub fn rename_file(
        &self,
        path: &path::PathBuf,
        context: &mut JoshutoContext,
        view: &JoshutoView,
    ) -> Result<(), std::io::Error> {
        let new_path = &self.path;
        if new_path.exists() {
            let err =
                std::io::Error::new(std::io::ErrorKind::AlreadyExists, "Filename already exists");
            return Err(err);
        }
        std::fs::rename(&path, &new_path)?;
        let curr_tab = &mut context.tabs[context.curr_tab_index];
        curr_tab
            .curr_list
            .update_contents(&context.config_t.sort_option)?;
        curr_tab.refresh_curr(&view.mid_win);
        curr_tab.refresh_preview(&view.right_win, &context.config_t);
        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 curr_list = &context.tabs[context.curr_tab_index].curr_list;
        if let Some(s) = curr_list.get_curr_ref() {
            path = Some(s.path.clone());
        }

        if let Some(path) = path {
            match self.rename_file(&path, context, view) {
                Ok(_) => {}
                Err(e) => return Err(JoshutoError::IO(e)),
            }
            ncurses::doupdate();
        }
        Ok(())
    }
}

#[derive(Clone, Debug)]
pub struct RenameFileAppend;

impl RenameFileAppend {
    pub fn new() -> Self {
        RenameFileAppend {}
    }
    pub const fn command() -> &'static str {
        "rename_append"
    }

    pub fn rename_file(
        &self,
        context: &mut JoshutoContext,
        view: &JoshutoView,
        file_name: String,
    ) -> Result<(), JoshutoError> {
        let prefix;
        let suffix;
        if let Some(ext) = file_name.rfind('.') {
            prefix = format!("rename {}", &file_name[0..ext]);
            suffix = String::from(&file_name[ext..]);
        } else {
            prefix = format!("rename {}", file_name);
            suffix = String::new();
        }

        let command = CommandLine::new(prefix, suffix);
        command.readline(context, view)
    }
}

impl JoshutoCommand for RenameFileAppend {}

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

impl JoshutoRunnable for RenameFileAppend {
    fn execute(
        &self,
        context: &mut JoshutoContext,
        view: &JoshutoView,
    ) -> Result<(), JoshutoError> {
        let curr_list = &context.tabs[context.curr_tab_index].curr_list;
        let file_name = match curr_list.get_curr_ref() {
            Some(s) => {
                let escaped = escape(
                    s.file_name_as_string.clone(),
                    ESCAPE_CHAR,
                    &DEFAULT_BREAK_CHARS,
                    Quote::None,
                );
                Some(escaped)
            }
            None => None,
        };

        if let Some(file_name) = file_name {
            self.rename_file(context, view, file_name)?;
            ncurses::doupdate();
        }
        Ok(())
    }
}

#[derive(Clone, Debug)]
pub struct RenameFilePrepend;

impl RenameFilePrepend {
    pub fn new() -> Self {
        RenameFilePrepend {}
    }
    pub const fn command() -> &'static str {
        "rename_prepend"
    }

    pub fn rename_file(
        &self,
        context: &mut JoshutoContext,
        view: &JoshutoView,
        file_name: String,
    ) -> Result<(), JoshutoError> {
        let prefix = String::from("rename ");
        let suffix = file_name;

        let command = CommandLine::new(prefix, suffix);
        command.readline(context, view)
    }
}

impl JoshutoCommand for RenameFilePrepend {}

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

impl JoshutoRunnable for RenameFilePrepend {
    fn execute(
        &self,
        context: &mut JoshutoContext,
        view: &JoshutoView,
    ) -> Result<(), JoshutoError> {
        let curr_list = &context.tabs[context.curr_tab_index].curr_list;
        let file_name = match curr_list.get_curr_ref() {
            Some(s) => {
                let escaped = escape(
                    s.file_name_as_string.clone(),
                    ESCAPE_CHAR,
                    &DEFAULT_BREAK_CHARS,
                    Quote::None,
                );
                Some(escaped)
            }
            None => None,
        };

        if let Some(file_name) = file_name {
            self.rename_file(context, view, file_name)?;
            ncurses::doupdate();
        }
        Ok(())
    }
}