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;
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());
}
#[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 });
}
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)?;
if !stdout.is_empty() {
print!("{}", String::from_utf8_lossy(&stdout));
}
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));
};
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)
}