summaryrefslogtreecommitdiffstats
path: root/src/commands/touch_file.rs
blob: f36befff7ae1a762ab892aae705d80f782de50cc (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
use std::fs::File;
use std::path;
use std::time::SystemTime;

use filetime::FileTime;

use crate::commands::cursor_move;
use crate::context::AppContext;
use crate::error::AppResult;
use crate::history::create_dirlist_with_history;

fn _update_actime(file: &path::Path) -> std::io::Result<()> {
    let file_time = FileTime::from_system_time(SystemTime::now());
    filetime::set_file_times(file, file_time, file_time)
}

fn _create_file(file: &path::Path) -> std::io::Result<()> {
    File::create(file)?;
    Ok(())
}

pub fn touch_file(context: &mut AppContext, arg: &str) -> AppResult {
    let curr_tab = context.tab_context_ref().curr_tab_ref();
    match arg {
        "" => {
            if let Some(selected_file_path) = context
                .tab_context_ref()
                .curr_tab_ref()
                .curr_list_ref()
                .and_then(|s| s.curr_entry_ref())
                .map(|s| s.file_path().to_path_buf())
            {
                _update_actime(&selected_file_path)?
            }
        }
        file_arg => {
            let file = path::PathBuf::from(file_arg);
            if file.exists() {
                _update_actime(file.as_path())?;
            } else {
                _create_file(file.as_path())?;
            }
        }
    }

    let path = curr_tab
        .curr_list_ref()
        .map(|lst| lst.file_path().to_path_buf());

    if let Some(path) = path {
        let options = context.config_ref().display_options_ref().clone();
        let tab_options = context
            .tab_context_ref()
            .curr_tab_ref()
            .option_ref()
            .clone();
        let history = context.tab_context_mut().curr_tab_mut().history_mut();
        let new_dirlist =
            create_dirlist_with_history(history, path.as_path(), &options, &tab_options)?;
        history.insert(path, new_dirlist);
    }

    if context.config_ref().focus_on_create {
        cursor_move::to_path(context, path::Path::new(arg))?;
    }

    Ok(())
}