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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
//! ## Runtime
//!
//! `runtime` contains the runtime functions for pyc core

/*
*
*   Copyright (C) 2020 Christian Visintin - christian.visintin1997@gmail.com
*
* 	This file is part of "Pyc"
*
*   Pyc is free software: you can redistribute it and/or modify
*   it under the terms of the GNU General Public License as published by
*   the Free Software Foundation, either version 3 of the License, or
*   (at your option) any later version.
*
*   Pyc is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU General Public License for more details.
*
*   You should have received a copy of the GNU General Public License
*   along with Pyc.  If not, see <http://www.gnu.org/licenses/>.
*
*/

//Deps
extern crate ansi_term;
extern crate nix;

use ansi_term::Colour;
use std::env;
use std::path::Path;
use std::thread::sleep;
use std::time::{Duration};

use crate::config;
use crate::shell::proc::ShellState;
use crate::shell::{Shell};
use crate::translator::ioprocessor::IOProcessor;
use crate::utils::async_stdin;
use crate::utils::file;

/// ### run_interactive
///
/// Run pyc in interactive mode

pub fn run_interactive(processor: IOProcessor, config: &config::Config, shell: Option<String>) -> u8 {
    //Determine the shell to use
    let (shell, args): (String, Vec<String>) = match shell {
        Some(sh) => (sh, vec![]),
        None => (config.shell_config.exec.clone(), config.shell_config.args.clone()) //Get shell from config
    };
    //Intantiate and start a new shell
    let mut shell: Shell = match Shell::start(shell, args, &config.prompt_config) {
        Ok(sh) => sh,
        Err(err) => {
            print_err(
                String::from(format!("Could not start shell: {}", err)),
                config.output_config.translate_output,
                &processor,
            );
            return 255;
        }
    };
    //@! Main loop
    let mut last_state: ShellState = ShellState::Unknown;
    let mut state_changed: bool = true; //Start with state changed, this determines whether the prompt should be printed
    while last_state != ShellState::Terminated {
        //@! Print prompt if state is Idle and state has changed
        let current_state: ShellState = shell.get_state();
        if current_state != last_state {
            state_changed = true;
            last_state = current_state;
        }
        if state_changed && current_state == ShellState::Idle {
            //Force shellenv to refresh info
            shell.refresh_env();
            //Print prompt
            shell.pprompt(&processor);
            state_changed = false; //Force state changed to false
        } else if state_changed {
            state_changed = false; //Check has been done, nothing to do
        }
        //@! Read user input
        if async_stdin::is_ready() { //Check if stdin is ready to be read
            let input: String = async_stdin::read();
            //If input is empty, print prompt (if state is IDLE)
            if input.trim().len() == 0 {
                if last_state == ShellState::Idle {
                    shell.pprompt(&processor);
                }
            } else {
                //Treat input
                //If state is Idle, convert expression, otherwise convert text
                let input: String = match last_state {
                    ShellState::Idle => {
                        //Resolve alias
                        let mut argv: Vec<String> = Vec::with_capacity(input.matches(" ").count() + 1);
                        for arg in input.split_whitespace() {
                            argv.push(String::from(arg));
                        }
                        //Process arg 0
                        resolve_command(&mut argv, &config);
                        //Rejoin arguments
                        let input: String = argv.join(" ") + "\n";
                        match processor.expression_to_latin(input) {
                            Ok(ex) => ex,
                            Err(err) => {
                                print_err(String::from(format!("Input error: {:?}", err)), config.output_config.translate_output, &processor);
                                continue;
                            }
                        }
                    },
                    ShellState::SubprocessRunning => processor.text_to_latin(input),
                    _ => continue
                };
                if let Err(err) = shell.write(input) {
                    print_err(
                        String::from(err.to_string()),
                        config.output_config.translate_output,
                        &processor,
                    );
                }
                //Update state after write
                let new_state = shell.get_state(); //Force last state to be changed
                if new_state != last_state {
                    last_state = new_state;
                    state_changed = true;
                }
            }
        }
        //@! Read Shell stdout
        if let Ok((out, err)) = shell.read() {
            if out.is_some() {
                //Convert out to cyrillic
                print_out(out.unwrap(), config.output_config.translate_output, &processor);
            }
            if err.is_some() {
                //Convert err to cyrillic
                print_err(err.unwrap().to_string(), config.output_config.translate_output, &processor);
            }
        }
        sleep(Duration::from_nanos(100)); //Sleep for 100ns
    } //@! End of loop
    //Return shell exitcode
    match shell.stop() {
        Ok(rc) => rc,
        Err(err) => {
            print_err(format!("Could not stop shell: {}", err), config.output_config.translate_output, &processor);
            255
        }
    }
}

/// ### run_command
/// 
/// Run command in shell and return
pub fn run_command(mut command: String, processor: IOProcessor, config: &config::Config, shell: Option<String>) -> u8 {
    //Determine the shell to use
    let (shell, args): (String, Vec<String>) = match shell {
        Some(sh) => (sh, vec![]),
        None => (config.shell_config.exec.clone(), config.shell_config.args.clone()) //Get shell from config
    };
    //Intantiate and start a new shell
    let mut shell: Shell = match Shell::start(shell, args, &config.prompt_config) {
        Ok(sh) => sh,
        Err(err) => {
            print_err(
                String::from(format!("Could not start shell: {}", err)),
                config.output_config.translate_output,
                &processor,
            );
            return 255;
        }
    };
    //Write command
    while command.ends_with('\n') {
        command.pop();
    }
    while command.ends_with(';') {
        command.pop();
    }
    //FIXME: handle fish $status
    command.push_str("; exit $?\n");
    if let Err(err) = shell.write(command) {
        print_err(
            String::from(format!("Could not start shell: {}", err)),
            config.output_config.translate_output,
            &processor,
        );
        return 255;
    }
    let _ = shell.write(String::from("\n"));
    //@! Main loop
    loop { //Check state after reading/writing, since program could have already terminate
        //@! Read user input
        if async_stdin::is_ready() { //Check if stdin is ready to be read
            let input: String = async_stdin::read();
            //If input is empty, ignore it
            if input.trim().len() > 0 {
                //Treat input
                //Convert text
                let input: String = processor.text_to_latin(input);
                if let Err(err) = shell.write(input) {
                    print_err(
                        String::from(err.to_string()),
                        config.output_config.translate_output,
                        &processor,
                    );
                }
            }
        }
        //@! Read Shell stdout
        if let Ok((out, err)) = shell.read() {
            if out.is_some() {
                //Convert out to cyrillic
                print_out(out.unwrap(), config.output_config.translate_output, &processor);
            }
            if err.is_some() {
                //Convert err to cyrillic
                print_err(err.unwrap().to_string(), config.output_config.translate_output, &processor);
            }
        }
        if shell.get_state() == ShellState::Terminated {
            break;
        }
        sleep(Duration::from_nanos(100)); //Sleep for 100ns
    } //@! End of main loop
    //Return shell exitcode
    match shell.stop() {
        Ok(rc) => rc,
        Err(err) => {
            print_err(format!("Could not stop shell: {}", err), config.output_config.translate_output, &processor);
            255
        }
    }
}

/// ### run_file
/// 
/// Run shell reading commands from file
pub fn run_file(file: String, processor: IOProcessor, config: &config::Config, shell: Option<String>) -> u8 {
    let file_path: &Path = Path::new(file.as_str());
    let lines: Vec<String> = match file::read_lines(file_path) {
        Ok(lines) => lines,
        Err(_) => {
            print_err(format!("{}: No such file or directory", file), config.output_config.translate_output, &processor);
            return 255
        }
    };
    //Join lines in a single command
    let mut command: String = String::new();
    for line in lines.iter() {
        if line.starts_with("#") {
            continue;
        }
        if line.len() == 0 {
            continue;
        }
        command.push_str(line);
        command.push(';');
    }
    //Execute command
    run_command(command, processor, config, shell)
}

#[allow(dead_code)]
/// ### get_shell_from_env
///
/// Try to get the shell path from SHELL environment variable
fn get_shell_from_env() -> Result<String, ()> {
    if let Ok(val) = env::var("SHELL") {
        Ok(val)
    } else {
        Err(())
    }
}

/// ### resolve_command
///
/// resolve command according to configured alias

fn resolve_command(argv: &mut Vec<String>, config: &config::Config) {
    //Process arg 0
    match config.get_alias(&argv[0]) {
        Some(resolved) => argv[0] = resolved,
        None => {}
    };
}

/// ### print_err
/// 
/// print error message; the message is may converted to cyrillic if translate config is true

fn print_err(err: String, to_cyrillic: bool, processor: &IOProcessor) {
    match to_cyrillic {
        true => eprintln!("{}", Colour::Red.paint(processor.text_to_cyrillic(err))),
        false => eprintln!("{}", Colour::Red.paint(err)),
    };
}

/// ### print_out
///
/// print normal message; the message is may converted to cyrillic if translate config is true

fn print_out(out: String, to_cyrillic: bool, processor: &IOProcessor) {
    match to_cyrillic {
        true => print!("{}", processor.text_to_cyrillic(out)),
        false => print!("{}", out),
    };
}