nvimo 0.0.1

A fork of nvim-oxi (Rust bindings to all things Neovim) using mlua for Rust-Lua interop
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Functions called by the code generated by `#[nvimo::test].`

use core::{fmt, str};
use std::any::Any;
use std::env;
use std::io::{self, Write};
use std::panic::{self, Location, UnwindSafe};
use std::process::{Command, Output};
use std::str::FromStr;
use std::sync::{Arc, OnceLock};
use std::thread;

use cargo_metadata::camino::Utf8PathBuf;

use crate::IntoResult;

/// The body of the `#[nvimo::plugin]` generated by the `#[nvimo::test]`
/// macro.
pub fn plugin_body<F, R>(test_body: F)
where
    F: FnOnce() -> R + UnwindSafe,
    R: IntoResult<()>,
    R::Error: fmt::Debug,
{
    let panic_info: Arc<OnceLock<PanicInfo>> = Arc::default();

    panic::set_hook({
        let panic_info = panic_info.clone();
        Box::new(move |info| {
            let _ = panic_info.set(info.into());
        })
    });

    let result = panic::catch_unwind(|| test_body().into_result())
        .map_err(|_| panic_info.get().unwrap().clone());

    exit(&result.into());
}

/// The body of the `#[nvimo::plugin]` generated by the `#[nvimo::test]`
/// macro when the `test-terminator` feature is enabled and the test function
/// takes a `TestTerminator` argument.
#[cfg(feature = "test-terminator")]
pub fn plugin_body_with_terminator<F>(test_body: F)
where
    F: FnOnce(super::terminator::TestTerminator),
{
    let result = Arc::new(OnceLock::<TestResult>::new());

    let handle =
        crate::libuv::AsyncHandle::new({
            let result = result.clone();
            move || {
                let result = result.clone();
                crate::schedule(move |()| {
                    exit(result.get().expect(
                        "AsyncHandle triggered before setting TestResult",
                    ))
                });
                Ok::<_, std::convert::Infallible>(())
            }
        })
        .unwrap();

    test_body(super::terminator::TestTerminator { handle, result });
}

/// The body of the `#[test]` generated by the `#[nvimo::test]` macro.
pub fn test_body(
    manifest_path: &str,
    plugin_name: &str,
    extra_cmd: Option<&str>,
) -> Result<(), impl fmt::Debug> {
    let Output { status, stdout, mut stderr } =
        run_nvim_command(manifest_path, plugin_name, extra_cmd)?
            .output()
            .map_err(ExpandedTestError::NeovimProcessFailed)?;

    // Re-emit stdout exactly as received.
    if !stdout.is_empty() {
        print!("{}", String::from_utf8_lossy(&stdout));
    }

    // Extract the test result from stderr.
    let Some(test_result) = TestResult::extract_from_stderr(&mut stderr)
    else {
        assert!(!status.success());
        return Err(status
            .code()
            .map(ExpandedTestError::NeovimExitedWithCode)
            .unwrap_or(ExpandedTestError::NeovimSegfaulted));
    };

    // Re-emit the rest of stderr.
    if !stderr.is_empty() {
        eprint!("{}", String::from_utf8_lossy(&stderr));
    }

    match test_result {
        TestResult::Passed => {
            assert!(status.success());
            Ok(())
        },

        TestResult::Errored(error_msg) => {
            Err(ExpandedTestError::TestErrored(error_msg))
        },

        TestResult::Panicked(panic_info) => {
            panic::set_hook(Box::new(move |info| {
                let mut info = info
                    .payload()
                    .downcast_ref::<PanicInfo>()
                    .cloned()
                    .unwrap_or_else(|| info.into());

                if let Some(thread) = thread::current().name()
                    && !thread.is_empty()
                {
                    info.thread = thread.to_owned();
                }

                eprintln!("\n{info}");
            }));

            panic::panic_any(panic_info)
        },
    }
}

#[doc(hidden)]
pub enum ExpandedTestError {
    CouldntReadManifest(super::build::BuildError),
    CouldntReadProfileEnvVar(env::VarError),
    LibraryNotFound(Utf8PathBuf),
    NeovimExitedWithCode(i32),
    NeovimProcessFailed(io::Error),
    NeovimSegfaulted,
    TestErrored(String),
}

pub(super) enum TestResult {
    Passed,
    Errored(String),
    Panicked(PanicInfo),
}

#[derive(Clone)]
pub(crate) struct PanicInfo {
    msg: String,
    thread: String,
    file: Option<String>,
    line: Option<u32>,
    column: Option<u32>,
}

impl TestResult {
    const FENCE_START: &str = "__NVIMO_TEST_RESULT_START__";
    const FENCE_END: &str = "__NVIMO_TEST_RESULT_END__";

    const PASSED_PREFIX: &str = "passed";
    const ERRORED_PREFIX: &str = "errored";
    const PANICKED_PREFIX: &str = "panicked";

    fn embed_in_stderr(&self, stderr: &mut io::Stderr) {
        write!(
            stderr,
            "{fence_start}{self}{fence_end}",
            fence_start = Self::FENCE_START,
            fence_end = Self::FENCE_END,
        )
        .expect("couldn't write TestResult to stderr");
    }

    fn extract_from_stderr(stderr: &mut Vec<u8>) -> Option<Self> {
        let fence_start = stderr
            .windows(Self::FENCE_START.len())
            .position(|window| window == Self::FENCE_START.as_bytes())?;

        let fence_end = fence_start
            + stderr[fence_start..]
                .windows(Self::FENCE_END.len())
                .position(|window| window == Self::FENCE_END.as_bytes())?;

        let this = str::from_utf8(
            &stderr[fence_start + Self::FENCE_START.len()..fence_end],
        )
        .ok()?
        .parse()
        .ok()?;

        stderr.drain(fence_start..fence_end + Self::FENCE_END.len());

        Some(this)
    }
}

impl fmt::Debug for ExpandedTestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CouldntReadManifest(err) => {
                write!(f, "couldn't read manifest: {err}")
            },
            Self::CouldntReadProfileEnvVar(err) => {
                write!(f, "couldn't read profile env var: {err}")
            },
            Self::LibraryNotFound(path) => {
                write!(
                    f,
                    "couldn't find library at '{path}'. Did you forget to \
                     use the build script?"
                )
            },
            Self::NeovimExitedWithCode(code) => {
                write!(f, "Neovim exited with code {code}")
            },
            Self::NeovimProcessFailed(err) => {
                write!(f, "Neovim process failed: {err}")
            },
            Self::NeovimSegfaulted => write!(f, "Neovim segfaulted"),
            Self::TestErrored(err) => write!(f, "{err}"),
        }
    }
}

impl fmt::Display for TestResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Passed => write!(f, "{}", Self::PASSED_PREFIX),
            Self::Errored(msg) => write!(f, "{}{msg}", Self::ERRORED_PREFIX),
            Self::Panicked(info) => {
                write!(f, "{}{info:?}", Self::PANICKED_PREFIX)
            },
        }
    }
}

impl FromStr for TestResult {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(empty) = s.strip_prefix(Self::PASSED_PREFIX) {
            empty.is_empty().then_some(Self::Passed).ok_or(())
        } else if let Some(info) = s.strip_prefix(Self::PANICKED_PREFIX) {
            info.parse().map(Self::Panicked)
        } else if let Some(msg) = s.strip_prefix(Self::ERRORED_PREFIX) {
            Ok(Self::Errored(msg.to_owned()))
        } else {
            Err(())
        }
    }
}

impl<T: fmt::Debug> From<Result<Result<(), T>, PanicInfo>> for TestResult {
    fn from(result: Result<Result<(), T>, PanicInfo>) -> Self {
        match result {
            Ok(Ok(())) => Self::Passed,
            Ok(Err(err)) => Self::Errored(format!("{err:?}")),
            Err(panic_info) => Self::Panicked(panic_info),
        }
    }
}

#[cfg(feature = "test-terminator")]
impl<T: fmt::Debug> From<Result<(), super::terminator::TestFailure<'_, T>>>
    for TestResult
{
    fn from(
        result: Result<(), super::terminator::TestFailure<'_, T>>,
    ) -> Self {
        match result {
            Ok(()) => Self::Passed,
            Err(super::terminator::TestFailure::Error(err)) => {
                Self::Errored(format!("{err:?}"))
            },
            Err(super::terminator::TestFailure::Panic(infos)) => {
                Self::Panicked(infos.into())
            },
        }
    }
}

fn exit(result: &TestResult) {
    let exec = |cmd: &str| {
        let opts = crate::api::opts::ExecOpts::builder().output(false).build();
        crate::api::exec2(cmd, &opts).unwrap();
    };

    result.embed_in_stderr(&mut io::stderr());

    if matches!(result, TestResult::Passed) {
        exec("qall!");
    } else {
        exec("cquit 1");
    }
}

fn run_nvim_command(
    manifest_path: &str,
    plugin_name: &str,
    extra_cmd: Option<&str>,
) -> Result<Command, ExpandedTestError> {
    let manifest = super::build::CargoManifest::from_path(manifest_path)
        .map_err(ExpandedTestError::CouldntReadManifest)?;

    let profile = env::var(manifest.profile_env())
        .map_err(ExpandedTestError::CouldntReadProfileEnvVar)?;

    let library_path = manifest.library_path(&profile);

    if !library_path.exists() {
        return Err(ExpandedTestError::LibraryNotFound(library_path));
    }

    let load_library = format!(
        "lua local f = package.loadlib([[{library_path}]], \
         'luaopen_{plugin_name}'); f()",
    );

    let mut command = Command::new("nvim");

    command
        .args(["-u", "NONE", "--headless"])
        .args(["-i", "NONE"])
        .args(["-c", "set noswapfile"])
        .args(extra_cmd.map(|cmd| ["-c", cmd]).unwrap_or_default())
        .args(["-c", &load_library]);

    Ok(command)
}

impl fmt::Display for PanicInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "thread '{}' panicked", self.thread)?;

        if let Some(file) = &self.file {
            write!(f, " at {file}")?;

            if let (Some(line), Some(col)) = (self.line, self.column) {
                write!(f, ":{line}:{col}")?;
            }
        }

        write!(f, ":\n{}", self.msg)?;

        Ok(())
    }
}

impl fmt::Debug for PanicInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "panic:{}", self.msg)?;

        write!(f, "\nthread:{}", self.thread)?;

        if let Some(file) = &self.file {
            write!(f, "\nfile:{file}")?;
        }

        if let Some(line) = self.line {
            write!(f, "\nline:{line}")?;
        }

        if let Some(column) = self.column {
            write!(f, "\ncolumn:{column}")?;
        }

        Ok(())
    }
}

impl FromStr for PanicInfo {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut info = PanicInfo {
            msg: String::new(),
            thread: String::new(),
            file: None,
            line: None,
            column: None,
        };

        let (_, s) = s.split_once("panic:").ok_or(())?;

        let (msg, s) = s.split_once("thread:").ok_or(())?;
        info.msg = msg.trim().to_owned();

        let (thread, s) = s.split_once("file:").ok_or(())?;
        info.thread = thread.trim().to_owned();

        let (file, s) = s.split_once("line:").ok_or(())?;
        info.file = Some(file.trim().to_owned());

        let (line, s) = s.split_once("column:").ok_or(())?;
        info.line = Some(line.trim().parse().map_err(|_| ())?);

        let column = s.trim().parse().map_err(|_| ())?;
        info.column = Some(column);

        Ok(info)
    }
}

impl From<&panic::PanicHookInfo<'_>> for PanicInfo {
    fn from(info: &panic::PanicHookInfo) -> Self {
        let payload = info.payload();

        let msg = downcast_display::<&str>(payload)
            .or_else(|| downcast_display::<String>(payload))
            .or_else(|| downcast_display::<&String>(payload))
            .map(ToString::to_string)
            .unwrap_or_default();

        let current_thread = thread::current();

        let thread = match current_thread.name() {
            Some(name) if !name.is_empty() => name,
            _ => "<unnamed>",
        };

        Self {
            msg,
            thread: thread.to_owned(),
            file: info.location().map(|l| l.file().to_owned()),
            line: info.location().map(Location::line),
            column: info.location().map(Location::column),
        }
    }
}

fn downcast_display<T: Any + fmt::Display>(
    value: &dyn Any,
) -> Option<&dyn fmt::Display> {
    value.downcast_ref::<T>().map(|msg| msg as &dyn fmt::Display)
}