use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};
use serde::Deserialize;
use serde_json::{Value, json};
use crate::analysis::{Form, forms};
use crate::syntax::{Kind, Tree};
#[derive(Clone, Debug, Default, Deserialize)]
pub struct UserConfig {
#[serde(default)]
pub emacs_path: Option<PathBuf>,
#[serde(default)]
pub load_paths: Vec<PathBuf>,
}
impl UserConfig {
pub fn load(dir: &Path) -> Result<Self, String> {
match fs::read_to_string(dir.join("config.toml")) {
Ok(text) => toml::from_str(&text).map_err(|err| format!("config.toml: {err}")),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
Err(err) => Err(format!("config.toml: {err}")),
}
}
}
#[derive(Debug, Default, Deserialize)]
struct ProjectFile {
#[serde(default)]
load_paths: Vec<String>,
#[serde(default)]
ignored_paths: Vec<String>,
#[serde(flatten)]
other: toml::Table,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LoadPath {
pub path: PathBuf,
pub source: &'static str,
}
#[derive(Clone, Debug, Default)]
pub struct Environment {
pub root: PathBuf,
pub load_paths: Vec<LoadPath>,
pub ignored: Vec<PathBuf>,
pub notes: Vec<String>,
}
impl Environment {
pub fn json(&self) -> Value {
json!({
"Root": self.root,
"LoadPath": self.load_paths.iter().map(|entry| json!({"Path": entry.path, "Source": entry.source})).collect::<Vec<_>>(),
"Ignored": self.ignored,
"Notes": self.notes,
})
}
pub fn is_ignored(&self, path: &Path) -> bool {
self.ignored.iter().any(|ignored| path.starts_with(ignored))
}
}
fn strings(form: &Form, text: &str) -> Vec<String> {
match form {
Form::Atom {
kind: Kind::String,
start,
end,
} => vec![unquote(&text[*start..*end])],
Form::List { items, .. } => items
.iter()
.filter_map(|item| match item {
Form::Atom {
kind: Kind::String,
start,
end,
} => Some(unquote(&text[*start..*end])),
_ => None,
})
.collect(),
Form::Prefixed {
prefix: Kind::Quote,
inner: Some(inner),
..
} => strings(inner, text),
_ => Vec::new(),
}
}
fn unquote(literal: &str) -> String {
let body = literal
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.unwrap_or(literal);
let mut out = String::new();
let mut chars = body.chars();
while let Some(c) = chars.next() {
if c == '\\' {
match chars.next() {
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('\n') | None => {}
Some(other) => out.push(other),
}
} else {
out.push(c);
}
}
out
}
fn symbol<'a>(form: &Form, text: &'a str) -> Option<&'a str> {
match form {
Form::Atom {
kind: Kind::Symbol,
start,
end,
} => Some(&text[*start..*end]),
_ => None,
}
}
fn eask_load_paths(text: &str) -> Vec<String> {
let tree = Tree::parse_str(text);
let mut out = Vec::new();
for form in forms(&tree) {
let Form::List { items, .. } = &form else {
continue;
};
if let Some(head) = items.first().and_then(|head| symbol(head, text))
&& matches!(head, "load-path" | "load-paths")
{
for item in &items[1..] {
out.extend(strings(item, text));
}
}
}
out
}
const DIR_LOCAL_VARIABLES: &[&str] = &["elisp-flymake-byte-compile-load-path", "load-path"];
const DIR_LOCAL_MODES: &[&str] = &["nil", "emacs-lisp-mode", "lisp-data-mode", "prog-mode"];
fn dir_locals_load_paths(text: &str) -> Vec<String> {
let tree = Tree::parse_str(text);
let Some(first) = forms(&tree).into_iter().next() else {
return Vec::new();
};
let alist = match first {
Form::Prefixed {
prefix: Kind::Quote,
inner: Some(inner),
..
} => *inner,
other => other,
};
let Form::List { items: modes, .. } = alist else {
return Vec::new();
};
let mut out = Vec::new();
for entry in &modes {
let Form::List { items, .. } = entry else {
continue;
};
let Some(mode) = items.first().and_then(|mode| symbol(mode, text)) else {
continue;
};
if !DIR_LOCAL_MODES.contains(&mode) {
continue;
}
let variables: Vec<&Form> = match items.as_slice() {
[
_,
Form::Atom {
kind: Kind::Dot, ..
},
Form::List { items, .. },
] => items.iter().collect(),
[_, rest @ ..] => rest.iter().collect(),
[] => Vec::new(),
};
for variable in variables {
let Form::List { items: pair, .. } = variable else {
continue;
};
let Some(name) = pair.first().and_then(|name| symbol(name, text)) else {
continue;
};
if !DIR_LOCAL_VARIABLES.contains(&name) {
continue;
}
let value = match pair.as_slice() {
[
_,
Form::Atom {
kind: Kind::Dot, ..
},
value,
] => Some(value),
[_, value] => Some(value),
_ => None,
};
if let Some(value) = value {
out.extend(strings(value, text));
}
}
}
out
}
fn package_dirs(root: &Path, dot: &str, version: Option<&str>) -> Vec<PathBuf> {
let base = root.join(dot);
let Ok(entries) = fs::read_dir(&base) else {
return Vec::new();
};
let mut versions: Vec<PathBuf> = entries
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.filter(|path| path.join("elpa").is_dir())
.collect();
versions.sort();
versions.reverse();
if let Some(version) = version
&& let Some(exact) = versions
.iter()
.find(|path| path.file_name().is_some_and(|name| name == version))
.cloned()
{
versions = vec![exact];
} else {
versions.truncate(1);
}
let mut out = Vec::new();
for version in versions {
let Ok(packages) = fs::read_dir(version.join("elpa")) else {
continue;
};
let mut packages: Vec<PathBuf> = packages
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.filter(|path| {
path.is_dir()
&& path
.file_name()
.is_some_and(|name| name != "archives" && name != "gnupg")
})
.collect();
packages.sort();
out.extend(packages);
}
out
}
pub struct Inputs<'a> {
pub user: &'a UserConfig,
pub emacs_version: Option<&'a str>,
pub trusted: bool,
pub emacs_load_path: Option<OsString>,
}
pub fn resolve(root: &Path, inputs: &Inputs) -> Environment {
let root = fs::canonicalize(root).unwrap_or_else(|_| root.to_owned());
let mut env = Environment {
root: root.clone(),
..Environment::default()
};
let push = |env: &mut Environment, path: PathBuf, source: &'static str| {
let Ok(real) = fs::canonicalize(&path) else {
return;
};
if real.is_dir() && !env.load_paths.iter().any(|entry| entry.path == real) {
env.load_paths.push(LoadPath { path: real, source });
}
};
for path in &inputs.user.load_paths {
if path.is_absolute() {
push(&mut env, path.clone(), "config.toml");
} else {
env.notes.push(format!(
"config.toml load path is not absolute: {}",
path.display()
));
}
}
match fs::read_to_string(root.join("elsmith.toml")) {
Ok(text) => match toml::from_str::<ProjectFile>(&text) {
Ok(project) => {
for path in project.load_paths {
push(&mut env, root.join(path), "elsmith.toml");
}
for path in project.ignored_paths {
let path = root.join(path);
env.ignored.push(fs::canonicalize(&path).unwrap_or(path));
}
for key in project.other.keys() {
env.notes
.push(format!("elsmith.toml key `{key}` is ignored"));
}
}
Err(err) => env.notes.push(format!("elsmith.toml: {err}")),
},
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => env.notes.push(format!("elsmith.toml: {err}")),
}
for (file, dot) in [("Keg", ".keg"), ("Eask", ".eask"), ("Cask", ".cask")] {
let Ok(text) = fs::read_to_string(root.join(file)) else {
continue;
};
let source: &'static str = match file {
"Keg" => "Keg",
"Eask" => "Eask",
_ => "Cask",
};
if file == "Eask" {
for path in eask_load_paths(&text) {
push(&mut env, root.join(path), source);
}
}
for dir in package_dirs(&root, dot, inputs.emacs_version) {
push(&mut env, dir, source);
}
}
if let Ok(text) = fs::read_to_string(root.join(".dir-locals.el")) {
for path in dir_locals_load_paths(&text) {
push(&mut env, root.join(path), ".dir-locals.el");
}
}
push(&mut env, root.join("lisp"), "lisp");
push(&mut env, root.join("test"), "test");
push(&mut env, root.clone(), "root");
if inputs.trusted
&& let Some(paths) = &inputs.emacs_load_path
{
for path in std::env::split_paths(paths) {
if path.is_absolute() {
push(&mut env, path, "EMACSLOADPATH");
}
}
}
env
}
#[cfg(test)]
mod tests {
use super::*;
fn inputs(user: &UserConfig) -> Inputs<'_> {
Inputs {
user,
emacs_version: Some("31.1"),
trusted: false,
emacs_load_path: Some(OsString::from("/nonexistent")),
}
}
#[test]
fn resolves_static_load_paths_in_priority_order() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
for path in [
"extra",
"lisp",
"test",
"vendor",
"ignored",
".keg/31.1/elpa/dep-1.0",
".keg/30.1/elpa/old-1.0",
".eask/31.1/elpa/eask-dep-2.0",
"eask-lisp",
] {
fs::create_dir_all(root.join(path)).unwrap();
}
fs::write(
root.join("elsmith.toml"),
"load_paths = [\"extra\"]\nignored_paths = [\"ignored\"]\nemacs_path = \"./evil\"\ntrusted = true\n",
)
.unwrap();
fs::write(
root.join("Keg"),
"(source gnu)\n(package (name \"demo\"))\n",
)
.unwrap();
fs::write(
root.join("Eask"),
"(package \"demo\" \"1\" \"d\")\n(load-paths \"eask-lisp\")\n(eval (shell-command \"touch pwned\"))\n",
)
.unwrap();
fs::write(
root.join(".dir-locals.el"),
"((emacs-lisp-mode . ((elisp-flymake-byte-compile-load-path . (\"./\" \"vendor\"))\n (eval . (shell-command \"touch pwned\")))))\n",
)
.unwrap();
let user = UserConfig::default();
let env = resolve(root, &inputs(&user));
let real = fs::canonicalize(root).unwrap();
let listed: Vec<(String, &str)> = env
.load_paths
.iter()
.map(|entry| {
(
entry
.path
.strip_prefix(&real)
.unwrap()
.to_string_lossy()
.into_owned(),
entry.source,
)
})
.collect();
assert_eq!(
listed,
vec![
("extra".to_owned(), "elsmith.toml"),
(".keg/31.1/elpa/dep-1.0".to_owned(), "Keg"),
("eask-lisp".to_owned(), "Eask"),
(".eask/31.1/elpa/eask-dep-2.0".to_owned(), "Eask"),
(String::new(), ".dir-locals.el"),
("vendor".to_owned(), ".dir-locals.el"),
("lisp".to_owned(), "lisp"),
("test".to_owned(), "test"),
]
);
assert_eq!(env.ignored, vec![real.join("ignored")]);
assert!(env.notes.iter().any(|note| note.contains("emacs_path")));
assert!(env.notes.iter().any(|note| note.contains("trusted")));
assert!(!root.join("pwned").exists());
}
#[test]
fn emacs_load_path_requires_trust() {
let dir = tempfile::tempdir().unwrap();
let extra = tempfile::tempdir().unwrap();
let user = UserConfig::default();
let mut input = inputs(&user);
input.emacs_load_path = Some(extra.path().as_os_str().to_owned());
let untrusted = resolve(dir.path(), &input);
assert!(
untrusted
.load_paths
.iter()
.all(|entry| entry.source != "EMACSLOADPATH")
);
input.trusted = true;
let trusted = resolve(dir.path(), &input);
assert!(
trusted
.load_paths
.iter()
.any(|entry| entry.source == "EMACSLOADPATH")
);
}
}