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
//! Run completions for your program
//!
//! # Example
//!
//! ```rust,no_run
//! # #[cfg(unix)] {
//! # use std::path::Path;
//! # let bin_root = Path::new("").to_owned();
//! # let completion_script = "";
//! # let home = std::env::current_dir().unwrap();
//! let term = completest_nu::Term::new();
//!
//! let mut runtime = completest_nu::NuRuntime::new(bin_root, home).unwrap();
//! runtime.register("foo", completion_script).unwrap();
//! let output = runtime.complete("foo \t\t", &term).unwrap();
//! # }
//! ```

#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![warn(missing_docs)]
#![warn(clippy::print_stderr)]
#![warn(clippy::print_stdout)]

use std::ffi::OsStr;
use std::ffi::OsString;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;

use nu_cli::NuCompleter;
use nu_command::add_shell_command_context;
use nu_parser::parse;
use nu_protocol::{
    engine::{EngineState, Stack, StateWorkingSet},
    Value,
};
use reedline::Completer;

pub use completest::Runtime;
pub use completest::RuntimeBuilder;
pub use completest::Term;

/// Abstract factory for [`NuRuntime`]
#[derive(Debug)]
#[non_exhaustive]
pub struct NuRuntimeBuilder {}

impl RuntimeBuilder for NuRuntimeBuilder {
    type Runtime = NuRuntime;

    fn name() -> &'static str {
        "nu"
    }

    fn new(bin_root: PathBuf, home: PathBuf) -> std::io::Result<Self::Runtime> {
        NuRuntime::new(bin_root, home)
    }

    fn with_home(bin_root: PathBuf, home: PathBuf) -> std::io::Result<Self::Runtime> {
        NuRuntime::with_home(bin_root, home)
    }
}

/// Nushell runtime
///
/// > **WARNING:** This will call `std::env::set_current_dir`
#[derive(Debug)]
pub struct NuRuntime {
    path: OsString,
    home: PathBuf,
}

impl NuRuntime {
    /// Initialize a new runtime's home
    pub fn new(bin_root: PathBuf, home: PathBuf) -> std::io::Result<Self> {
        std::fs::create_dir_all(&home)?;

        let config = "";
        let config_path = home.join(".config/nushell/config.nu");
        std::fs::create_dir_all(config_path.parent().expect("path created with a parent"))?;
        std::fs::write(config_path, config)?;

        Self::with_home(bin_root, home)
    }

    /// Reuse an existing runtime's home
    pub fn with_home(bin_root: PathBuf, home: PathBuf) -> std::io::Result<Self> {
        let bin_root = dunce::canonicalize(bin_root)?;
        let home = dunce::canonicalize(home)?;
        let path = build_path(bin_root);
        Ok(Self { path, home })
    }

    /// Location of the runtime's home directory
    pub fn home(&self) -> &Path {
        &self.home
    }

    /// Register a completion script
    pub fn register(&mut self, name: &str, content: &str) -> std::io::Result<()> {
        let path = self
            .home
            .join(format!(".config/nushell/completions/{name}.nu"));
        std::fs::create_dir_all(path.parent().expect("path created with a parent"))?;
        std::fs::write(path, content)
    }

    /// Get the output from typing `input` into the shell
    pub fn complete(&mut self, input: &str, term: &Term) -> std::io::Result<String> {
        use std::fmt::Write as _;

        let input = input.split_once('\t').unwrap_or((input, "")).0;

        let completion_root = self.home.join(".config/nushell/completions");
        let mut completers = std::collections::BTreeMap::new();
        for entry in std::fs::read_dir(completion_root)? {
            let entry = entry?;
            if let Some(stem) = entry
                .file_name()
                .to_str()
                .unwrap_or_default()
                .strip_suffix(".nu")
            {
                let content = std::fs::read_to_string(entry.path())?;
                completers.insert(stem.to_owned(), content);
            }
        }
        let mut completer = external_completion(&self.path, &self.home, &completers)?;

        let suggestions = completer.complete(input, input.len());

        let mut max_value_len = 0;
        for suggestion in &suggestions {
            max_value_len = suggestion.value.len().max(max_value_len);
        }
        let spacer = "    ";

        let mut buffer = String::new();
        let _ = writeln!(&mut buffer, "% {input}");
        for suggestion in &suggestions {
            let value = &suggestion.value;
            let max_descr_len = (term.get_width() as usize) - max_value_len - spacer.len();
            let descr = suggestion
                .description
                .as_deref()
                .unwrap_or_default()
                .trim_end_matches('\n');
            let spacer = if !descr.is_empty() { spacer } else { "" };
            let descr = &descr[0..max_descr_len.min(descr.len())];
            let _ = writeln!(&mut buffer, "{value}{spacer}{descr}");
        }

        Ok(buffer)
    }
}

impl Runtime for NuRuntime {
    fn home(&self) -> &Path {
        self.home()
    }

    fn register(&mut self, name: &str, content: &str) -> std::io::Result<()> {
        self.register(name, content)
    }

    fn complete(&mut self, input: &str, term: &Term) -> std::io::Result<String> {
        self.complete(input, term)
    }
}

fn external_completion(
    path: &OsStr,
    home: &Path,
    completers: &std::collections::BTreeMap<String, String>,
) -> std::io::Result<NuCompleter> {
    // Create a new engine
    let (mut engine_state, mut stack) = new_engine(path, home)?;

    for completer in completers.values() {
        let (_, delta) = {
            let mut working_set = StateWorkingSet::new(&engine_state);
            let block = parse(&mut working_set, None, completer.as_bytes(), false);
            if !working_set.parse_errors.is_empty() {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    working_set.parse_errors.remove(0),
                ));
            }

            (block, working_set.render())
        };

        engine_state
            .merge_delta(delta)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;
    }

    // Merge environment into the permanent state
    engine_state
        .merge_env(&mut stack, home)
        .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

    if engine_state.num_blocks() == 0 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::Other,
            "completer not registered",
        ));
    }
    let latest_block_id = engine_state.num_blocks() - 1;

    // Change config adding the external completer
    let mut config = engine_state.get_config().clone();
    config.external_completer = Some(latest_block_id);
    engine_state.set_config(config);

    // Instantiate a new completer
    Ok(NuCompleter::new(Arc::new(engine_state), stack))
}

/// creates a new engine with the current path into the completions fixtures folder
fn new_engine(path: &OsStr, home: &Path) -> std::io::Result<(EngineState, Stack)> {
    let mut pwd = home
        .to_owned()
        .into_os_string()
        .into_string()
        .unwrap_or_default();
    pwd.push(std::path::MAIN_SEPARATOR);

    let path = path.to_owned().into_string().unwrap_or_default();
    let path_len = path.len();

    // Create a new engine with default context
    let mut engine_state = add_shell_command_context(nu_cmd_lang::create_default_context());

    // New stack
    let mut stack = Stack::new();

    // Add pwd as env var
    stack.add_env_var(
        "PWD".to_owned(),
        Value::String {
            val: pwd.clone(),
            internal_span: nu_protocol::Span::new(0, pwd.len()),
        },
    );

    #[cfg(windows)]
    stack.add_env_var(
        "Path".to_owned(),
        Value::String {
            val: path,
            internal_span: nu_protocol::Span::new(0, path_len),
        },
    );

    #[cfg(not(windows))]
    stack.add_env_var(
        "PATH".to_owned(),
        Value::String {
            val: path,
            internal_span: nu_protocol::Span::new(0, path_len),
        },
    );

    // Merge environment into the permanent state
    engine_state
        .merge_env(&mut stack, home)
        .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

    Ok((engine_state, stack))
}

fn build_path(bin_root: PathBuf) -> OsString {
    let mut path = bin_root.into_os_string();
    if let Some(existing) = std::env::var_os("PATH") {
        path.push(":");
        path.push(existing);
    }
    path
}