use std::env;
use std::ffi::OsString;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use clap::error::ErrorKind;
use clap::{Parser, Subcommand, ValueEnum};
use elsmith::catalog::{self, Catalog};
use elsmith::project::UserConfig;
use elsmith::{elisp_header, lsp, trust};
use serde_json::{Value, json};
#[derive(Parser)]
#[command(
version,
about,
propagate_version = true,
disable_help_subcommand = true
)]
struct Cli {
#[arg(long, global = true, value_enum, default_value_t = Output::Json)]
output: Output,
#[arg(long, global = true)]
debug: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Clone, Copy, ValueEnum)]
enum Output {
Json,
Text,
Table,
}
#[derive(Subcommand)]
enum Command {
#[command(subcommand)]
Server(Server),
#[command(subcommand)]
Check(Check),
#[command(subcommand)]
Catalog(CatalogCommand),
#[command(subcommand)]
Trust(Trust),
}
#[derive(Subcommand)]
#[command(disable_help_subcommand = true)]
enum CatalogCommand {
BuildCatalog {
#[arg(long, value_name = "PATH")]
emacs: Option<PathBuf>,
#[arg(long)]
force: bool,
},
ShowCatalog {
#[arg(long, value_name = "PATH")]
emacs: Option<PathBuf>,
},
}
#[derive(Subcommand)]
#[command(disable_help_subcommand = true)]
enum Server {
RunServer {
#[arg(long, value_name = "PATH")]
emacs: Option<PathBuf>,
#[arg(long, value_name = "PATH")]
log_file: Option<PathBuf>,
},
}
#[derive(Subcommand)]
#[command(disable_help_subcommand = true)]
enum Check {
CheckFile {
#[arg(long, value_name = "PATH")]
file: PathBuf,
#[arg(long, value_name = "PATH")]
emacs: Option<PathBuf>,
},
}
#[derive(Subcommand)]
#[command(disable_help_subcommand = true)]
enum Trust {
ListRoots,
AddRoot {
#[arg(long, value_name = "DIR")]
path: PathBuf,
},
RemoveRoot {
#[arg(long, value_name = "DIR")]
path: PathBuf,
},
}
fn check_file(path: &Path, emacs: Option<&Path>) -> io::Result<Value> {
let text = fs::read_to_string(path)?;
let catalog = match locate(emacs) {
Ok(path) => catalog::cache_dir()
.ok()
.and_then(|cache| Catalog::cached(&path, &cache).ok().flatten()),
Err(err) if emacs.is_some() => return Err(err),
Err(_) => None,
};
Ok(json!({
"File": path.to_string_lossy(),
"LexicalBinding": elisp_header::lexical_cookie(&text).as_json(),
"Lines": text.lines().count(),
"Bytes": text.len(),
"Diagnostics": lsp::check_source(&text, catalog.as_ref()),
}))
}
fn summary(catalog: &Catalog, cache: &Path) -> Value {
let count = |kind: &str| {
catalog
.data
.functions
.iter()
.filter(|function| function.kind == kind)
.count()
};
json!({
"Emacs": catalog.emacs,
"Version": catalog.data.version,
"CacheFile": catalog.cache_file,
"StdlibDirectory": catalog.stdlib_dir(cache),
"Functions": catalog.data.functions.len(),
"Subrs": count("subr"),
"SpecialForms": count("special-form"),
"Macros": count("macro"),
"Autoloads": catalog.data.functions.iter().filter(|function| function.autoload).count(),
"Variables": catalog.data.variables.len(),
"Features": catalog.data.features.len(),
"Libraries": catalog.libraries().count(),
})
}
fn locate(emacs: Option<&Path>) -> io::Result<PathBuf> {
let configured = trust::config_dir()
.ok()
.and_then(|dir| UserConfig::load(&dir).ok())
.and_then(|config| config.emacs_path);
catalog::locate_emacs(emacs, configured.as_deref(), &[])
}
fn catalog_command(command: CatalogCommand) -> io::Result<Value> {
let cache = catalog::cache_dir()?;
match command {
CatalogCommand::BuildCatalog { emacs, force } => {
let emacs = locate(emacs.as_deref())?;
let built = Catalog::load_or_build(&emacs, &cache, force)?;
let mut value = summary(&built.catalog, &cache);
value["Cached"] = json!(built.cached);
value["DurationMs"] = json!(built.duration.as_millis() as u64);
Ok(value)
}
CatalogCommand::ShowCatalog { emacs } => {
let emacs = locate(emacs.as_deref())?;
let catalog = Catalog::cached(&emacs, &cache)?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!(
"No catalog for {}; run `elsmith catalog build-catalog`",
emacs.display()
),
)
})?;
Ok(summary(&catalog, &cache))
}
}
}
fn display(output: Output, value: Value) -> io::Result<()> {
let mut stdout = io::stdout().lock();
match output {
Output::Json => writeln!(stdout, "{}", serde_json::to_string_pretty(&value)?),
Output::Text | Output::Table => {
let fields = value.as_object().expect("CLI output is an object");
let width = fields.keys().map(String::len).max().unwrap_or(0);
if matches!(output, Output::Table) {
writeln!(stdout, "{:<width$} | Value", "Field")?;
writeln!(stdout, "{}-+------", "-".repeat(width))?;
}
for (key, value) in fields {
let text = value
.as_str()
.map_or_else(|| value.to_string(), str::to_owned);
if matches!(output, Output::Table) {
writeln!(stdout, "{key:<width$} | {text}")?;
} else {
writeln!(stdout, "{key}\t{text}")?;
}
}
Ok(())
}
}
}
fn parse() -> Result<Cli, clap::Error> {
let mut args: Vec<OsString> = env::args_os().collect();
match Cli::try_parse_from(&args) {
Err(err)
if matches!(
err.kind(),
ErrorKind::InvalidSubcommand | ErrorKind::UnknownArgument
) && args.last().is_some_and(|arg| arg == "help") =>
{
*args.last_mut().expect("a trailing help token was checked") = "--help".into();
Cli::try_parse_from(args)
}
result => result,
}
}
fn classify_cli_error(error: io::Error) -> (u8, io::Error) {
match error.kind() {
io::ErrorKind::InvalidInput | io::ErrorKind::NotFound | io::ErrorKind::InvalidData => {
(254, error)
}
_ => (255, error),
}
}
fn run(cli: Cli) -> Result<u8, (u8, io::Error)> {
let value = match cli.command {
Command::Server(Server::RunServer { emacs, log_file }) => {
let mut log: Box<dyn Write> = match log_file {
Some(path) => Box::new(
OpenOptions::new()
.create(true)
.append(true)
.open(path)
.map_err(|err| (255, err))?,
),
None if cli.debug => Box::new(io::stderr()),
None => Box::new(io::sink()),
};
let result = lsp::run(
io::BufReader::new(io::stdin()),
io::stdout().lock(),
&mut log,
lsp::Options { emacs },
)
.map_err(|err| (255, err))?;
return Ok(result as u8);
}
Command::Check(Check::CheckFile { file, emacs }) => {
check_file(&file, emacs.as_deref()).map_err(classify_cli_error)?
}
Command::Catalog(command) => catalog_command(command).map_err(classify_cli_error)?,
Command::Trust(action) => {
let dir = trust::config_dir().map_err(|err| (255, err))?;
let allowlist = match action {
Trust::ListRoots => trust::Allowlist::load(&dir),
Trust::AddRoot { path } => trust::Allowlist::add(&dir, &path),
Trust::RemoveRoot { path } => trust::Allowlist::remove(&dir, &path),
}
.map_err(classify_cli_error)?;
json!({"Roots": allowlist.roots()})
}
};
display(cli.output, value).map_err(|err| (255, err))?;
Ok(0)
}
fn main() -> ExitCode {
let mut args = env::args_os().skip(1);
if args.next().as_deref() == Some(std::ffi::OsStr::new("--elsmith-oracle")) {
let result = args.next().zip(args.next()).and_then(|(emacs, parent)| {
elsmith::oracle::supervise(&emacs, parent.to_str()?.parse().ok()?).ok()
});
return ExitCode::from(u8::from(result != Some(true)));
}
let cli = match parse() {
Ok(cli) => cli,
Err(err) => {
let code = match err.kind() {
ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => 0,
_ => 252,
};
let _ = err.print();
return ExitCode::from(code);
}
};
match run(cli) {
Ok(code) => ExitCode::from(code),
Err((code, err)) => {
eprintln!("elsmith: {err}");
ExitCode::from(code)
}
}
}