use std::fs;
use std::io;
use std::path::PathBuf;
use std::process::{Child, ChildStdin, Command, Stdio};
use std::time::{Duration, Instant};
use serde::Deserialize;
use serde_json::{Value, json};
use crate::navigation::Lines;
use crate::position::Encoding;
mod process;
pub use process::supervise;
pub(crate) struct Input {
pub emacs: PathBuf,
pub file: PathBuf,
pub load_paths: Vec<PathBuf>,
pub text: String,
pub form: Option<String>,
}
pub(crate) struct Job {
dir: tempfile::TempDir,
child: Child,
control: Option<ChildStdin>,
started: Instant,
}
impl Job {
pub fn start(input: &Input) -> io::Result<Self> {
let dir = tempfile::tempdir()?;
let source_dir = dir.path().join("source");
fs::create_dir(&source_dir)?;
let file = source_dir.join(
input
.file
.file_name()
.ok_or_else(|| io::Error::other("No source filename"))?,
);
fs::write(&file, input.text.replace("\r\n", "\n"))?;
fs::write(dir.path().join("pass.el"), include_str!("oracle/pass.el"))?;
let mut request = json!({"file": file, "loadPaths": input.load_paths});
if let Some(form) = &input.form {
request["form"] = json!(form);
}
fs::write(
dir.path().join("request.json"),
serde_json::to_vec(&request)?,
)?;
let mut child = Command::new(std::env::current_exe()?)
.arg("--elsmith-oracle")
.arg(&input.emacs)
.arg(std::process::id().to_string())
.current_dir(dir.path())
.env_clear()
.env("HOME", dir.path())
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?;
let control = child.stdin.take();
Ok(Self {
dir,
child,
control,
started: Instant::now(),
})
}
pub fn poll(&mut self) -> io::Result<Option<Value>> {
if self.started.elapsed() >= Duration::from_secs(10) {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"Emacs oracle timed out",
));
}
let Some(status) = self.child.try_wait()? else {
return Ok(None);
};
if !status.success() {
return Err(io::Error::other(format!(
"Emacs oracle exited with {status}"
)));
}
let result = fs::read(self.dir.path().join("result.json"))?;
let result: Value = serde_json::from_slice(&result)?;
if let Some(error) = result.get("error").and_then(Value::as_str) {
return Err(io::Error::other(error));
}
Ok(Some(result))
}
}
impl Drop for Job {
fn drop(&mut self) {
self.control.take();
let _ = self.child.wait();
}
}
#[derive(Deserialize)]
struct Finding {
source: String,
start: usize,
end: Option<usize>,
severity: u8,
message: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Report {
byte_compile: Vec<Finding>,
checkdoc: Vec<Finding>,
package_lint: PackageLint,
}
#[derive(Deserialize)]
struct PackageLint {
status: String,
findings: Vec<Finding>,
message: Option<String>,
}
impl Report {
pub fn package_status(&self) -> (&str, usize, Option<&str>) {
(
&self.package_lint.status,
self.package_lint.findings.len(),
self.package_lint.message.as_deref(),
)
}
pub fn diagnostics(self, text: &str, encoding: Encoding) -> Vec<Value> {
let lines = Lines::new(text, encoding);
let offsets: Vec<_> = text
.char_indices()
.filter_map(|(offset, c)| {
(!(c == '\r' && text[offset..].starts_with("\r\n"))).then_some(offset)
})
.chain(std::iter::once(text.len()))
.collect();
self.byte_compile
.into_iter()
.chain(self.checkdoc)
.chain(self.package_lint.findings)
.filter_map(|finding| {
let start = *offsets.get(finding.start)?;
let end = *offsets.get(
finding
.end
.unwrap_or((finding.start + 1).min(offsets.len() - 1)),
)?;
Some(json!({
"source": finding.source,
"severity": finding.severity,
"range": lines.range(start, end.max(start)),
"message": finding.message,
}))
})
.collect()
}
}