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
// [[file:../gosh-shell.note::7643ea86][7643ea86]]
use gut::prelude::*;
use std::path::{Path, PathBuf};
// 7643ea86 ends here

// [[file:../gosh-shell.note::f90f0bfb][f90f0bfb]]
mod helper;
// f90f0bfb ends here

// [[file:../gosh-shell.note::845cbd1e][845cbd1e]]
use rustyline::{history::FileHistory, Editor};
type MyEditor<R> = Editor<helper::MyHelper<R>, FileHistory>;

/// An shell-like REPL interpreter.
pub struct Interpreter<A> {
    prompt: String,
    history_file: Option<PathBuf>,
    action: A,
}
// 845cbd1e ends here

// [[file:../gosh-shell.note::aa47dc5f][aa47dc5f]]
impl<A: Actionable> Interpreter<A> {
    /// Interpret one line.
    fn continue_interpret_line(&mut self, line: &str) -> bool {
        if let Some(mut args) = shlex::split(line) {
            assert!(args.len() >= 1);
            args.insert(0, self.prompt.to_owned());

            match A::try_parse_from(&args) {
                // apply subcommand
                Ok(x) => match self.action.act_on(&x) {
                    Ok(exit) => {
                        if exit {
                            return false;
                        }
                    }
                    Err(e) => {
                        eprintln!("{:?}", e);
                    }
                },
                // show subcommand usage
                Err(e) => println!("{:}", e),
            }
            true
        } else {
            eprintln!("Invalid quoting: {line:?}");
            false
        }
    }

    fn continue_read_eval_print<R: HelpfulCommand>(&mut self, editor: &mut MyEditor<R>) -> bool {
        match editor.readline(&self.prompt) {
            Err(rustyline::error::ReadlineError::Eof) => false,
            Ok(line) => {
                let line = line.trim();
                if !line.is_empty() {
                    let _ = editor.add_history_entry(line);
                    self.continue_interpret_line(&line)
                } else {
                    true
                }
            }
            Err(e) => {
                eprintln!("{}", e);
                false
            }
        }
    }
}

fn create_readline_editor<R: HelpfulCommand>() -> Result<Editor<helper::MyHelper<R>, FileHistory>> {
    use rustyline::{ColorMode, CompletionType, Config};

    let config = Config::builder()
        .color_mode(ColorMode::Enabled)
        .completion_type(CompletionType::Fuzzy)
        .history_ignore_dups(true)?
        .history_ignore_space(true)
        .max_history_size(1000)?
        .build();

    let mut rl = Editor::with_config(config)?;
    let h = self::helper::MyHelper::new();
    rl.set_helper(Some(h));
    Ok(rl)
}
// aa47dc5f ends here

// [[file:../gosh-shell.note::360871b3][360871b3]]
impl<A: Actionable> Interpreter<A> {
    fn load_history<R: HelpfulCommand>(&mut self, editor: &mut MyEditor<R>) -> Result<()> {
        if let Some(h) = self.history_file.as_ref() {
            editor.load_history(h).context("no history")?;
        }
        Ok(())
    }

    fn save_history<R: HelpfulCommand>(&mut self, editor: &mut MyEditor<R>) -> Result<()> {
        if let Some(h) = self.history_file.as_ref() {
            editor.save_history(h).context("write history file")?;
        }
        Ok(())
    }
}
// 360871b3 ends here

// [[file:../gosh-shell.note::05b99d70][05b99d70]]
impl<A: Actionable> Interpreter<A> {
    pub fn interpret_script(&mut self, script: &str) -> Result<()> {
        let lines = script.lines().filter(|s| !s.trim().is_empty());
        for line in lines {
            debug!("Execute: {:?}", line);
            if !self.continue_interpret_line(&line) {
                break;
            }
        }

        Ok(())
    }

    pub fn interpret_script_file(&mut self, script_file: &Path) -> Result<()> {
        let s = gut::fs::read_file(script_file)?;
        self.interpret_script(&s)?;
        Ok(())
    }
}
// 05b99d70 ends here

// [[file:../gosh-shell.note::9fdf556e][9fdf556e]]
/// Defines actions for REPL commands
pub trait Actionable {
    type Command: clap::Parser;

    /// Take action on REPL commands. Return Ok(true) will exit shell
    /// loop.
    fn act_on(&mut self, cmd: &Self::Command) -> Result<bool>;

    /// parse Command from shell line input.
    fn try_parse_from<I, T>(iter: I) -> Result<Self::Command>
    where
        I: IntoIterator<Item = T>,
        T: Into<std::ffi::OsString> + Clone,
    {
        use clap::Parser;

        let r = Self::Command::try_parse_from(iter)?;
        Ok(r)
    }
}

/// Define command completion
pub trait HelpfulCommand {
    fn get_subcommands() -> Vec<String>;
    fn suitable_for_path_complete(line: &str, pos: usize) -> bool;
}

impl<T: clap::CommandFactory> HelpfulCommand for T {
    fn get_subcommands() -> Vec<String> {
        let app = Self::command();
        app.get_subcommands().map(|s| s.get_name().into()).collect()
    }

    /// try to complete when current char is a path separator: foo ./
    fn suitable_for_path_complete(line: &str, pos: usize) -> bool {
        line[..pos]
            .chars()
            .last()
            .map(|x| std::path::is_separator(x))
            .unwrap_or(false)
    }
}
// 9fdf556e ends here

// [[file:../gosh-shell.note::f3bcb018][f3bcb018]]
impl<A: Actionable> Interpreter<A> {
    #[track_caller]
    pub fn new(action: A) -> Self {
        Self {
            prompt: "> ".to_string(),
            // editor: create_readline_editor::<R>().unwrap(),
            history_file: None,
            action,
        }
    }
}

impl<A: Actionable> Interpreter<A> {
    /// Set absolute path to history file for permanently storing command history.
    pub fn with_history_file<P: Into<PathBuf>>(mut self, path: P) -> Self {
        let p = path.into();
        self.history_file = Some(p);
        self
    }

    /// Set prompting string for REPL.
    pub fn with_prompt(mut self, s: &str) -> Self {
        self.prompt = s.into();
        self
    }

    /// Entry point for REPL.
    pub fn run(&mut self) -> Result<()> {
        let version = env!("CARGO_PKG_VERSION");
        println!("This is the interactive parser, version {}.", version);
        println!("Enter \"help\" or \"?\" for a list of commands.");
        println!("Press Ctrl-D or enter \"quit\" or \"q\" to exit.");
        println!("");

        let mut editor = create_readline_editor::<A::Command>()?;
        let _ = self.load_history(&mut editor);
        while self.continue_read_eval_print(&mut editor) {
            debug!("excuted one loop");
        }
        self.save_history(&mut editor)?;

        Ok(())
    }
}
// f3bcb018 ends here