1use std::path::{Path, PathBuf};
9
10use anyhow::{Context, Result, bail};
11use serde::Serialize;
12use serde_json::{Map, Value, json};
13
14pub const NAME: &str = "rust-anything";
16
17pub const SKILL: &str = include_str!("../skills/rust-anything/SKILL.md");
19pub(crate) const 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 #[value(name = "opencode")]
40 OpenCode,
41}
42
43impl Agent {
44 pub const ALL: [Agent; 5] = [
45 Agent::Claude,
46 Agent::Codex,
47 Agent::Cursor,
48 Agent::Gemini,
49 Agent::OpenCode,
50 ];
51
52 pub fn name(self) -> &'static str {
53 match self {
54 Agent::Claude => "Claude Code",
55 Agent::Codex => "Codex",
56 Agent::Cursor => "Cursor",
57 Agent::Gemini => "Gemini CLI",
58 Agent::OpenCode => "OpenCode",
59 }
60 }
61
62 fn markers(self) -> (&'static str, &'static str) {
64 match self {
65 Agent::Claude => (".claude", "claude"),
66 Agent::Codex => (".codex", "codex"),
67 Agent::Cursor => (".cursor", "cursor"),
68 Agent::Gemini => (".gemini", "gemini"),
69 Agent::OpenCode => (".config/opencode", "opencode"),
70 }
71 }
72
73 pub(crate) fn config(self, home: &Path) -> PathBuf {
75 home.join(match self {
76 Agent::Claude => ".claude.json",
77 Agent::Codex => ".codex/config.toml",
78 Agent::Cursor => ".cursor/mcp.json",
79 Agent::Gemini => ".gemini/settings.json",
80 Agent::OpenCode => ".config/opencode/opencode.json",
81 })
82 }
83
84 pub(crate) fn skill_dir(self, home: &Path) -> Option<PathBuf> {
86 match self {
87 Agent::Claude => Some(home.join(".claude/skills").join(NAME)),
88 Agent::Codex => Some(home.join(".codex/skills").join(NAME)),
89 Agent::OpenCode => Some(home.join(".config/opencode/skills").join(NAME)),
90 Agent::Cursor | Agent::Gemini => None,
91 }
92 }
93
94 pub(crate) fn present(self, home: &Path) -> bool {
96 let (dir, command) = self.markers();
97 home.join(dir).is_dir() || on_path(command)
98 }
99}
100
101pub(crate) fn on_path(command: &str) -> bool {
102 std::env::var_os("PATH").is_some_and(|paths| {
103 std::env::split_paths(&paths).any(|dir| {
104 let file = dir.join(command);
105 file.is_file()
106 || file.with_extension("exe").is_file()
107 || file.with_extension("cmd").is_file()
108 })
109 })
110}
111
112pub struct Options<'a> {
113 pub home: &'a Path,
114 pub agents: Vec<Agent>,
116 pub command: PathBuf,
118 pub remove: bool,
119 pub dry_run: bool,
120}
121
122#[derive(Debug, Serialize)]
124pub struct Change {
125 pub agent: Agent,
126 pub file: PathBuf,
127 pub action: &'static str,
129 #[serde(skip_serializing_if = "Option::is_none")]
131 pub backup: Option<PathBuf>,
132}
133
134#[derive(Debug, Serialize)]
135pub struct Report {
136 pub command: PathBuf,
137 pub agents: Vec<Agent>,
138 pub changes: Vec<Change>,
139 pub dry_run: bool,
140}
141
142pub fn home() -> Result<PathBuf> {
144 std::env::var_os("HOME")
145 .or_else(|| std::env::var_os("USERPROFILE"))
146 .map(PathBuf::from)
147 .context("no home directory (HOME is not set)")
148}
149
150pub fn setup(opts: &Options) -> Result<Report> {
151 let agents: Vec<Agent> = if opts.agents.is_empty() {
152 Agent::ALL
153 .into_iter()
154 .filter(|a| a.present(opts.home))
155 .collect()
156 } else {
157 opts.agents.clone()
158 };
159 if agents.is_empty() {
160 bail!(
161 "no coding agent found (looked for ~/.claude, ~/.codex, ~/.cursor, ~/.gemini, ~/.config/opencode and their commands); \
162 name one with --agent claude|codex|cursor|gemini|opencode"
163 );
164 }
165 let command = opts.command.to_string_lossy().into_owned();
166 let mut changes = Vec::new();
167 for &agent in &agents {
168 let config = agent.config(opts.home);
169 changes.push(match agent {
170 Agent::Codex => codex_server(agent, &config, &command, opts)?,
171 Agent::OpenCode => opencode_server(agent, &config, &command, opts)?,
172 _ => json_server(agent, &config, &command, opts, agent == Agent::Claude)?,
173 });
174 if let Some(dir) = agent.skill_dir(opts.home) {
175 changes.push(skill(agent, &dir, opts)?);
176 }
177 }
178 Ok(Report {
179 command: opts.command.clone(),
180 agents,
181 changes,
182 dry_run: opts.dry_run,
183 })
184}
185
186fn backup(path: &Path) -> Result<Option<PathBuf>> {
188 if !path.is_file() {
189 return Ok(None);
190 }
191 let mut name = path.file_name().unwrap_or_default().to_os_string();
192 name.push(".rust-anything.bak");
193 let copy = path.with_file_name(name);
194 std::fs::copy(path, ©).with_context(|| format!("backing up {}", path.display()))?;
195 Ok(Some(copy))
196}
197
198fn write(path: &Path, text: &str) -> Result<()> {
202 let path = &std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
203 if let Some(dir) = path.parent() {
204 std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
205 }
206 let tmp = path.with_extension("rust-anything.tmp");
207 let mut file =
208 std::fs::File::create(&tmp).with_context(|| format!("writing {}", tmp.display()))?;
209 if let Ok(meta) = std::fs::metadata(path) {
210 file.set_permissions(meta.permissions())
211 .with_context(|| format!("writing {}", tmp.display()))?;
212 }
213 std::io::Write::write_all(&mut file, text.as_bytes())
214 .with_context(|| format!("writing {}", tmp.display()))?;
215 drop(file);
216 std::fs::rename(&tmp, path).with_context(|| format!("replacing {}", path.display()))
217}
218
219fn json_server(
221 agent: Agent,
222 path: &Path,
223 command: &str,
224 opts: &Options,
225 stdio_type: bool,
226) -> Result<Change> {
227 let text = match std::fs::read_to_string(path) {
228 Ok(t) => Some(t),
229 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
230 Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
231 };
232 let mut doc: Value = match text.as_deref().map(str::trim) {
233 None | Some("") => json!({}),
234 Some(t) => serde_json::from_str(t).with_context(|| {
235 format!(
236 "{} is not valid JSON; fix it or add the server by hand",
237 path.display()
238 )
239 })?,
240 };
241 let Some(root) = doc.as_object_mut() else {
242 bail!(
243 "{} is not a JSON object; add the server by hand",
244 path.display()
245 );
246 };
247 let servers = root.entry("mcpServers").or_insert_with(|| json!({}));
248 let Some(servers) = servers.as_object_mut() else {
249 bail!(
250 "`mcpServers` in {} is not an object; add the server by hand",
251 path.display()
252 );
253 };
254 let action = if opts.remove {
255 if servers.shift_remove(NAME).is_some() {
256 "removed"
257 } else {
258 "absent"
259 }
260 } else {
261 let existing = servers.get(NAME);
262 let mut entry = existing
263 .and_then(Value::as_object)
264 .cloned()
265 .unwrap_or_default();
266 entry.insert("command".into(), json!(command));
267 entry.insert("args".into(), json!(["mcp"]));
268 if stdio_type || entry.contains_key("type") {
269 entry.insert("type".into(), json!("stdio"));
270 }
271 if stdio_type {
272 entry.entry("env").or_insert_with(|| json!({}));
273 }
274 entry.shift_remove("url");
275 let entry = Value::Object(entry);
276 if existing == Some(&entry) {
277 "unchanged"
278 } else {
279 let action = if existing.is_some() {
280 "updated"
281 } else {
282 "added"
283 };
284 servers.insert(NAME.into(), entry);
285 action
286 }
287 };
288 let mut saved = None;
289 if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
290 saved = backup(path)?;
291 write(path, &(serde_json::to_string_pretty(&doc)? + "\n"))?;
292 }
293 Ok(Change {
294 agent,
295 file: path.to_path_buf(),
296 action,
297 backup: saved,
298 })
299}
300
301fn opencode_servers<'a>(
305 mcp: &'a mut Map<String, Value>,
306 path: &Path,
307) -> Result<&'a mut Map<String, Value>> {
308 if mcp.is_empty() || matches!(mcp.get("servers"), Some(Value::Object(_))) {
309 let servers = mcp.entry("servers").or_insert_with(|| json!({}));
310 return servers.as_object_mut().with_context(|| {
311 format!(
312 "`mcp.servers` in {} is not an object; add the server by hand",
313 path.display()
314 )
315 });
316 }
317 Ok(mcp)
318}
319
320fn opencode_server(agent: Agent, path: &Path, command: &str, opts: &Options) -> Result<Change> {
323 let text = match std::fs::read_to_string(path) {
324 Ok(t) => Some(t),
325 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
326 Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
327 };
328 let mut doc: Value = match text.as_deref().map(str::trim) {
329 None | Some("") => json!({}),
330 Some(t) => serde_json::from_str(t).with_context(|| {
331 format!(
332 "{} is not valid JSON; fix it or add the server by hand",
333 path.display()
334 )
335 })?,
336 };
337 let Some(root) = doc.as_object_mut() else {
338 bail!(
339 "{} is not a JSON object; add the server by hand",
340 path.display()
341 );
342 };
343 let mcp = root.entry("mcp").or_insert_with(|| json!({}));
344 let Some(mcp) = mcp.as_object_mut() else {
345 bail!(
346 "`mcp` in {} is not an object; add the server by hand",
347 path.display()
348 );
349 };
350 let servers = opencode_servers(mcp, path)?;
351 let action = if opts.remove {
352 if servers.shift_remove(NAME).is_some() {
353 "removed"
354 } else {
355 "absent"
356 }
357 } else {
358 let existing = servers.get(NAME);
359 let mut entry = existing
360 .and_then(Value::as_object)
361 .cloned()
362 .unwrap_or_default();
363 entry.insert("type".into(), json!("local"));
364 entry.insert("command".into(), json!([command, "mcp"]));
365 entry.shift_remove("disabled");
368 entry.shift_remove("enabled");
369 entry.shift_remove("url");
370 let entry = Value::Object(entry);
371 if existing == Some(&entry) {
372 "unchanged"
373 } else {
374 let action = if existing.is_some() {
375 "updated"
376 } else {
377 "added"
378 };
379 servers.insert(NAME.into(), entry);
380 action
381 }
382 };
383 let mut saved = None;
384 if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
385 saved = backup(path)?;
386 write(path, &(serde_json::to_string_pretty(&doc)? + "\n"))?;
387 }
388 Ok(Change {
389 agent,
390 file: path.to_path_buf(),
391 action,
392 backup: saved,
393 })
394}
395
396fn codex_server(agent: Agent, path: &Path, command: &str, opts: &Options) -> Result<Change> {
398 let text = match std::fs::read_to_string(path) {
399 Ok(t) => t,
400 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
401 Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
402 };
403 let mut doc: toml_edit::DocumentMut = text.parse().with_context(|| {
404 format!(
405 "{} is not valid TOML; fix it or add the server by hand",
406 path.display()
407 )
408 })?;
409 let servers = doc
410 .entry("mcp_servers")
411 .or_insert_with(|| {
412 let mut t = toml_edit::Table::new();
413 t.set_implicit(true);
414 toml_edit::Item::Table(t)
415 })
416 .as_table_mut()
417 .with_context(|| format!("`mcp_servers` in {} is not a table", path.display()))?;
418 let same = servers
419 .get(NAME)
420 .and_then(|t| t.as_table_like())
421 .is_some_and(|t| {
422 t.get("command").and_then(|c| c.as_str()) == Some(command)
423 && t.get("url").is_none()
424 && t.get("args").and_then(|a| a.as_array()).is_some_and(|a| {
425 a.iter().map(|v| v.as_str()).collect::<Vec<_>>() == [Some("mcp")]
426 })
427 });
428 let action = if opts.remove {
429 if servers.remove(NAME).is_some() {
430 "removed"
431 } else {
432 "absent"
433 }
434 } else if same {
435 "unchanged"
436 } else {
437 let had = servers.contains_key(NAME);
438 let mut entry = match servers.get(NAME) {
440 Some(toml_edit::Item::Table(t)) => t.clone(),
441 Some(toml_edit::Item::Value(toml_edit::Value::InlineTable(t))) => {
442 t.clone().into_table()
443 }
444 _ => toml_edit::Table::new(),
445 };
446 entry["command"] = toml_edit::value(command);
447 let mut args = toml_edit::Array::new();
448 args.push("mcp");
449 entry["args"] = toml_edit::value(args);
450 entry.remove("url");
451 servers.insert(NAME, toml_edit::Item::Table(entry));
452 if had { "updated" } else { "added" }
453 };
454 let mut saved = None;
455 if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
456 saved = backup(path)?;
457 write(path, &doc.to_string())?;
458 }
459 Ok(Change {
460 agent,
461 file: path.to_path_buf(),
462 action,
463 backup: saved,
464 })
465}
466
467fn skill(agent: Agent, dir: &Path, opts: &Options) -> Result<Change> {
469 let current: Vec<Option<String>> = SKILL_FILES
470 .iter()
471 .map(|(name, _)| std::fs::read_to_string(dir.join(name)).ok())
472 .collect();
473 let action = if opts.remove {
474 if current.iter().any(Option::is_some) {
475 "removed"
476 } else {
477 "absent"
478 }
479 } else if current.iter().all(Option::is_none) {
480 "added"
481 } else if current
482 .iter()
483 .zip(SKILL_FILES)
484 .all(|(have, (_, want))| have.as_deref() == Some(*want))
485 {
486 "unchanged"
487 } else {
488 "updated"
489 };
490 if !opts.dry_run {
491 for (name, text) in SKILL_FILES {
492 let path = dir.join(name);
493 match action {
494 "added" | "updated" => write(&path, text)?,
495 "removed" if path.exists() => {
496 std::fs::remove_file(&path)
497 .with_context(|| format!("removing {}", path.display()))?;
498 }
499 _ => {}
500 }
501 }
502 if action == "removed" {
503 let _ = std::fs::remove_dir(dir);
505 }
506 }
507 Ok(Change {
508 agent,
509 file: dir.join("SKILL.md"),
510 action,
511 backup: None,
512 })
513}
514
515pub fn text(r: &Report) -> String {
517 let mut out = String::new();
518 let verb = if r.dry_run { "Would set up" } else { "Set up" };
519 let names: Vec<&str> = r.agents.iter().map(|a| a.name()).collect();
520 out.push_str(&format!("{verb} rust-anything for {}\n", names.join(", ")));
521 for c in &r.changes {
522 out.push_str(&format!(
523 " {:<10} {:<9} {}\n",
524 c.agent.name(),
525 c.action,
526 c.file.display()
527 ));
528 if let Some(b) = &c.backup {
529 out.push_str(&format!(" {:<10} {:<9} {}\n", "", "backup", b.display()));
530 }
531 }
532 if !r.dry_run
533 && r.changes
534 .iter()
535 .any(|c| c.action != "removed" && c.action != "absent")
536 {
537 out.push_str(&format!(
538 "\nThe agents run `{} mcp`. Restart them, then ask, for example:\n \
539 \"Profile this repo's slowest workflow with rust-anything and move the hot loop to Rust.\"\n",
540 r.command.display()
541 ));
542 }
543 out
544}
545
546#[cfg(test)]
547mod tests {
548 use super::*;
549
550 fn temp_home(name: &str) -> PathBuf {
551 let dir =
552 std::env::temp_dir().join(format!("rust-anything-setup-{name}-{}", std::process::id()));
553 let _ = std::fs::remove_dir_all(&dir);
554 std::fs::create_dir_all(&dir).unwrap();
555 dir
556 }
557
558 fn opts(home: &Path, agents: Vec<Agent>) -> Options<'_> {
559 Options {
560 home,
561 agents,
562 command: PathBuf::from("/opt/bin/rust-anything"),
563 remove: false,
564 dry_run: false,
565 }
566 }
567
568 #[test]
569 fn adds_keeps_and_removes_entries() {
570 let home = temp_home("all");
571 std::fs::write(
573 home.join(".claude.json"),
574 r#"{"zeta": 1, "mcpServers": {"other": {"command": "x"}}, "alpha": true}"#,
575 )
576 .unwrap();
577 std::fs::create_dir_all(home.join(".codex")).unwrap();
578 std::fs::write(
579 home.join(".codex/config.toml"),
580 "model = \"o4\"\n\n[mcp_servers.other]\ncommand = \"x\"\n",
581 )
582 .unwrap();
583
584 let all = Agent::ALL.to_vec();
585 let r = setup(&opts(&home, all.clone())).unwrap();
586 assert!(
587 r.changes.iter().all(|c| c.action == "added"),
588 "{:?}",
589 r.changes
590 );
591
592 let claude: Value =
593 serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
594 .unwrap();
595 assert_eq!(
596 claude["mcpServers"]["rust-anything"]["args"],
597 json!(["mcp"])
598 );
599 assert_eq!(claude["mcpServers"]["other"]["command"], "x");
600 let saved = r.changes[0]
602 .backup
603 .clone()
604 .expect("an existing file is backed up");
605 assert!(
606 std::fs::read_to_string(saved)
607 .unwrap()
608 .starts_with(r#"{"zeta": 1"#)
609 );
610 assert!(r.changes.iter().any(|c| c.backup.is_none()));
611 let keys: Vec<&String> = claude.as_object().unwrap().keys().collect();
612 assert_eq!(keys, ["zeta", "mcpServers", "alpha"], "key order kept");
613 let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
614 assert!(codex.starts_with("model = \"o4\""), "{codex}");
615 assert!(codex.contains("[mcp_servers.rust-anything]\ncommand = \"/opt/bin/rust-anything\"\nargs = [\"mcp\"]"), "{codex}");
616 assert!(codex.contains("[mcp_servers.other]"));
617 assert_eq!(
618 std::fs::read_to_string(home.join(".claude/skills/rust-anything/SKILL.md")).unwrap(),
619 SKILL
620 );
621 assert!(
622 home.join(".codex/skills/rust-anything/whole-app.md")
623 .exists()
624 );
625 let cursor: Value =
626 serde_json::from_str(&std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap())
627 .unwrap();
628 assert_eq!(
629 cursor["mcpServers"]["rust-anything"]["command"],
630 "/opt/bin/rust-anything"
631 );
632 assert!(home.join(".gemini/settings.json").exists());
633
634 let again = setup(&opts(&home, all.clone())).unwrap();
636 assert!(
637 again.changes.iter().all(|c| c.action == "unchanged"),
638 "{:?}",
639 again.changes
640 );
641
642 let mut moved = opts(&home, vec![Agent::Codex]);
644 moved.command = PathBuf::from("/usr/local/bin/rust-anything");
645 let r = setup(&moved).unwrap();
646 assert_eq!(r.changes[0].action, "updated");
647
648 let mut remove = opts(&home, all);
650 remove.remove = true;
651 setup(&remove).unwrap();
652 let claude: Value =
653 serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
654 .unwrap();
655 assert!(claude["mcpServers"].get("rust-anything").is_none());
656 assert_eq!(claude["mcpServers"]["other"]["command"], "x");
657 assert!(!home.join(".claude/skills/rust-anything").exists());
658 let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
659 assert!(
660 !codex.contains("rust-anything") && codex.contains("[mcp_servers.other]"),
661 "{codex}"
662 );
663 std::fs::remove_dir_all(&home).unwrap();
664 }
665
666 #[test]
667 fn reinstall_preserves_custom_options_for_the_same_server() {
668 let home = temp_home("custom-entry");
669 let cursor = home.join(".cursor/mcp.json");
670 let codex = home.join(".codex/config.toml");
671 std::fs::create_dir_all(cursor.parent().unwrap()).unwrap();
672 std::fs::create_dir_all(codex.parent().unwrap()).unwrap();
673 std::fs::write(&cursor, r#"{"mcpServers":{"rust-anything":{"command":"old","args":["mcp"],"env":{"MODE":"custom"}}}}"#).unwrap();
674 std::fs::write(&codex, "[mcp_servers.rust-anything]\ncommand = \"old\"\nargs = [\"mcp\"]\ntool_timeout_sec = 120\n").unwrap();
675
676 let options = opts(&home, vec![Agent::Cursor, Agent::Codex]);
677 setup(&options).unwrap();
678 let cursor: Value =
679 serde_json::from_str(&std::fs::read_to_string(cursor).unwrap()).unwrap();
680 let codex: toml_edit::DocumentMut =
681 std::fs::read_to_string(codex).unwrap().parse().unwrap();
682 let again = setup(&options).unwrap();
683 std::fs::remove_dir_all(home).unwrap();
684 assert_eq!(cursor["mcpServers"][NAME]["env"]["MODE"], "custom");
685 assert_eq!(
686 cursor["mcpServers"][NAME]["command"],
687 "/opt/bin/rust-anything"
688 );
689 assert_eq!(
690 codex["mcp_servers"][NAME]["tool_timeout_sec"].as_integer(),
691 Some(120)
692 );
693 assert!(again.changes.iter().all(|c| c.action == "unchanged"));
694 }
695
696 #[test]
697 fn reinstall_keeps_an_inline_codex_entry() {
698 let home = temp_home("codex-inline");
699 let codex = home.join(".codex/config.toml");
700 std::fs::create_dir_all(codex.parent().unwrap()).unwrap();
701 std::fs::write(
702 &codex,
703 "[mcp_servers]\nrust-anything = { command = \"old\", args = [\"mcp\"], env = { MODE = \"custom\" } }\n",
704 )
705 .unwrap();
706
707 let options = opts(&home, vec![Agent::Codex]);
708 setup(&options).unwrap();
709 let doc: toml_edit::DocumentMut = std::fs::read_to_string(&codex).unwrap().parse().unwrap();
710 let again = setup(&options).unwrap();
711 std::fs::remove_dir_all(home).unwrap();
712 assert_eq!(
713 doc["mcp_servers"][NAME]["env"]["MODE"].as_str(),
714 Some("custom")
715 );
716 assert_eq!(
717 doc["mcp_servers"][NAME]["command"].as_str(),
718 Some("/opt/bin/rust-anything")
719 );
720 assert!(again.changes.iter().all(|c| c.action == "unchanged"));
721 }
722
723 #[test]
724 fn opencode_gets_a_local_server_and_the_skill() {
725 let home = temp_home("opencode");
726 let config = home.join(".config/opencode/opencode.json");
727 std::fs::create_dir_all(config.parent().unwrap()).unwrap();
728 std::fs::write(
730 &config,
731 r#"{"$schema":"https://opencode.ai/config.json","mcp":{"servers":{"other":{"type":"local","command":["x"]}}},"model":"a/b"}"#,
732 )
733 .unwrap();
734
735 let mut options = opts(&home, vec![Agent::OpenCode]);
736 setup(&options).unwrap();
737 let doc: Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
738 let entry = &doc["mcp"]["servers"][NAME];
739 assert_eq!(entry["type"], "local");
740 assert_eq!(entry["command"], json!(["/opt/bin/rust-anything", "mcp"]));
741 assert!(entry.get("disabled").is_none(), "{entry}");
742 assert_eq!(doc["mcp"]["servers"]["other"]["command"], json!(["x"]));
743 assert_eq!(doc["model"], "a/b");
744 let keys: Vec<&String> = doc.as_object().unwrap().keys().collect();
745 assert_eq!(keys, ["$schema", "mcp", "model"], "key order kept");
746 assert_eq!(
747 std::fs::read_to_string(home.join(".config/opencode/skills/rust-anything/SKILL.md"))
748 .unwrap(),
749 SKILL
750 );
751
752 let again = setup(&options).unwrap();
754 assert!(
755 again.changes.iter().all(|c| c.action == "unchanged"),
756 "{:?}",
757 again.changes
758 );
759
760 let mut doc: Value =
762 serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
763 doc["mcp"]["servers"][NAME]["disabled"] = json!(true);
764 std::fs::write(&config, serde_json::to_string(&doc).unwrap()).unwrap();
765 let r = setup(&options).unwrap();
766 assert_eq!(r.changes[0].action, "updated");
767 let doc: Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
768 assert!(doc["mcp"]["servers"][NAME].get("disabled").is_none());
769
770 options.command = PathBuf::from("/usr/local/bin/rust-anything");
772 let r = setup(&options).unwrap();
773 assert_eq!(r.changes[0].action, "updated");
774
775 options.remove = true;
777 setup(&options).unwrap();
778 let doc: Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
779 assert!(doc["mcp"]["servers"].get(NAME).is_none());
780 assert_eq!(doc["mcp"]["servers"]["other"]["command"], json!(["x"]));
781 assert!(!home.join(".config/opencode/skills/rust-anything").exists());
782
783 let flat = temp_home("opencode-flat");
785 let flat_config = flat.join(".config/opencode/opencode.json");
786 std::fs::create_dir_all(flat_config.parent().unwrap()).unwrap();
787 std::fs::write(
788 &flat_config,
789 r#"{"mcp":{"other":{"type":"local","command":["x"]},"rust-anything":{"type":"local","command":["/old/rust-anything","mcp"],"enabled":true}}}"#,
790 )
791 .unwrap();
792 setup(&opts(&flat, vec![Agent::OpenCode])).unwrap();
793 let doc: Value =
794 serde_json::from_str(&std::fs::read_to_string(&flat_config).unwrap()).unwrap();
795 let entry = &doc["mcp"][NAME];
796 assert_eq!(entry["command"], json!(["/opt/bin/rust-anything", "mcp"]));
797 assert!(entry.get("enabled").is_none(), "{entry}");
798 assert!(entry.get("disabled").is_none(), "{entry}");
799 assert!(
800 doc["mcp"].get("servers").is_none(),
801 "shapes never mix: {doc}"
802 );
803 assert_eq!(doc["mcp"]["other"]["command"], json!(["x"]));
804 std::fs::remove_dir_all(&flat).unwrap();
805
806 std::fs::write(&config, "{ not json").unwrap();
808 let err = setup(&opts(&home, vec![Agent::OpenCode])).unwrap_err();
809 assert!(format!("{err:#}").contains("not valid JSON"), "{err:#}");
810 assert_eq!(std::fs::read_to_string(&config).unwrap(), "{ not json");
811 std::fs::remove_dir_all(&home).unwrap();
812 }
813
814 #[cfg(unix)]
815 #[test]
816 fn keeps_a_symlinked_settings_file_and_its_permissions() {
817 use std::os::unix::fs::PermissionsExt;
818 let home = temp_home("link");
819 let dotfiles = home.join("dotfiles");
820 std::fs::create_dir_all(&dotfiles).unwrap();
821 let real = dotfiles.join("claude.json");
822 std::fs::write(&real, r#"{"token": "secret"}"#).unwrap();
823 std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o600)).unwrap();
824 std::os::unix::fs::symlink(&real, home.join(".claude.json")).unwrap();
825
826 setup(&opts(&home, vec![Agent::Claude])).unwrap();
827 let link = std::fs::symlink_metadata(home.join(".claude.json")).unwrap();
828 assert!(link.file_type().is_symlink(), "the link is kept");
829 let text = std::fs::read_to_string(&real).unwrap();
830 assert!(text.contains("rust-anything"), "{text}");
831 let mode = std::fs::metadata(&real).unwrap().permissions().mode() & 0o777;
832 assert_eq!(mode, 0o600, "permissions kept");
833 std::fs::remove_dir_all(&home).unwrap();
834 }
835
836 #[test]
837 fn finds_agents_and_never_breaks_a_bad_file() {
838 let home = temp_home("detect");
839 std::fs::create_dir_all(home.join(".cursor")).unwrap();
840 std::fs::write(home.join(".cursor/mcp.json"), "{ not json").unwrap();
841 let found: Vec<Agent> = Agent::ALL
843 .into_iter()
844 .filter(|a| a.present(&home))
845 .collect();
846 assert!(found.contains(&Agent::Cursor));
847 let err = setup(&opts(&home, vec![Agent::Cursor])).unwrap_err();
848 assert!(format!("{err:#}").contains("not valid JSON"), "{err:#}");
849 assert_eq!(
850 std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap(),
851 "{ not json"
852 );
853
854 let mut dry = opts(&home, vec![Agent::Gemini]);
856 dry.dry_run = true;
857 let r = setup(&dry).unwrap();
858 assert_eq!(r.changes[0].action, "added");
859 assert!(!home.join(".gemini").exists());
860 std::fs::remove_dir_all(&home).unwrap();
861 }
862}