use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::{env, fs};
use serde_json::{Value, json};
fn binary() -> Command {
Command::new(env!("CARGO_BIN_EXE_elsmith"))
}
fn send(input: &mut impl Write, bytes: &[u8]) {
write!(input, "Content-Length: {}\r\n\r\n", bytes.len()).unwrap();
input.write_all(bytes).unwrap();
}
fn responses(mut bytes: &[u8]) -> Vec<Value> {
let mut messages = Vec::new();
while !bytes.is_empty() {
let separator = bytes.windows(4).position(|w| w == b"\r\n\r\n").unwrap();
let header = str::from_utf8(&bytes[..separator]).unwrap();
let length = header
.strip_prefix("Content-Length: ")
.unwrap()
.parse()
.unwrap();
let (body, rest) = bytes[separator + 4..].split_at(length);
messages.push(serde_json::from_slice(body).unwrap());
bytes = rest;
}
messages
}
fn shell() -> PathBuf {
let path = env::var_os("PATH").unwrap_or_default();
std::iter::once(PathBuf::from("/bin/sh"))
.chain(env::split_paths(&path).map(|dir| dir.join("sh")))
.find(|path| path.is_absolute() && path.is_file())
.expect("the test needs a POSIX shell for its fake Emacs")
}
fn gzip(text: &str) -> Vec<u8> {
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(text.as_bytes()).unwrap();
encoder.finish().unwrap()
}
const SEQ: &str = "(defun fake-filter (pred sequence)\n \"Keep elements of SEQUENCE matching PRED.\"\n (delq nil (mapcar pred sequence)))\n(defun fake-autoloaded (x) x)\n(provide 'fake-seq)\n";
struct Install {
_temp: tempfile::TempDir,
root: PathBuf,
emacs: PathBuf,
lisp: PathBuf,
logs: PathBuf,
cache: PathBuf,
config: PathBuf,
workspace: PathBuf,
}
impl Install {
fn new() -> Self {
let temp = tempfile::tempdir().unwrap();
let root = fs::canonicalize(temp.path()).unwrap();
let share = root.join("install/share/emacs/31.1");
let lisp = share.join("lisp");
fs::create_dir_all(lisp.join("emacs-lisp")).unwrap();
fs::create_dir_all(share.join("src")).unwrap();
fs::write(lisp.join("emacs-lisp/fake-seq.el.gz"), gzip(SEQ)).unwrap();
fs::write(
lisp.join("subr.el"),
"(defmacro when (cond &rest body)\n \"If COND yields non-nil, do BODY.\"\n (list 'if cond (cons 'progn body)))\n",
)
.unwrap();
fs::write(
share.join("src/data.c"),
"#include <config.h>\n\nDEFUN (\"car\", Fcar, Scar, 1, 1, 0,\n doc: /* Return the car of LIST. */)\n",
)
.unwrap();
let logs = root.join("logs");
fs::create_dir_all(&logs).unwrap();
let lisp_text = lisp.display().to_string();
let function = |name: &str,
kind: &str,
usage: &str,
doc: &str,
file: &str,
autoload: bool| {
json!({"name": name, "kind": kind, "usage": usage, "doc": doc, "file": file, "autoload": autoload, "alias": null})
};
let catalog = json!({
"schema": 2,
"version": "31.1",
"lispDirectory": lisp_text,
"dataDirectory": share.join("etc"),
"sourceDirectory": null,
"loadPath": [lisp_text, lisp.join("emacs-lisp")],
"features": ["subr"],
"loadedDuringExtraction": [],
"functions": [
function("fake-filter", "function", "(fake-filter PRED SEQUENCE)", "Keep elements of SEQUENCE matching PRED.", &format!("{lisp_text}/emacs-lisp/fake-seq.elc"), false),
function("fake-autoloaded", "function", "(fake-autoloaded X)", "Autoloaded.", "emacs-lisp/fake-seq", true),
function("car", "subr", "(car LIST)", "Return the car of LIST.", "src/data.c", false),
function("mapcar", "subr", "(mapcar FUNCTION SEQUENCE)", "Apply FUNCTION to each element of SEQUENCE.", "src/fns.c", false),
function("when", "macro", "(when COND &rest BODY)", "If COND yields non-nil, do BODY.", &format!("{lisp_text}/subr.elc"), false),
function("if", "special-form", "(if COND THEN ELSE...)", "If COND yields non-nil, do THEN.", "src/eval.c", false),
],
"variables": [
{"name": "load-path", "special": true, "constant": false, "doc": "List of directories.", "file": "src/lread.c"},
],
});
let text = serde_json::to_string(&catalog).unwrap();
assert!(!text.contains('\''));
let logs_text = logs.display();
let emacs = root.join("install/bin/emacs");
fs::create_dir_all(emacs.parent().unwrap()).unwrap();
fs::write(
&emacs,
format!(
"#!{}\nprintf '%s\\n' \"$@\" > '{logs_text}/args.txt'\nexport -p > '{logs_text}/env.txt'\nprintf '%s\\n' \"$PWD\" > '{logs_text}/cwd.txt'\nprintf '%s\\n' * > '{logs_text}/listing.txt'\nprintf x >> '{logs_text}/count.txt'\nprintf '%s' '{text}' > catalog.json\n",
shell().display()
),
)
.unwrap();
fs::set_permissions(&emacs, fs::Permissions::from_mode(0o755)).unwrap();
let workspace = root.join("workspace");
fs::create_dir_all(&workspace).unwrap();
fs::write(
workspace.join("sibling.el"),
"(defun sibling-old (x) x)\n(provide 'sibling)\n",
)
.unwrap();
fs::write(
workspace.join("disk.el"),
"(defun disk-only (x)\n \"Only on disk.\"\n x)\n(provide 'disk)\n",
)
.unwrap();
Self {
root: root.clone(),
emacs,
lisp,
logs,
cache: root.join("cache"),
config: root.join("config"),
workspace,
_temp: temp,
}
}
fn command(&self) -> Command {
let mut command = binary();
command
.env("PATH", "")
.env("XDG_CACHE_HOME", &self.cache)
.env("ELSMITH_CONFIG_DIR", &self.config)
.env("EMACSLOADPATH", "/should/not/leak")
.current_dir(&self.root);
command
}
fn session(&self, emacs: Option<&Path>, messages: &[Value]) -> (Output, Vec<Value>) {
self.session_with_path(emacs, Path::new(""), messages)
}
fn session_with_path(
&self,
emacs: Option<&Path>,
path: &Path,
messages: &[Value],
) -> (Output, Vec<Value>) {
let mut command = self.command();
command
.env("PATH", path)
.args(["server", "run-server", "--debug"]);
if let Some(emacs) = emacs {
command.arg("--emacs").arg(emacs);
}
let mut child = command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
{
let mut input = child.stdin.take().unwrap();
for message in messages {
send(&mut input, &serde_json::to_vec(message).unwrap());
}
}
let output = child.wait_with_output().unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let replies = responses(&output.stdout);
(output, replies)
}
fn main_session(&self, emacs: Option<&Path>, requests: &[(u32, &str, Value)]) -> Vec<Value> {
let main = self.uri("main.el");
let mut messages = initialize(
&self.workspace,
json!({"textDocument": {"hover": {"contentFormat": ["markdown"]}}}),
)
.to_vec();
messages.push(open(&main, MAIN));
messages.push(open(&self.uri("sibling.el"), SIBLING));
for (id, method, params) in requests {
let mut params = params.clone();
params["textDocument"] = json!({"uri": main});
messages.push(request(*id, method, params));
}
messages.extend(finish());
self.session(emacs, &messages).1
}
fn uri(&self, name: &str) -> String {
url::Url::from_file_path(self.workspace.join(name))
.unwrap()
.to_string()
}
}
const MAIN: &str = ";;; main.el --- Main -*- lexical-binding: t -*-\n(require 'fake-seq)\n(defun main-run (items)\n (fake-filter #'identity items)\n (car items)\n (mapcar #'1+ items)\n (when items (fake-autoloaded items))\n (sibling-new items)\n (disk-only items))\n";
const SIBLING: &str = "(defun sibling-new (x)\n \"New.\"\n x)\n(provide 'sibling)\n";
fn at(text: &str, needle: &str) -> Value {
let offset = text.find(needle).unwrap();
let line = text[..offset].matches('\n').count();
let column = offset - text[..offset].rfind('\n').map_or(0, |index| index + 1);
json!({"line": line, "character": column})
}
fn request(id: u32, method: &str, params: Value) -> Value {
json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
}
fn open(uri: &str, text: &str) -> Value {
json!({"jsonrpc": "2.0", "method": "textDocument/didOpen", "params": {"textDocument": {"uri": uri, "languageId": "emacs-lisp", "version": 1, "text": text}}})
}
fn initialize(root: &Path, capabilities: Value) -> [Value; 2] {
let uri = url::Url::from_directory_path(root).unwrap();
[
request(
1,
"initialize",
json!({"processId": null, "rootUri": uri.as_str(), "capabilities": capabilities}),
),
json!({"jsonrpc": "2.0", "method": "initialized", "params": {}}),
]
}
fn finish() -> [Value; 2] {
[
request(999, "shutdown", Value::Null),
json!({"jsonrpc": "2.0", "method": "exit"}),
]
}
fn by_id(replies: &[Value], id: u32) -> &Value {
let reply = replies.iter().find(|reply| reply["id"] == id).unwrap();
assert!(reply.get("error").is_none(), "{reply}");
&reply["result"]
}
fn range_text(uri: &str, range: &Value) -> String {
let path = url::Url::parse(uri).unwrap().to_file_path().unwrap();
let text = fs::read_to_string(path).unwrap();
let line = |key: &str| range[key]["line"].as_u64().unwrap() as usize;
let character = |key: &str| range[key]["character"].as_u64().unwrap() as usize;
let lines: Vec<&str> = text.split('\n').collect();
assert_eq!(line("start"), line("end"));
lines[line("start")][character("start")..character("end")].to_owned()
}
fn definition_at(needle: &str) -> Value {
json!({"position": at(MAIN, needle)})
}
#[test]
fn stdlib_el_gz_definitions_open_a_read_only_cache_copy() {
let install = Install::new();
let replies = install.main_session(
Some(&install.emacs),
&[
(
10,
"textDocument/definition",
definition_at("fake-filter #'"),
),
(
11,
"textDocument/definition",
definition_at("fake-autoloaded items"),
),
(12, "textDocument/definition", definition_at("fake-seq)")),
],
);
let stdlib = by_id(&replies, 10);
let target = stdlib[0]["uri"].as_str().unwrap();
let cached = url::Url::parse(target).unwrap().to_file_path().unwrap();
assert!(
cached.starts_with(install.cache.join("elsmith/stdlib")),
"{target}"
);
assert!(cached.ends_with("emacs-lisp/fake-seq.el"));
assert!(cached.starts_with(&install.cache));
assert_eq!(fs::read_to_string(&cached).unwrap(), SEQ);
assert_eq!(
fs::metadata(&cached).unwrap().permissions().mode() & 0o222,
0
);
assert_eq!(range_text(target, &stdlib[0]["range"]), "fake-filter");
let autoloaded = by_id(&replies, 11);
assert_eq!(autoloaded[0]["uri"].as_str().unwrap(), target);
assert_eq!(
range_text(target, &autoloaded[0]["range"]),
"fake-autoloaded"
);
let feature = by_id(&replies, 12);
assert_eq!(feature[0]["uri"].as_str().unwrap(), target);
assert_eq!(range_text(target, &feature[0]["range"]), "fake-seq");
assert!(install.lisp.join("emacs-lisp/fake-seq.el.gz").is_file());
}
#[test]
fn c_source_present_opens_the_defun() {
let install = Install::new();
let replies = install.main_session(
Some(&install.emacs),
&[
(10, "textDocument/definition", definition_at("car items")),
(11, "textDocument/hover", definition_at("car items")),
],
);
let c_source = by_id(&replies, 10);
let data_c = c_source[0]["uri"].as_str().unwrap();
assert!(
data_c.ends_with("/install/share/emacs/31.1/src/data.c"),
"{data_c}"
);
assert_eq!(range_text(data_c, &c_source[0]["range"]), "\"car\"");
let hover = by_id(&replies, 11)["contents"]["value"].as_str().unwrap();
assert!(
hover.contains("`src/data.c`") && !hover.contains("not installed"),
"{hover}"
);
}
#[test]
fn c_source_absent_gives_an_empty_definition_and_a_rich_hover() {
let install = Install::new();
let replies = install.main_session(
Some(&install.emacs),
&[
(10, "textDocument/definition", definition_at("mapcar #'")),
(11, "textDocument/hover", definition_at("mapcar #'")),
],
);
assert_eq!(by_id(&replies, 10), &json!([]));
let hover = by_id(&replies, 11)["contents"]["value"].as_str().unwrap();
assert!(hover.contains("(mapcar FUNCTION SEQUENCE)"), "{hover}");
assert!(hover.contains("Built-in function"), "{hover}");
assert!(hover.contains("source not installed"), "{hover}");
assert!(
hover.contains("Apply FUNCTION to each element of SEQUENCE."),
"{hover}"
);
}
#[test]
fn no_emacs_with_an_empty_path_still_serves_the_workspace() {
let install = Install::new();
let main = install.uri("main.el");
let doc = json!({"uri": main});
let mut messages = initialize(&install.workspace, json!({})).to_vec();
messages.push(open(&main, MAIN));
messages.push(request(
10,
"textDocument/hover",
json!({"textDocument": doc, "position": at(MAIN, "car items")}),
));
messages.push(request(
11,
"textDocument/definition",
json!({"textDocument": doc, "position": at(MAIN, "car items")}),
));
messages.push(request(
12,
"textDocument/definition",
json!({"textDocument": doc, "position": at(MAIN, "disk-only items")}),
));
messages.push(request(
13,
"textDocument/completion",
json!({"textDocument": doc, "position": {"line": 8, "character": 6}}),
));
messages.push(request(
14,
"textDocument/signatureHelp",
json!({"textDocument": doc, "position": {"line": 8, "character": 13}}),
));
messages.push(request(
15,
"textDocument/semanticTokens/full",
json!({"textDocument": doc}),
));
messages.extend(finish());
let (output, replies) = install.session(None, &messages);
let log = String::from_utf8_lossy(&output.stderr);
assert!(
log.contains("No Emacs catalog: Emacs was not found"),
"{log}"
);
assert!(by_id(&replies, 10).is_null());
assert!(by_id(&replies, 11).is_null());
assert_eq!(by_id(&replies, 12)[0]["uri"], install.uri("disk.el"));
let items = by_id(&replies, 13)["items"].as_array().unwrap();
assert!(items.iter().any(|item| item["label"] == "disk-only"));
let signature = by_id(&replies, 14);
assert_eq!(signature["signatures"][0]["label"], "(disk-only X)");
assert_eq!(signature["activeParameter"], 0);
assert!(!by_id(&replies, 15)["data"].as_array().unwrap().is_empty());
assert!(!install.cache.exists());
assert!(!install.logs.join("count.txt").exists());
}
#[test]
fn a_workspace_emacs_on_path_is_never_spawned() {
let install = Install::new();
let marker = install.root.join("spawned");
let workspace_emacs = install.workspace.join("emacs");
fs::write(
&workspace_emacs,
format!(
"#!{}\nprintf x > '{}'\n",
shell().display(),
marker.display()
),
)
.unwrap();
fs::set_permissions(&workspace_emacs, fs::Permissions::from_mode(0o755)).unwrap();
let main = install.uri("main.el");
let mut messages = initialize(&install.workspace, json!({})).to_vec();
messages.push(open(&main, MAIN));
messages.push(request(
10,
"textDocument/hover",
json!({"textDocument": {"uri": main}, "position": at(MAIN, "car items")}),
));
messages.extend(finish());
let (output, replies) = install.session_with_path(None, &install.workspace, &messages);
assert!(by_id(&replies, 10).is_null());
assert!(!marker.exists());
let log = String::from_utf8_lossy(&output.stderr);
assert!(log.contains("No Emacs catalog"), "{log}");
}
#[test]
fn the_extractor_runs_isolated_and_only_once() {
let install = Install::new();
install.main_session(
Some(&install.emacs),
&[(10, "textDocument/hover", definition_at("car items"))],
);
install.main_session(
Some(&install.emacs),
&[(10, "textDocument/hover", definition_at("car items"))],
);
let args = fs::read_to_string(install.logs.join("args.txt")).unwrap();
assert!(args.starts_with("-Q\n--batch\n-l\n"), "{args}");
let environment = fs::read_to_string(install.logs.join("env.txt")).unwrap();
for leaked in [
"EMACSLOADPATH",
"XDG_CACHE_HOME",
"ELSMITH_CONFIG_DIR",
"PATH=",
] {
assert!(
!environment.contains(leaked),
"{leaked} leaked: {environment}"
);
}
assert_eq!(
fs::read_to_string(install.logs.join("listing.txt")).unwrap(),
"*\n"
);
let cwd = fs::read_to_string(install.logs.join("cwd.txt")).unwrap();
assert!(
!cwd.trim().starts_with(install.root.to_str().unwrap()),
"{cwd}"
);
assert_eq!(
fs::read_to_string(install.logs.join("count.txt")).unwrap(),
"x"
);
}
#[test]
fn unsaved_buffers_override_disk_across_files() {
let install = Install::new();
let main = install.uri("main.el");
let sibling = install.uri("sibling.el");
let replies = install.main_session(
Some(&install.emacs),
&[
(10, "textDocument/definition", definition_at("sibling-new items")),
(11, "textDocument/definition", definition_at("disk-only items")),
(12, "textDocument/references", json!({"position": at(MAIN, "sibling-new items"), "context": {"includeDeclaration": true}})),
(13, "workspace/symbol", json!({"query": "sibling"})),
(14, "textDocument/completion", json!({"position": {"line": 8, "character": 6}})),
],
);
assert_eq!(
by_id(&replies, 10),
&json!([{"uri": sibling, "range": {"start": {"line": 0, "character": 7}, "end": {"line": 0, "character": 18}}}])
);
assert_eq!(by_id(&replies, 11)[0]["uri"], install.uri("disk.el"));
let references: Vec<&str> = by_id(&replies, 12)
.as_array()
.unwrap()
.iter()
.map(|location| location["uri"].as_str().unwrap())
.collect();
assert_eq!(references, vec![main.as_str(), sibling.as_str()]);
let names: Vec<&str> = by_id(&replies, 13)
.as_array()
.unwrap()
.iter()
.map(|symbol| symbol["name"].as_str().unwrap())
.collect();
assert_eq!(names, vec!["sibling-new", "sibling"]);
let items = by_id(&replies, 14)["items"].as_array().unwrap();
assert!(items.iter().any(|item| item["label"] == "disk-only"));
}
#[test]
fn buffers_opened_through_a_symlink_or_an_escaped_uri_replace_the_index() {
let install = Install::new();
let link = install.root.join("link");
std::os::unix::fs::symlink(&install.workspace, &link).unwrap();
fs::write(
install.workspace.join("plus+file.el"),
"(defun plus-old () 1)\n",
)
.unwrap();
let sibling = url::Url::from_file_path(link.join("sibling.el"))
.unwrap()
.to_string();
let plus = url::Url::from_file_path(link.join("plus+file.el"))
.unwrap()
.to_string()
.replace('+', "%2B");
let mut messages = initialize(&link, json!({})).to_vec();
messages.push(open(&sibling, SIBLING));
messages.push(open(&plus, "(defun plus-new () 2)\n"));
messages.push(request(
10,
"workspace/symbol",
json!({"query": "sibling-"}),
));
messages.push(request(11, "workspace/symbol", json!({"query": "plus-"})));
messages.extend(finish());
let (_, replies) = install.session(None, &messages);
let names = |id| -> Vec<(String, String)> {
by_id(&replies, id)
.as_array()
.unwrap()
.iter()
.map(|symbol| {
(
symbol["name"].as_str().unwrap().to_owned(),
symbol["location"]["uri"].as_str().unwrap().to_owned(),
)
})
.collect()
};
assert_eq!(names(10), vec![("sibling-new".to_owned(), sibling.clone())]);
assert_eq!(names(11), vec![("plus-new".to_owned(), plus.clone())]);
}
#[test]
fn local_declarations_do_not_hide_definitions_elsewhere() {
let install = Install::new();
let main = install.uri("main.el");
let text = format!(
"{MAIN}(declare-function sibling-new \"sibling\")\n(declare-function car \"data\")\n(defvar load-path)\n(defun main-more () (sibling-new 1) (car nil) load-path)\n"
);
let doc = json!({"uri": main});
let mut messages = initialize(&install.workspace, json!({})).to_vec();
messages.push(open(&main, &text));
messages.push(open(&install.uri("sibling.el"), SIBLING));
let call = |needle: &str| json!({"textDocument": doc, "position": at(&text, needle)});
messages.push(request(
10,
"textDocument/definition",
call("sibling-new 1"),
));
messages.push(request(11, "textDocument/definition", call("car nil")));
messages.push(request(
12,
"textDocument/declaration",
call("sibling-new 1"),
));
messages.push(request(13, "textDocument/definition", call("load-path)\n")));
messages.extend(finish());
let (_, replies) = install.session(Some(&install.emacs), &messages);
assert_eq!(by_id(&replies, 10)[0]["uri"], install.uri("sibling.el"));
assert!(
by_id(&replies, 11)[0]["uri"]
.as_str()
.unwrap()
.ends_with("src/data.c")
);
let declaration = by_id(&replies, 12);
assert_eq!(declaration[0]["uri"], main);
assert_eq!(declaration[0]["range"]["start"]["line"], 9);
let variable = by_id(&replies, 13);
assert_eq!(variable[0]["uri"], main);
assert_eq!(variable[0]["range"]["start"]["line"], 11);
}
#[test]
fn require_edits_follow_the_client_capability_and_the_cache_is_reused() {
let install = Install::new();
let main = install.uri("main.el");
let doc = json!({"uri": main});
let item = |edits: bool| {
let capabilities = if edits {
json!({"textDocument": {"completion": {"completionItem": {"resolveSupport": {"properties": ["additionalTextEdits"]}}}}})
} else {
json!({})
};
let mut messages = initialize(&install.workspace, capabilities).to_vec();
messages.push(open(&main, MAIN));
messages.push(request(
10,
"textDocument/completion",
json!({"textDocument": doc, "position": {"line": 8, "character": 6}}),
));
messages.extend(finish());
let (_, replies) = install.session(Some(&install.emacs), &messages);
let completion = by_id(&replies, 10);
let disk = completion["items"]
.as_array()
.unwrap()
.iter()
.find(|item| item["label"] == "disk-only")
.unwrap()
.clone();
let mut messages = initialize(&install.workspace, if edits {
json!({"textDocument": {"completion": {"completionItem": {"resolveSupport": {"properties": ["additionalTextEdits"]}}}}})
} else {
json!({})
})
.to_vec();
messages.push(open(&main, MAIN));
messages.push(request(11, "completionItem/resolve", disk));
messages.extend(finish());
let (_, replies) = install.session(Some(&install.emacs), &messages);
by_id(&replies, 11).clone()
};
let with_edits = item(true);
assert_eq!(
with_edits["additionalTextEdits"],
json!([{"range": {"start": {"line": 1, "character": 19}, "end": {"line": 1, "character": 19}}, "newText": "\n(require 'disk)"}])
);
assert!(
with_edits["documentation"]["value"]
.as_str()
.unwrap()
.contains("Only on disk.")
);
let without = item(false);
assert!(without.get("additionalTextEdits").is_none(), "{without}");
assert_eq!(
fs::read_to_string(install.logs.join("count.txt")).unwrap(),
"x"
);
}
#[test]
fn catalog_commands_build_show_and_report_missing_emacs() {
let install = Install::new();
let run = |args: &[&str]| install.command().args(args).output().unwrap();
let missing = run(&["catalog", "show-catalog"]);
assert_eq!(missing.status.code(), Some(254));
let emacs = install.emacs.to_str().unwrap();
let absent = run(&["catalog", "show-catalog", "--emacs", emacs]);
assert_eq!(absent.status.code(), Some(254));
let built = run(&["catalog", "build-catalog", "--emacs", emacs]);
assert!(
built.status.success(),
"{}",
String::from_utf8_lossy(&built.stderr)
);
let built: Value = serde_json::from_slice(&built.stdout).unwrap();
assert_eq!(built["Cached"], false);
assert_eq!(built["Functions"], 6);
assert_eq!(built["Subrs"], 2);
let again: Value =
serde_json::from_slice(&run(&["catalog", "build-catalog", "--emacs", emacs]).stdout)
.unwrap();
assert_eq!(again["Cached"], true);
let shown = run(&["catalog", "show-catalog", "--emacs", emacs]);
assert!(shown.status.success());
let shown: Value = serde_json::from_slice(&shown.stdout).unwrap();
assert_eq!(shown["CacheFile"], built["CacheFile"]);
assert_eq!(
fs::read_to_string(install.logs.join("count.txt")).unwrap(),
"x"
);
let forced = run(&["catalog", "build-catalog", "--emacs", emacs, "--force"]);
assert!(forced.status.success());
assert_eq!(
fs::read_to_string(install.logs.join("count.txt")).unwrap(),
"xx"
);
let relative = run(&["catalog", "build-catalog", "--emacs", "emacs"]);
assert_eq!(relative.status.code(), Some(254));
}
fn system_emacs() -> Option<PathBuf> {
let path = env::var_os("PATH")?;
env::split_paths(&path)
.filter(|dir| dir.is_absolute())
.map(|dir| dir.join("emacs"))
.find(|candidate| candidate.is_file())
}
#[test]
fn real_emacs_catalog_jumps_into_the_stdlib_cache() {
let Some(emacs) = system_emacs() else {
eprintln!("skipped: no emacs on PATH");
return;
};
let temp = tempfile::tempdir().unwrap();
let root = fs::canonicalize(temp.path()).unwrap();
let workspace = root.join("workspace");
fs::create_dir_all(&workspace).unwrap();
let text = ";;; real.el --- Real -*- lexical-binding: t -*-\n(defun real-run (items)\n (seq-filter #'identity items)\n (car items))\n";
let uri = url::Url::from_file_path(workspace.join("real.el"))
.unwrap()
.to_string();
let doc = json!({"uri": uri});
let mut messages = initialize(&workspace, json!({})).to_vec();
messages.push(open(&uri, text));
messages.push(request(
10,
"textDocument/definition",
json!({"textDocument": doc, "position": at(text, "seq-filter")}),
));
messages.push(request(
11,
"textDocument/definition",
json!({"textDocument": doc, "position": at(text, "car items")}),
));
messages.push(request(
12,
"textDocument/hover",
json!({"textDocument": doc, "position": at(text, "seq-filter")}),
));
messages.extend(finish());
let mut child = binary()
.args(["server", "run-server", "--emacs"])
.arg(&emacs)
.env("XDG_CACHE_HOME", root.join("cache"))
.env("ELSMITH_CONFIG_DIR", root.join("config"))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
{
let mut input = child.stdin.take().unwrap();
for message in &messages {
send(&mut input, &serde_json::to_vec(message).unwrap());
}
}
let output = child.wait_with_output().unwrap();
assert!(output.status.success());
let replies = responses(&output.stdout);
let seq = by_id(&replies, 10);
let target = seq[0]["uri"].as_str().unwrap();
let path = url::Url::parse(target).unwrap().to_file_path().unwrap();
assert!(
path.starts_with(root.join("cache/elsmith/stdlib")),
"{target}"
);
assert!(path.ends_with("emacs-lisp/seq.el"));
assert_eq!(range_text(target, &seq[0]["range"]), "seq-filter");
let car = by_id(&replies, 11);
let lisp = fs::canonicalize(&emacs)
.unwrap()
.parent()
.unwrap()
.join("../share/emacs");
let has_c_source = fs::read_dir(&lisp)
.ok()
.into_iter()
.flatten()
.flatten()
.any(|entry| entry.path().join("src/data.c").is_file());
if has_c_source {
let data_c = car[0]["uri"].as_str().unwrap();
assert!(data_c.ends_with("/src/data.c"), "{data_c}");
assert_eq!(range_text(data_c, &car[0]["range"]), "\"car\"");
} else {
assert_eq!(car, &json!([]));
}
let hover = by_id(&replies, 12)["contents"]["value"].as_str().unwrap();
assert!(hover.contains("(seq-filter PRED SEQUENCE)"), "{hover}");
}