use std::{fs, io, path::Path};
use troll_core::{Config, ProbeError, Store};
use troll_probe::{ClassifierConfig, SystemProbe};
use crate::{
cli::{Color, Command, Integration},
error::CliError,
mcp, platform, serve, setup, wizard,
};
pub(crate) mod app;
mod doctor;
pub(crate) mod edit;
pub(crate) mod history;
mod import;
pub(crate) mod inspect;
pub(crate) mod list;
pub(crate) mod registry;
pub(crate) mod timestamp;
mod with;
pub(crate) mod zone;
pub(crate) struct Context {
pub(crate) config: Config,
store: Store,
probe: SystemProbe,
range_error: Option<ProbeError>,
}
impl Context {
pub(crate) fn load() -> Result<Self, CliError> {
Self::load_from(&platform::config_home()?, platform::proc_probe())
}
pub(crate) fn load_from(config_home: &Path, probe: SystemProbe) -> Result<Self, CliError> {
let path = config_home.join("config.toml");
let text = read_config(&path)?;
let (range, range_error) = match probe.ephemeral_range() {
Ok(range) => (range, None),
Err(error) => (None, Some(error)),
};
let mut config = Config::parse(config_home, &text, range)
.map_err(|error| CliError::Config(path, error))?;
if let Ok(excluded) = probe.excluded_ranges() {
config.policy.excluded_ranges = excluded;
}
if range_error.is_none()
&& let Some(notice) = config.app_range_notice()
{
eprintln!("{notice}");
}
Ok(Self::from_config(config, probe, range_error))
}
pub(crate) fn from_config(
config: Config,
probe: SystemProbe,
range_error: Option<ProbeError>,
) -> Self {
let store = platform::open_store(&config.registry_home);
Self {
config,
store,
probe,
range_error,
}
}
fn load_for_allocation() -> Result<Self, CliError> {
let context = Self::load()?;
context.require_ephemeral_range()?;
Ok(context)
}
fn require_ephemeral_range(&self) -> Result<(), CliError> {
match &self.range_error {
Some(error) => Err(CliError::EphemeralRange(error.clone())),
None => Ok(()),
}
}
fn probe(&self) -> Result<&SystemProbe, ProbeError> {
platform::require_listener_probe(&self.probe)?;
Ok(&self.probe)
}
fn ensure_registry_home(&self) -> Result<(), CliError> {
let home = &self.config.registry_home;
fs::create_dir_all(home).map_err(|error| CliError::RegistryHome(home.clone(), error))
}
fn classifier(&self, probe: &SystemProbe) -> Result<ClassifierConfig, ProbeError> {
let mut classifier = ClassifierConfig::new(probe.current_uid()?);
if let Some(roots) = &self.config.project_roots {
classifier.project_roots.clone_from(roots);
}
if let Some(patterns) = &self.config.third_party {
classifier.third_party.clone_from(patterns);
}
Ok(classifier)
}
}
fn read_config(path: &Path) -> Result<String, CliError> {
let result = match fs::symlink_metadata(path) {
Ok(_) => fs::read_to_string(path),
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(String::new()),
Err(error) => Err(error),
};
result.map_err(|error| CliError::ReadConfig(path.to_owned(), error))
}
pub fn run(command: Command, json: bool, color: Color) -> Result<i32, CliError> {
let style = crate::style::Style::detect(crate::style::Stream::Stdout, color, json);
match command {
Command::Init { yes, service } => wizard::run(yes, service, json, color),
Command::Setup { integration } => match integration {
Integration::Claude { force } => setup::plugins::run("claude", force, json),
Integration::Codex { force } => setup::plugins::run("codex", force, json),
Integration::Service { force } => setup::run(force, json),
},
Command::Doctor => return doctor::run(json, style),
Command::With {
project,
purpose,
command,
} => {
return with::run(
&Context::load_for_allocation()?,
project,
purpose,
&command,
json,
);
}
Command::ImportLegacy { dir, apply, .. } => {
return import::run(&Context::load()?, &dir, apply, json);
}
Command::Serve { port, bind } => serve::run(port, bind, json),
Command::Mcp => mcp::run(),
Command::List {
drift: true,
kind,
role,
} => list::run(
&Context::load()?,
kind.map(Into::into),
role.map(Into::into),
json,
style,
),
Command::Claim(args) => registry::claim(&Context::load()?, args, json),
Command::Edit { port, changes } => edit::run_edit(&Context::load()?, port, changes, json),
Command::Lease { args, group } => registry::lease(&Context::load()?, args, group, json),
Command::LeaseEdit {
port,
tag,
purpose,
duration,
} => edit::run_lease_edit(
&Context::load()?,
port,
tag.as_deref(),
purpose,
duration,
json,
),
Command::Renew { target, duration } => {
registry::renew(&Context::load()?, target, duration, json)
}
Command::Release {
target,
force_shared,
} => registry::release(&Context::load()?, target, force_shared, json),
Command::History { action } => history::run(&Context::load()?, action, json, style),
Command::Zone { action } => zone::run(&Context::load()?, action, json),
Command::App { action } => app::run(&Context::load()?, action, json),
Command::Env { app } => app::env(&Context::load()?, &app, json),
Command::Check { port } => inspect::check(&Context::load()?, port, json, style),
Command::Explain { port } => inspect::explain(&Context::load()?, port, json, style),
Command::List {
kind,
role,
drift: false,
} => inspect::list(
&Context::load()?,
kind.map(Into::into),
role.map(Into::into),
json,
style,
),
Command::Sweep { dry_run } => registry::sweep(&Context::load()?, dry_run, json),
}?;
Ok(0)
}
#[cfg(test)]
mod tests {
use troll_core::{StoreError, UpdateError, Zone};
use crate::test_support::TempDir;
use super::*;
#[test]
fn invalid_registry_update_stays_invalid_after_repair() {
let home = TempDir::new();
let config = Config::parse(home.path(), "", None).unwrap();
let context = Context::from_config(config, platform::proc_probe(), None);
let path = home.path().join("registry.toml");
fs::write(
&path,
"schema = 2\n[[zone]]\nlabel = 'broken'\nports = []\nenabled = true\n",
)
.unwrap();
let result = troll_core::add_zone(
&context.store,
Zone {
label: "development".into(),
reason: None,
ports: vec!["8123".into()],
enabled: true,
},
);
assert!(matches!(
&result,
Err(UpdateError::Store(StoreError::Invalid { .. }))
));
fs::write(&path, "schema = 2\n").unwrap();
assert!(context.store.load().unwrap().zone.is_empty());
let error = CliError::from(result.unwrap_err());
assert_eq!(error.kind_and_code(), ("InvalidRegistry", 1));
let canonical_path = fs::canonicalize(&path).unwrap();
assert!(
matches!(error, CliError::Store(StoreError::Invalid { path: reported, .. }) if reported == canonical_path)
);
}
}