pub mod project;
use std::path::PathBuf;
use crate::clients::{self, edit, Client, Registration, Scope};
use crate::launch::{self, Launch};
#[derive(Debug)]
pub enum Action {
RunCommand {
binary: String,
resolved: PathBuf,
args: Vec<String>,
},
ReplaceCommand {
binary: String,
resolved: PathBuf,
remove: Vec<String>,
add: Vec<String>,
was: Option<String>,
},
WriteFile(Box<edit::Edit>),
AlreadyRegistered {
checked: clients::Checked,
},
StaleElsewhere {
was: Option<String>,
fix: String,
},
NotInstalled,
Refused(String),
}
impl Action {
pub fn changes_anything(&self) -> bool {
matches!(
self,
Action::RunCommand { .. } | Action::ReplaceCommand { .. } | Action::WriteFile(_)
)
}
}
#[derive(Debug)]
pub struct ClientPlan {
pub id: String,
pub display: String,
pub scope: Scope,
pub action: Action,
pub note: Option<String>,
}
pub fn plan(
scope: Scope,
only: &[String],
home: Option<&str>,
launch: &Launch,
) -> Result<Vec<ClientPlan>, String> {
let registry = select(only)?;
let home = home.map(str::to_owned).or_else(clients::home_dir);
Ok(registry
.into_iter()
.map(|c| plan_one(&c, scope, home.as_deref(), launch))
.collect())
}
pub fn select(only: &[String]) -> Result<Vec<Client>, String> {
let registry = clients::load()?;
for id in only {
if !registry.iter().any(|c| &c.id == id) {
return Err(format!(
"no client named `{id}`; known clients: {}",
clients::ids().join(", ")
));
}
}
Ok(registry
.into_iter()
.filter(|c| only.is_empty() || only.contains(&c.id))
.collect())
}
fn plan_one(client: &Client, scope: Scope, home: Option<&str>, launch: &Launch) -> ClientPlan {
let mk = |scope, action, note| ClientPlan {
id: client.id.clone(),
display: client.display.clone(),
scope,
action,
note,
};
let Some(home) = home else {
return mk(
scope,
Action::Refused("cannot find your home directory".to_owned()),
None,
);
};
let cli_on_path = client
.cli
.as_ref()
.and_then(|c| which(&c.binary).map(|path| (c, path)));
if !is_installed(client, home) {
return mk(scope, Action::NotInstalled, None);
}
let mut was: Option<String> = None;
match clients::registration(client, scope, home, launch) {
(Registration::Yes, checked) => {
return mk(scope, Action::AlreadyRegistered { checked }, None);
}
(Registration::Stale { found }, _) => was = found,
(Registration::No, _) => {}
(Registration::Unknown(_), _) => {}
}
if let Some((cli, resolved)) = &cli_on_path {
if let Some(args) = cli.add_args(scope, launch) {
if was.is_some() {
let Some(remove) = cli.remove_args(scope) else {
return mk(
scope,
Action::StaleElsewhere {
was,
fix: format!(
"remove the `{}` server from {} yourself, then run `memfork init` again",
clients::SERVER_NAME,
client.display
),
},
None,
);
};
return mk(
scope,
Action::ReplaceCommand {
binary: cli.binary.clone(),
resolved: resolved.clone(),
remove,
add: args,
was,
},
None,
);
}
return mk(
scope,
Action::RunCommand {
binary: cli.binary.clone(),
resolved: resolved.clone(),
args,
},
None,
);
}
}
let note = fallback_note(client, scope, cli_on_path.is_some());
let (scope, note) = match (client.file_writable(scope), scope) {
(true, s) => (s, note),
(false, Scope::User) => (Scope::Project, note),
(false, Scope::Project) => {
return mk(
scope,
Action::Refused("MemFork will not write this client's config".to_owned()),
note,
)
}
};
let Some(file) = client.file.as_ref() else {
return mk(
scope,
Action::Refused("this client has no config file MemFork can write".to_owned()),
note,
);
};
let Some(path) = file.path_here(scope, home) else {
return mk(
scope,
Action::Refused(
"MemFork does not write this client's configuration for this scope".to_owned(),
),
note,
);
};
match edit::plan(file, &path, launch) {
Ok(e) if e.change == edit::Change::Unchanged => mk(
scope,
Action::AlreadyRegistered {
checked: clients::Checked::File(path),
},
note,
),
Ok(e) => mk(scope, Action::WriteFile(Box::new(e)), note),
Err(reason) => mk(scope, Action::Refused(reason), note),
}
}
pub fn is_installed(client: &Client, home: &str) -> bool {
let cli_on_path = client
.cli
.as_ref()
.is_some_and(|c| which(&c.binary).is_some());
let config_exists = |scope| {
client
.file
.as_ref()
.and_then(|f| f.path_here(scope, home))
.is_some_and(|p| p.exists())
};
cli_on_path
|| config_exists(Scope::User)
|| config_exists(Scope::Project)
|| client.detect_dirs_here(home).iter().any(|p| p.is_dir())
}
fn fallback_note(client: &Client, scope: Scope, cli_present: bool) -> Option<String> {
let cli = client.cli.as_ref()?;
if cli_present {
if cli.scope_flags(scope).is_none() {
return Some(format!(
"`{} mcp add` has no {} scope, so this goes through the config file instead",
cli.binary,
scope.as_str()
));
}
return None;
}
if !client.file_writable(Scope::User) {
return Some(format!(
"`{}` is not on PATH, and MemFork will not edit this client's user config \
because it also holds session credentials — registering for this project \
instead. Install the `{}` command and re-run for user scope.",
cli.binary, cli.binary
));
}
Some(format!(
"`{}` is not on PATH, so this goes through the config file instead",
cli.binary
))
}
pub fn apply(plan: &ClientPlan) -> Result<Option<String>, String> {
let _spinner = matches!(
plan.action,
Action::RunCommand { .. } | Action::ReplaceCommand { .. }
)
.then(|| crate::style::Spinner::quiet(&format!("registering MemFork with {}", plan.display)));
match &plan.action {
Action::RunCommand {
binary,
resolved,
args,
} => {
let output = std::process::Command::new(resolved)
.args(args)
.output()
.map_err(|e| {
format!(
"cannot run `{binary}` ({}): {e}",
crate::style::path(resolved)
)
})?;
if output.status.success() {
Ok(None)
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let detail = if stderr.trim().is_empty() {
stdout
} else {
stderr
};
Err(format!(
"`{binary} {}` failed: {}",
args.join(" "),
detail.trim()
))
}
}
Action::ReplaceCommand {
binary,
resolved,
remove,
add,
..
} => {
let _ = std::process::Command::new(resolved).args(remove).output();
let output = std::process::Command::new(resolved)
.args(add)
.output()
.map_err(|e| format!("`{binary} {}` could not be run: {e}", add.join(" ")))?;
if output.status.success() {
return Ok(None);
}
let detail = String::from_utf8_lossy(&output.stderr);
Err(format!(
"`{binary} {}` failed: {}",
add.join(" "),
detail.trim()
))
}
Action::WriteFile(e) => Ok(edit::apply(e)?.map(|p| crate::style::path(&p))),
Action::AlreadyRegistered { .. }
| Action::StaleElsewhere { .. }
| Action::NotInstalled
| Action::Refused(_) => Ok(None),
}
}
pub fn command_line() -> String {
launch::resolve().display(clients::SERVER_ARGS)
}
pub fn which(binary: &str) -> Option<PathBuf> {
let path = std::env::var_os("PATH")?;
let extensions: Vec<String> = if cfg!(target_os = "windows") {
std::env::var("PATHEXT")
.unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_owned())
.split(';')
.filter(|e| !e.is_empty())
.map(|e| e.to_ascii_lowercase())
.collect()
} else {
Vec::new()
};
for dir in std::env::split_paths(&path) {
let direct = dir.join(binary);
if direct.is_file() {
return Some(direct);
}
for ext in &extensions {
let candidate = dir.join(format!("{binary}{ext}"));
if candidate.is_file() {
return Some(candidate);
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_unknown_client_is_named_along_with_the_known_ones() {
let err = plan(
Scope::User,
&["nope".to_owned()],
Some("/home/ada"),
&Launch::program("memfork"),
)
.expect_err("unknown client");
assert!(err.contains("nope"), "{err}");
assert!(err.contains("cursor"), "{err}");
}
#[test]
fn selecting_one_client_plans_only_that_client() {
let plans = plan(
Scope::User,
&["cursor".to_owned()],
Some("/home/ada"),
&Launch::program("memfork"),
)
.expect("planned");
assert_eq!(plans.len(), 1);
assert_eq!(plans[0].id, "cursor");
}
#[test]
fn which_finds_something_that_certainly_exists() {
let found = if cfg!(target_os = "windows") {
which("cmd")
} else {
which("sh")
};
assert!(found.is_some(), "PATH lookup found nothing at all");
assert!(which("a-binary-that-does-not-exist-anywhere").is_none());
}
}