summaryrefslogtreecommitdiffstats
path: root/src/commands/sub_process.rs
blob: 2e5a1c8e8741eb2d1f13d4efecd60dd73e63b82c (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
use crate::context::AppContext;
use crate::error::AppResult;
use crate::ui::AppBackend;
use std::process::{Command, Stdio};

use super::reload;

#[derive(Debug, Clone)]
pub enum SubprocessCallMode {
    Interactive,
    Spawn,
    Capture,
}

pub fn current_filenames(context: &AppContext) -> Vec<&str> {
    let mut result = Vec::new();
    if let Some(curr_list) = context.tab_context_ref().curr_tab_ref().curr_list_ref() {
        let mut i = 0;
        curr_list
            .iter_selected()
            .map(|e| e.file_name())
            .for_each(|file_name| {
                result.push(file_name);
                i += 1;
            });
        if i == 0 {
            if let Some(entry) = curr_list.curr_entry_ref() {
                result.push(entry.file_name());
            }
        }
    }

    result
}

fn execute_sub_process(
    context: &mut AppContext,
    words: &[String],
    mode: SubprocessCallMode,
) -> std::io::Result<()> {
    let mut command = Command::new(words[0].clone());
    for word in words.iter().skip(1) {
        match (*word).as_str() {
            "%s" => {
                current_filenames(context).into_iter().for_each(|x| {
                    command.arg(x);
                });
            }
            "%p" => {
                if let Some(curr_list) = context.tab_context_ref().curr_tab_ref().curr_list_ref() {
                    let mut i = 0;
                    curr_list
                        .iter_selected()
                        .map(|e| e.file_path())
                        .for_each(|file_path| {
                            command.arg(file_path);
                            i += 1;
                        });
                    if i == 0 {
                        if let Some(entry) = curr_list.curr_entry_ref() {
                            command.arg(entry.file_path());
                        }
                    }
                }
            }
            s => {
                command.arg(s);
            }
        };
    }
    match mode {
        SubprocessCallMode::Interactive => {
            let status = command.status();
            match status {
                Ok(status) => {
                    if status.code() == Some(0) {
                        Ok(())
                    } else {
                        Err(std::io::Error::new(
                            std::io::ErrorKind::Other,
                            format!("Command failed with {:?}", status),
                        ))
                    }
                }
                Err(err) => Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    format!("Shell execution failed: {:?}", err),
                )),
            }
        }
        SubprocessCallMode::Spawn => {
            command
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()?;
            Ok(())
        }
        SubprocessCallMode::Capture => {
            let output = command
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .output()?;
            if output.status.code() == Some(0) {
                context.last_stdout = Some(String::from_utf8_lossy(&output.stdout).to_string());
                Ok(())
            } else {
                Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    format!("Command failed with {:?}", output.status),
                ))
            }
        }
    }
}

/// Handler for Joshuto's `shell` and `spawn` commands.
pub fn sub_process(
    context: &mut AppContext,
    backend: &mut AppBackend,
    words: &[String],
    mode: SubprocessCallMode,
) -> AppResult {
    match mode {
        SubprocessCallMode::Interactive => {
            // Joshuto needs to release the terminal when handing it over to some interactive
            // shell command and restore it afterwards
            backend.terminal_drop();
            execute_sub_process(context, words, mode)?;
            backend.terminal_restore()?;
            let _ = reload::soft_reload_curr_tab(context);
            context
                .message_queue_mut()
                .push_info(format!("Finished: {}", words.join(" ")));
        }
        SubprocessCallMode::Spawn => {
            execute_sub_process(context, words, mode)?;
            context
                .message_queue_mut()
                .push_info(format!("Spawned: {}", words.join(" ")));
        }
        SubprocessCallMode::Capture => {
            execute_sub_process(context, words, mode)?;
            let _ = reload::soft_reload_curr_tab(context);
        }
    };
    Ok(())
}