1use std::path::{Path, PathBuf};
9
10use anyhow::{Context, Result, bail};
11use serde::Serialize;
12use serde_json::{Value, json};
13
14pub const NAME: &str = "rust-anything";
16
17pub const SKILL: &str = include_str!("../skills/rust-anything/SKILL.md");
19const SKILL_FILES: &[(&str, &str)] = &[
20 ("SKILL.md", SKILL),
21 (
22 "whole-app.md",
23 include_str!("../skills/rust-anything/whole-app.md"),
24 ),
25];
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
28#[serde(rename_all = "lowercase")]
29pub enum Agent {
30 Claude,
32 Codex,
34 Cursor,
36 Gemini,
38}
39
40impl Agent {
41 pub const ALL: [Agent; 4] = [Agent::Claude, Agent::Codex, Agent::Cursor, Agent::Gemini];
42
43 pub fn name(self) -> &'static str {
44 match self {
45 Agent::Claude => "Claude Code",
46 Agent::Codex => "Codex",
47 Agent::Cursor => "Cursor",
48 Agent::Gemini => "Gemini CLI",
49 }
50 }
51
52 fn markers(self) -> (&'static str, &'static str) {
54 match self {
55 Agent::Claude => (".claude", "claude"),
56 Agent::Codex => (".codex", "codex"),
57 Agent::Cursor => (".cursor", "cursor"),
58 Agent::Gemini => (".gemini", "gemini"),
59 }
60 }
61
62 fn present(self, home: &Path) -> bool {
64 let (dir, command) = self.markers();
65 home.join(dir).is_dir() || on_path(command)
66 }
67}
68
69fn on_path(command: &str) -> bool {
70 std::env::var_os("PATH").is_some_and(|paths| {
71 std::env::split_paths(&paths).any(|dir| {
72 let file = dir.join(command);
73 file.is_file()
74 || file.with_extension("exe").is_file()
75 || file.with_extension("cmd").is_file()
76 })
77 })
78}
79
80pub struct Options<'a> {
81 pub home: &'a Path,
82 pub agents: Vec<Agent>,
84 pub command: PathBuf,
86 pub remove: bool,
87 pub dry_run: bool,
88}
89
90#[derive(Debug, Serialize)]
92pub struct Change {
93 pub agent: Agent,
94 pub file: PathBuf,
95 pub action: &'static str,
97 #[serde(skip_serializing_if = "Option::is_none")]
99 pub backup: Option<PathBuf>,
100}
101
102#[derive(Debug, Serialize)]
103pub struct Report {
104 pub command: PathBuf,
105 pub agents: Vec<Agent>,
106 pub changes: Vec<Change>,
107 pub dry_run: bool,
108}
109
110pub fn home() -> Result<PathBuf> {
112 std::env::var_os("HOME")
113 .or_else(|| std::env::var_os("USERPROFILE"))
114 .map(PathBuf::from)
115 .context("no home directory (HOME is not set)")
116}
117
118pub fn setup(opts: &Options) -> Result<Report> {
119 let agents: Vec<Agent> = if opts.agents.is_empty() {
120 Agent::ALL
121 .into_iter()
122 .filter(|a| a.present(opts.home))
123 .collect()
124 } else {
125 opts.agents.clone()
126 };
127 if agents.is_empty() {
128 bail!(
129 "no coding agent found (looked for ~/.claude, ~/.codex, ~/.cursor, ~/.gemini and their commands); \
130 name one with --agent claude|codex|cursor|gemini"
131 );
132 }
133 let command = opts.command.to_string_lossy().into_owned();
134 let mut changes = Vec::new();
135 for &agent in &agents {
136 let home = opts.home;
137 match agent {
138 Agent::Claude => {
139 changes.push(json_server(
140 agent,
141 &home.join(".claude.json"),
142 &command,
143 opts,
144 true,
145 )?);
146 changes.push(skill(agent, &home.join(".claude/skills").join(NAME), opts)?);
147 }
148 Agent::Codex => {
149 changes.push(codex_server(
150 agent,
151 &home.join(".codex/config.toml"),
152 &command,
153 opts,
154 )?);
155 changes.push(skill(agent, &home.join(".codex/skills").join(NAME), opts)?);
156 }
157 Agent::Cursor => {
158 changes.push(json_server(
159 agent,
160 &home.join(".cursor/mcp.json"),
161 &command,
162 opts,
163 false,
164 )?);
165 }
166 Agent::Gemini => {
167 changes.push(json_server(
168 agent,
169 &home.join(".gemini/settings.json"),
170 &command,
171 opts,
172 false,
173 )?);
174 }
175 }
176 }
177 Ok(Report {
178 command: opts.command.clone(),
179 agents,
180 changes,
181 dry_run: opts.dry_run,
182 })
183}
184
185fn backup(path: &Path) -> Result<Option<PathBuf>> {
187 if !path.is_file() {
188 return Ok(None);
189 }
190 let mut name = path.file_name().unwrap_or_default().to_os_string();
191 name.push(".rust-anything.bak");
192 let copy = path.with_file_name(name);
193 std::fs::copy(path, ©).with_context(|| format!("backing up {}", path.display()))?;
194 Ok(Some(copy))
195}
196
197fn write(path: &Path, text: &str) -> Result<()> {
199 if let Some(dir) = path.parent() {
200 std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
201 }
202 let tmp = path.with_extension("rust-anything.tmp");
203 std::fs::write(&tmp, text).with_context(|| format!("writing {}", tmp.display()))?;
204 std::fs::rename(&tmp, path).with_context(|| format!("replacing {}", path.display()))
205}
206
207fn json_server(
209 agent: Agent,
210 path: &Path,
211 command: &str,
212 opts: &Options,
213 stdio_type: bool,
214) -> Result<Change> {
215 let text = match std::fs::read_to_string(path) {
216 Ok(t) => Some(t),
217 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
218 Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
219 };
220 let mut doc: Value = match text.as_deref().map(str::trim) {
221 None | Some("") => json!({}),
222 Some(t) => serde_json::from_str(t).with_context(|| {
223 format!(
224 "{} is not valid JSON; fix it or add the server by hand",
225 path.display()
226 )
227 })?,
228 };
229 let Some(root) = doc.as_object_mut() else {
230 bail!(
231 "{} is not a JSON object; add the server by hand",
232 path.display()
233 );
234 };
235 let servers = root.entry("mcpServers").or_insert_with(|| json!({}));
236 let Some(servers) = servers.as_object_mut() else {
237 bail!(
238 "`mcpServers` in {} is not an object; add the server by hand",
239 path.display()
240 );
241 };
242 let action = if opts.remove {
243 if servers.shift_remove(NAME).is_some() {
244 "removed"
245 } else {
246 "absent"
247 }
248 } else {
249 let existing = servers.get(NAME);
250 let mut entry = existing
251 .and_then(Value::as_object)
252 .cloned()
253 .unwrap_or_default();
254 entry.insert("command".into(), json!(command));
255 entry.insert("args".into(), json!(["mcp"]));
256 if stdio_type || entry.contains_key("type") {
257 entry.insert("type".into(), json!("stdio"));
258 }
259 if stdio_type {
260 entry.entry("env").or_insert_with(|| json!({}));
261 }
262 entry.shift_remove("url");
263 let entry = Value::Object(entry);
264 if existing == Some(&entry) {
265 "unchanged"
266 } else {
267 let action = if existing.is_some() {
268 "updated"
269 } else {
270 "added"
271 };
272 servers.insert(NAME.into(), entry);
273 action
274 }
275 };
276 let mut saved = None;
277 if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
278 saved = backup(path)?;
279 write(path, &(serde_json::to_string_pretty(&doc)? + "\n"))?;
280 }
281 Ok(Change {
282 agent,
283 file: path.to_path_buf(),
284 action,
285 backup: saved,
286 })
287}
288
289fn codex_server(agent: Agent, path: &Path, command: &str, opts: &Options) -> Result<Change> {
291 let text = match std::fs::read_to_string(path) {
292 Ok(t) => t,
293 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
294 Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
295 };
296 let mut doc: toml_edit::DocumentMut = text.parse().with_context(|| {
297 format!(
298 "{} is not valid TOML; fix it or add the server by hand",
299 path.display()
300 )
301 })?;
302 let servers = doc
303 .entry("mcp_servers")
304 .or_insert_with(|| {
305 let mut t = toml_edit::Table::new();
306 t.set_implicit(true);
307 toml_edit::Item::Table(t)
308 })
309 .as_table_mut()
310 .with_context(|| format!("`mcp_servers` in {} is not a table", path.display()))?;
311 let same = servers
312 .get(NAME)
313 .and_then(|t| t.as_table())
314 .is_some_and(|t| {
315 t.get("command").and_then(|c| c.as_str()) == Some(command)
316 && t.get("url").is_none()
317 && t.get("args").and_then(|a| a.as_array()).is_some_and(|a| {
318 a.iter().map(|v| v.as_str()).collect::<Vec<_>>() == [Some("mcp")]
319 })
320 });
321 let action = if opts.remove {
322 if servers.remove(NAME).is_some() {
323 "removed"
324 } else {
325 "absent"
326 }
327 } else if same {
328 "unchanged"
329 } else {
330 let had = servers.contains_key(NAME);
331 let mut entry = servers
332 .get(NAME)
333 .and_then(toml_edit::Item::as_table)
334 .cloned()
335 .unwrap_or_default();
336 entry["command"] = toml_edit::value(command);
337 let mut args = toml_edit::Array::new();
338 args.push("mcp");
339 entry["args"] = toml_edit::value(args);
340 entry.remove("url");
341 servers.insert(NAME, toml_edit::Item::Table(entry));
342 if had { "updated" } else { "added" }
343 };
344 let mut saved = None;
345 if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
346 saved = backup(path)?;
347 write(path, &doc.to_string())?;
348 }
349 Ok(Change {
350 agent,
351 file: path.to_path_buf(),
352 action,
353 backup: saved,
354 })
355}
356
357fn skill(agent: Agent, dir: &Path, opts: &Options) -> Result<Change> {
359 let current: Vec<Option<String>> = SKILL_FILES
360 .iter()
361 .map(|(name, _)| std::fs::read_to_string(dir.join(name)).ok())
362 .collect();
363 let action = if opts.remove {
364 if current.iter().any(Option::is_some) {
365 "removed"
366 } else {
367 "absent"
368 }
369 } else if current.iter().all(Option::is_none) {
370 "added"
371 } else if current
372 .iter()
373 .zip(SKILL_FILES)
374 .all(|(have, (_, want))| have.as_deref() == Some(*want))
375 {
376 "unchanged"
377 } else {
378 "updated"
379 };
380 if !opts.dry_run {
381 for (name, text) in SKILL_FILES {
382 let path = dir.join(name);
383 match action {
384 "added" | "updated" => write(&path, text)?,
385 "removed" if path.exists() => {
386 std::fs::remove_file(&path)
387 .with_context(|| format!("removing {}", path.display()))?;
388 }
389 _ => {}
390 }
391 }
392 if action == "removed" {
393 let _ = std::fs::remove_dir(dir);
395 }
396 }
397 Ok(Change {
398 agent,
399 file: dir.join("SKILL.md"),
400 action,
401 backup: None,
402 })
403}
404
405pub fn text(r: &Report) -> String {
407 let mut out = String::new();
408 let verb = if r.dry_run { "Would set up" } else { "Set up" };
409 let names: Vec<&str> = r.agents.iter().map(|a| a.name()).collect();
410 out.push_str(&format!("{verb} rust-anything for {}\n", names.join(", ")));
411 for c in &r.changes {
412 out.push_str(&format!(
413 " {:<10} {:<9} {}\n",
414 c.agent.name(),
415 c.action,
416 c.file.display()
417 ));
418 if let Some(b) = &c.backup {
419 out.push_str(&format!(" {:<10} {:<9} {}\n", "", "backup", b.display()));
420 }
421 }
422 if !r.dry_run
423 && r.changes
424 .iter()
425 .any(|c| c.action != "removed" && c.action != "absent")
426 {
427 out.push_str(&format!(
428 "\nThe agents run `{} mcp`. Restart them, then ask, for example:\n \
429 \"Profile this repo's slowest workflow with rust-anything and move the hot loop to Rust.\"\n",
430 r.command.display()
431 ));
432 }
433 out
434}
435
436#[cfg(test)]
437mod tests {
438 use super::*;
439
440 fn temp_home(name: &str) -> PathBuf {
441 let dir =
442 std::env::temp_dir().join(format!("rust-anything-setup-{name}-{}", std::process::id()));
443 let _ = std::fs::remove_dir_all(&dir);
444 std::fs::create_dir_all(&dir).unwrap();
445 dir
446 }
447
448 fn opts(home: &Path, agents: Vec<Agent>) -> Options<'_> {
449 Options {
450 home,
451 agents,
452 command: PathBuf::from("/opt/bin/rust-anything"),
453 remove: false,
454 dry_run: false,
455 }
456 }
457
458 #[test]
459 fn adds_keeps_and_removes_entries() {
460 let home = temp_home("all");
461 std::fs::write(
463 home.join(".claude.json"),
464 r#"{"zeta": 1, "mcpServers": {"other": {"command": "x"}}, "alpha": true}"#,
465 )
466 .unwrap();
467 std::fs::create_dir_all(home.join(".codex")).unwrap();
468 std::fs::write(
469 home.join(".codex/config.toml"),
470 "model = \"o4\"\n\n[mcp_servers.other]\ncommand = \"x\"\n",
471 )
472 .unwrap();
473
474 let all = Agent::ALL.to_vec();
475 let r = setup(&opts(&home, all.clone())).unwrap();
476 assert!(
477 r.changes.iter().all(|c| c.action == "added"),
478 "{:?}",
479 r.changes
480 );
481
482 let claude: Value =
483 serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
484 .unwrap();
485 assert_eq!(
486 claude["mcpServers"]["rust-anything"]["args"],
487 json!(["mcp"])
488 );
489 assert_eq!(claude["mcpServers"]["other"]["command"], "x");
490 let saved = r.changes[0]
492 .backup
493 .clone()
494 .expect("an existing file is backed up");
495 assert!(
496 std::fs::read_to_string(saved)
497 .unwrap()
498 .starts_with(r#"{"zeta": 1"#)
499 );
500 assert!(r.changes.iter().any(|c| c.backup.is_none()));
501 let keys: Vec<&String> = claude.as_object().unwrap().keys().collect();
502 assert_eq!(keys, ["zeta", "mcpServers", "alpha"], "key order kept");
503 let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
504 assert!(codex.starts_with("model = \"o4\""), "{codex}");
505 assert!(codex.contains("[mcp_servers.rust-anything]\ncommand = \"/opt/bin/rust-anything\"\nargs = [\"mcp\"]"), "{codex}");
506 assert!(codex.contains("[mcp_servers.other]"));
507 assert_eq!(
508 std::fs::read_to_string(home.join(".claude/skills/rust-anything/SKILL.md")).unwrap(),
509 SKILL
510 );
511 assert!(
512 home.join(".codex/skills/rust-anything/whole-app.md")
513 .exists()
514 );
515 let cursor: Value =
516 serde_json::from_str(&std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap())
517 .unwrap();
518 assert_eq!(
519 cursor["mcpServers"]["rust-anything"]["command"],
520 "/opt/bin/rust-anything"
521 );
522 assert!(home.join(".gemini/settings.json").exists());
523
524 let again = setup(&opts(&home, all.clone())).unwrap();
526 assert!(
527 again.changes.iter().all(|c| c.action == "unchanged"),
528 "{:?}",
529 again.changes
530 );
531
532 let mut moved = opts(&home, vec![Agent::Codex]);
534 moved.command = PathBuf::from("/usr/local/bin/rust-anything");
535 let r = setup(&moved).unwrap();
536 assert_eq!(r.changes[0].action, "updated");
537
538 let mut remove = opts(&home, all);
540 remove.remove = true;
541 setup(&remove).unwrap();
542 let claude: Value =
543 serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
544 .unwrap();
545 assert!(claude["mcpServers"].get("rust-anything").is_none());
546 assert_eq!(claude["mcpServers"]["other"]["command"], "x");
547 assert!(!home.join(".claude/skills/rust-anything").exists());
548 let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
549 assert!(
550 !codex.contains("rust-anything") && codex.contains("[mcp_servers.other]"),
551 "{codex}"
552 );
553 std::fs::remove_dir_all(&home).unwrap();
554 }
555
556 #[test]
557 fn reinstall_preserves_custom_options_for_the_same_server() {
558 let home = temp_home("custom-entry");
559 let cursor = home.join(".cursor/mcp.json");
560 let codex = home.join(".codex/config.toml");
561 std::fs::create_dir_all(cursor.parent().unwrap()).unwrap();
562 std::fs::create_dir_all(codex.parent().unwrap()).unwrap();
563 std::fs::write(&cursor, r#"{"mcpServers":{"rust-anything":{"command":"old","args":["mcp"],"env":{"MODE":"custom"}}}}"#).unwrap();
564 std::fs::write(&codex, "[mcp_servers.rust-anything]\ncommand = \"old\"\nargs = [\"mcp\"]\ntool_timeout_sec = 120\n").unwrap();
565
566 let options = opts(&home, vec![Agent::Cursor, Agent::Codex]);
567 setup(&options).unwrap();
568 let cursor: Value =
569 serde_json::from_str(&std::fs::read_to_string(cursor).unwrap()).unwrap();
570 let codex: toml_edit::DocumentMut =
571 std::fs::read_to_string(codex).unwrap().parse().unwrap();
572 let again = setup(&options).unwrap();
573 std::fs::remove_dir_all(home).unwrap();
574 assert_eq!(cursor["mcpServers"][NAME]["env"]["MODE"], "custom");
575 assert_eq!(
576 cursor["mcpServers"][NAME]["command"],
577 "/opt/bin/rust-anything"
578 );
579 assert_eq!(
580 codex["mcp_servers"][NAME]["tool_timeout_sec"].as_integer(),
581 Some(120)
582 );
583 assert!(again.changes.iter().all(|c| c.action == "unchanged"));
584 }
585
586 #[test]
587 fn finds_agents_and_never_breaks_a_bad_file() {
588 let home = temp_home("detect");
589 std::fs::create_dir_all(home.join(".cursor")).unwrap();
590 std::fs::write(home.join(".cursor/mcp.json"), "{ not json").unwrap();
591 let found: Vec<Agent> = Agent::ALL
593 .into_iter()
594 .filter(|a| a.present(&home))
595 .collect();
596 assert!(found.contains(&Agent::Cursor));
597 let err = setup(&opts(&home, vec![Agent::Cursor])).unwrap_err();
598 assert!(format!("{err:#}").contains("not valid JSON"), "{err:#}");
599 assert_eq!(
600 std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap(),
601 "{ not json"
602 );
603
604 let mut dry = opts(&home, vec![Agent::Gemini]);
606 dry.dry_run = true;
607 let r = setup(&dry).unwrap();
608 assert_eq!(r.changes[0].action, "added");
609 assert!(!home.join(".gemini").exists());
610 std::fs::remove_dir_all(&home).unwrap();
611 }
612}