use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context as _, Result};
use openmoat_hosts::{Host, McpCommandForm, McpFile, McpReader, McpSyntax};
use serde_json::{Map, Value};
use toml_edit::{DocumentMut, Item};
use crate::home::{Home, user_home};
use crate::install::HostConfig;
#[derive(Debug, Clone)]
pub struct Source {
pub host: Host,
pub path: PathBuf,
pub reader: &'static dyn McpReader,
pub user: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Server {
pub id: String,
pub host: Host,
pub file: PathBuf,
pub pointer: String,
pub name: String,
pub entry: Value,
pub form: McpCommandForm,
pub runs_in_host: bool,
}
#[derive(Debug, Default)]
pub struct Scan {
pub servers: Vec<Server>,
pub unreadable: Vec<(PathBuf, String)>,
pub scanned: Vec<PathBuf>,
pub provenance: std::collections::BTreeMap<String, super::provenance::Provenance>,
}
pub fn sources(home: &Home, host: Host, cwd: Option<&Path>) -> Result<Vec<Source>> {
let Some(mcp) = &host.spec().mcp else {
return Ok(Vec::new());
};
let mut out: Vec<Source> = user_files(home, host, mcp.user_file)?
.into_iter()
.map(|path| Source {
host,
path,
reader: mcp.user_reader,
user: true,
})
.collect();
if let Some(cwd) = cwd
&& !mcp.project_files.is_empty()
{
for dir in project_dirs(cwd)? {
for (relative, reader) in mcp.project_files {
out.push(Source {
host,
path: dir.join(relative),
reader: *reader,
user: false,
});
}
}
}
Ok(out)
}
fn user_files(home: &Home, host: Host, file: McpFile) -> Result<Vec<PathBuf>> {
let config = HostConfig::for_host(home, host)?;
Ok(match file {
McpFile::HookFile => vec![config.settings_path],
McpFile::BesideHookFile(name) => vec![config.settings_path.with_file_name(name)],
McpFile::InConfigDir(name) => vec![config.dir().join(name)],
McpFile::EachInConfigDir(names) => names.iter().map(|n| config.dir().join(n)).collect(),
McpFile::BesideDefaultDir(name) => {
let user = user_home()?;
let default = host.spec().install.as_ref().map(|i| user.join(i.dir_name));
let inside = config.dir().join(name);
if default.is_some_and(|d| config.dir() == d) {
vec![user.join(name), inside]
} else {
vec![inside]
}
}
})
}
fn project_dirs(cwd: &Path) -> Result<Vec<PathBuf>> {
let (cwd, home) = (resolved(cwd), resolved(&user_home()?));
let cwd = cwd.as_path();
let Some(root) = crate::project::root_of(cwd, &home) else {
return Ok(Vec::new());
};
Ok(cwd
.ancestors()
.take_while(|dir| dir.starts_with(&root))
.map(Path::to_path_buf)
.collect())
}
fn resolved(path: &Path) -> PathBuf {
if cfg!(unix) {
std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
} else {
path.to_path_buf()
}
}
pub fn scan(sources: &[Source]) -> Scan {
let mut found = Scan::default();
for source in sources {
found.scanned.push(source.path.clone());
let text = match fs::read_to_string(&source.path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => {
found.unreadable.push((source.path.clone(), e.to_string()));
continue;
}
};
match parse(source, &text) {
Ok(servers) => found.servers.extend(servers),
Err(e) => found
.unreadable
.push((source.path.clone(), format!("{e:#}"))),
}
}
found
}
pub fn parse(source: &Source, text: &str) -> Result<Vec<Server>> {
let doc = match source.reader.syntax() {
McpSyntax::Json if text.trim().is_empty() => Value::Object(Map::new()),
McpSyntax::Json => serde_json::from_str(text).context("parsing JSON")?,
McpSyntax::Toml => {
let doc: DocumentMut = text.parse().context("parsing TOML")?;
toml_to_json(doc.as_item())
}
McpSyntax::Json5 => {
crate::install::json5_file::parse_or_empty(text)
.context("parsing JSON5")?
.value
}
McpSyntax::Yaml => openmoat_hosts::yaml_hooks::parse(text)
.map_err(anyhow::Error::msg)
.context("parsing YAML")?,
};
let servers = source.reader.servers(&doc).map_err(anyhow::Error::msg)?;
Ok(servers
.into_iter()
.map(|server| Server {
id: format!("{}#{}", source.path.display(), server.pointer),
host: source.host,
file: source.path.clone(),
pointer: server.pointer,
name: server.name,
runs_in_host: source.reader.runs_in_host(&server.entry),
entry: server.entry,
form: source.reader.command_form(),
})
.collect())
}
pub fn toml_to_json(item: &Item) -> Value {
match item {
Item::None => Value::Null,
Item::Value(value) => toml_value(value),
Item::Table(table) => Value::Object(
table
.iter()
.map(|(k, v)| (k.to_owned(), toml_to_json(v)))
.collect(),
),
Item::ArrayOfTables(tables) => Value::Array(
tables
.iter()
.map(|t| toml_to_json(&Item::Table(t.clone())))
.collect(),
),
}
}
fn toml_value(value: &toml_edit::Value) -> Value {
use toml_edit::Value as T;
match value {
T::String(s) => Value::String(s.value().clone()),
T::Integer(i) => Value::from(*i.value()),
T::Float(f) => serde_json::Number::from_f64(*f.value())
.map_or_else(|| Value::String(f.value().to_string()), Value::Number),
T::Boolean(b) => Value::Bool(*b.value()),
T::Datetime(d) => Value::String(d.value().to_string()),
T::Array(items) => Value::Array(items.iter().map(toml_value).collect()),
T::InlineTable(table) => Value::Object(
table
.iter()
.map(|(k, v)| (k.to_owned(), toml_value(v)))
.collect(),
),
}
}
#[cfg(test)]
mod tests;