rust-anything 1.2.0

Rewrite your app in Rust, one piece at a time, checked against the original's recorded behavior at every step. TypeScript/JavaScript, Python, C, Go, Ruby and Java
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! `setup`: register rust-anything with the coding agents on this machine, in one command.
//!
//! For each agent it finds (or is told about), it adds the MCP server (`rust-anything mcp`) to
//! the agent's own configuration and, where the agent reads skills, installs the workflow skill.
//! Existing settings are kept: only the `rust-anything` entries are added or replaced, and a file
//! that does not parse is left alone with an error. `--remove` takes the entries out again.

use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::Serialize;
use serde_json::{Value, json};

/// The server and skill name in every agent.
pub const NAME: &str = "rust-anything";

/// The workflow skill, as shipped in `skills/rust-anything/SKILL.md`.
pub const SKILL: &str = include_str!("../skills/rust-anything/SKILL.md");
const SKILL_FILES: &[(&str, &str)] = &[
    ("SKILL.md", SKILL),
    (
        "whole-app.md",
        include_str!("../skills/rust-anything/whole-app.md"),
    ),
];

#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Agent {
    /// Claude Code: `~/.claude.json`, skill in `~/.claude/skills`.
    Claude,
    /// OpenAI Codex CLI: `~/.codex/config.toml`, skill in `~/.codex/skills`.
    Codex,
    /// Cursor: `~/.cursor/mcp.json`.
    Cursor,
    /// Gemini CLI: `~/.gemini/settings.json`.
    Gemini,
}

impl Agent {
    pub const ALL: [Agent; 4] = [Agent::Claude, Agent::Codex, Agent::Cursor, Agent::Gemini];

    pub fn name(self) -> &'static str {
        match self {
            Agent::Claude => "Claude Code",
            Agent::Codex => "Codex",
            Agent::Cursor => "Cursor",
            Agent::Gemini => "Gemini CLI",
        }
    }

    /// The agent's folder in the home directory, and its command.
    fn markers(self) -> (&'static str, &'static str) {
        match self {
            Agent::Claude => (".claude", "claude"),
            Agent::Codex => (".codex", "codex"),
            Agent::Cursor => (".cursor", "cursor"),
            Agent::Gemini => (".gemini", "gemini"),
        }
    }

    /// Whether the agent seems installed: its folder exists or its command is on `PATH`.
    fn present(self, home: &Path) -> bool {
        let (dir, command) = self.markers();
        home.join(dir).is_dir() || on_path(command)
    }
}

fn on_path(command: &str) -> bool {
    std::env::var_os("PATH").is_some_and(|paths| {
        std::env::split_paths(&paths).any(|dir| {
            let file = dir.join(command);
            file.is_file()
                || file.with_extension("exe").is_file()
                || file.with_extension("cmd").is_file()
        })
    })
}

pub struct Options<'a> {
    pub home: &'a Path,
    /// Agents to set up; empty means every agent found.
    pub agents: Vec<Agent>,
    /// The command the agents run; the current executable by default.
    pub command: PathBuf,
    pub remove: bool,
    pub dry_run: bool,
}

/// One change: which agent, which file, and what happened.
#[derive(Debug, Serialize)]
pub struct Change {
    pub agent: Agent,
    pub file: PathBuf,
    /// `added`, `updated`, `unchanged`, `removed` or `absent`.
    pub action: &'static str,
    /// The copy of the file as it was, when an existing file was changed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backup: Option<PathBuf>,
}

#[derive(Debug, Serialize)]
pub struct Report {
    pub command: PathBuf,
    pub agents: Vec<Agent>,
    pub changes: Vec<Change>,
    pub dry_run: bool,
}

/// The home directory: `HOME`, or `USERPROFILE` on Windows.
pub fn home() -> Result<PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .context("no home directory (HOME is not set)")
}

pub fn setup(opts: &Options) -> Result<Report> {
    let agents: Vec<Agent> = if opts.agents.is_empty() {
        Agent::ALL
            .into_iter()
            .filter(|a| a.present(opts.home))
            .collect()
    } else {
        opts.agents.clone()
    };
    if agents.is_empty() {
        bail!(
            "no coding agent found (looked for ~/.claude, ~/.codex, ~/.cursor, ~/.gemini and their commands); \
             name one with --agent claude|codex|cursor|gemini"
        );
    }
    let command = opts.command.to_string_lossy().into_owned();
    let mut changes = Vec::new();
    for &agent in &agents {
        let home = opts.home;
        match agent {
            Agent::Claude => {
                changes.push(json_server(
                    agent,
                    &home.join(".claude.json"),
                    &command,
                    opts,
                    true,
                )?);
                changes.push(skill(agent, &home.join(".claude/skills").join(NAME), opts)?);
            }
            Agent::Codex => {
                changes.push(codex_server(
                    agent,
                    &home.join(".codex/config.toml"),
                    &command,
                    opts,
                )?);
                changes.push(skill(agent, &home.join(".codex/skills").join(NAME), opts)?);
            }
            Agent::Cursor => {
                changes.push(json_server(
                    agent,
                    &home.join(".cursor/mcp.json"),
                    &command,
                    opts,
                    false,
                )?);
            }
            Agent::Gemini => {
                changes.push(json_server(
                    agent,
                    &home.join(".gemini/settings.json"),
                    &command,
                    opts,
                    false,
                )?);
            }
        }
    }
    Ok(Report {
        command: opts.command.clone(),
        agents,
        changes,
        dry_run: opts.dry_run,
    })
}

/// Copies an existing settings file to `<file>.rust-anything.bak` before it is changed.
fn backup(path: &Path) -> Result<Option<PathBuf>> {
    if !path.is_file() {
        return Ok(None);
    }
    let mut name = path.file_name().unwrap_or_default().to_os_string();
    name.push(".rust-anything.bak");
    let copy = path.with_file_name(name);
    std::fs::copy(path, &copy).with_context(|| format!("backing up {}", path.display()))?;
    Ok(Some(copy))
}

/// Writes `text` to `path` through a temporary file, so a failed write never leaves half a file.
fn write(path: &Path, text: &str) -> Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
    }
    let tmp = path.with_extension("rust-anything.tmp");
    std::fs::write(&tmp, text).with_context(|| format!("writing {}", tmp.display()))?;
    std::fs::rename(&tmp, path).with_context(|| format!("replacing {}", path.display()))
}

/// The `mcpServers` entry of a JSON settings file (Claude Code, Cursor, Gemini CLI).
fn json_server(
    agent: Agent,
    path: &Path,
    command: &str,
    opts: &Options,
    stdio_type: bool,
) -> Result<Change> {
    let text = match std::fs::read_to_string(path) {
        Ok(t) => Some(t),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
    };
    let mut doc: Value = match text.as_deref().map(str::trim) {
        None | Some("") => json!({}),
        Some(t) => serde_json::from_str(t).with_context(|| {
            format!(
                "{} is not valid JSON; fix it or add the server by hand",
                path.display()
            )
        })?,
    };
    let Some(root) = doc.as_object_mut() else {
        bail!(
            "{} is not a JSON object; add the server by hand",
            path.display()
        );
    };
    let mut entry = json!({ "command": command, "args": ["mcp"] });
    if stdio_type {
        entry = json!({ "type": "stdio", "command": command, "args": ["mcp"], "env": {} });
    }
    let servers = root.entry("mcpServers").or_insert_with(|| json!({}));
    let Some(servers) = servers.as_object_mut() else {
        bail!(
            "`mcpServers` in {} is not an object; add the server by hand",
            path.display()
        );
    };
    let action = if opts.remove {
        if servers.shift_remove(NAME).is_some() {
            "removed"
        } else {
            "absent"
        }
    } else {
        match servers.get(NAME) {
            Some(old) if *old == entry => "unchanged",
            Some(_) => {
                servers.insert(NAME.into(), entry);
                "updated"
            }
            None => {
                servers.insert(NAME.into(), entry);
                "added"
            }
        }
    };
    let mut saved = None;
    if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
        saved = backup(path)?;
        write(path, &(serde_json::to_string_pretty(&doc)? + "\n"))?;
    }
    Ok(Change {
        agent,
        file: path.to_path_buf(),
        action,
        backup: saved,
    })
}

/// `[mcp_servers.rust-anything]` in Codex's `config.toml`, keeping the rest of the file as is.
fn codex_server(agent: Agent, path: &Path, command: &str, opts: &Options) -> Result<Change> {
    let text = match std::fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
    };
    let mut doc: toml_edit::DocumentMut = text.parse().with_context(|| {
        format!(
            "{} is not valid TOML; fix it or add the server by hand",
            path.display()
        )
    })?;
    let servers = doc
        .entry("mcp_servers")
        .or_insert_with(|| {
            let mut t = toml_edit::Table::new();
            t.set_implicit(true);
            toml_edit::Item::Table(t)
        })
        .as_table_mut()
        .with_context(|| format!("`mcp_servers` in {} is not a table", path.display()))?;
    let mut entry = toml_edit::Table::new();
    entry["command"] = toml_edit::value(command);
    let mut args = toml_edit::Array::new();
    args.push("mcp");
    entry["args"] = toml_edit::value(args);
    let same = servers
        .get(NAME)
        .and_then(|t| t.as_table())
        .is_some_and(|t| {
            t.get("command").and_then(|c| c.as_str()) == Some(command)
                && t.get("args").and_then(|a| a.as_array()).is_some_and(|a| {
                    a.iter().map(|v| v.as_str()).collect::<Vec<_>>() == [Some("mcp")]
                })
        });
    let action = if opts.remove {
        if servers.remove(NAME).is_some() {
            "removed"
        } else {
            "absent"
        }
    } else if same {
        "unchanged"
    } else {
        let had = servers.contains_key(NAME);
        servers.insert(NAME, toml_edit::Item::Table(entry));
        if had { "updated" } else { "added" }
    };
    let mut saved = None;
    if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
        saved = backup(path)?;
        write(path, &doc.to_string())?;
    }
    Ok(Change {
        agent,
        file: path.to_path_buf(),
        action,
        backup: saved,
    })
}

/// The workflow skill in an agent's skills folder.
fn skill(agent: Agent, dir: &Path, opts: &Options) -> Result<Change> {
    let current: Vec<Option<String>> = SKILL_FILES
        .iter()
        .map(|(name, _)| std::fs::read_to_string(dir.join(name)).ok())
        .collect();
    let action = if opts.remove {
        if current.iter().any(Option::is_some) {
            "removed"
        } else {
            "absent"
        }
    } else if current.iter().all(Option::is_none) {
        "added"
    } else if current
        .iter()
        .zip(SKILL_FILES)
        .all(|(have, (_, want))| have.as_deref() == Some(*want))
    {
        "unchanged"
    } else {
        "updated"
    };
    if !opts.dry_run {
        for (name, text) in SKILL_FILES {
            let path = dir.join(name);
            match action {
                "added" | "updated" => write(&path, text)?,
                "removed" if path.exists() => {
                    std::fs::remove_file(&path)
                        .with_context(|| format!("removing {}", path.display()))?;
                }
                _ => {}
            }
        }
        if action == "removed" {
            // The folder is ours; leave it only if someone put other files in it.
            let _ = std::fs::remove_dir(dir);
        }
    }
    Ok(Change {
        agent,
        file: dir.join("SKILL.md"),
        action,
        backup: None,
    })
}

/// The report for people.
pub fn text(r: &Report) -> String {
    let mut out = String::new();
    let verb = if r.dry_run { "Would set up" } else { "Set up" };
    let names: Vec<&str> = r.agents.iter().map(|a| a.name()).collect();
    out.push_str(&format!("{verb} rust-anything for {}\n", names.join(", ")));
    for c in &r.changes {
        out.push_str(&format!(
            "  {:<10} {:<9} {}\n",
            c.agent.name(),
            c.action,
            c.file.display()
        ));
        if let Some(b) = &c.backup {
            out.push_str(&format!("  {:<10} {:<9} {}\n", "", "backup", b.display()));
        }
    }
    if !r.dry_run
        && r.changes
            .iter()
            .any(|c| c.action != "removed" && c.action != "absent")
    {
        out.push_str(&format!(
            "\nThe agents run `{} mcp`. Restart them, then ask, for example:\n  \
             \"Profile this repo's slowest workflow with rust-anything and move the hot loop to Rust.\"\n",
            r.command.display()
        ));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn temp_home(name: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("rust-anything-setup-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn opts(home: &Path, agents: Vec<Agent>) -> Options<'_> {
        Options {
            home,
            agents,
            command: PathBuf::from("/opt/bin/rust-anything"),
            remove: false,
            dry_run: false,
        }
    }

    #[test]
    fn adds_keeps_and_removes_entries() {
        let home = temp_home("all");
        // Existing settings that must survive, in their own order.
        std::fs::write(
            home.join(".claude.json"),
            r#"{"zeta": 1, "mcpServers": {"other": {"command": "x"}}, "alpha": true}"#,
        )
        .unwrap();
        std::fs::create_dir_all(home.join(".codex")).unwrap();
        std::fs::write(
            home.join(".codex/config.toml"),
            "model = \"o4\"\n\n[mcp_servers.other]\ncommand = \"x\"\n",
        )
        .unwrap();

        let all = Agent::ALL.to_vec();
        let r = setup(&opts(&home, all.clone())).unwrap();
        assert!(
            r.changes.iter().all(|c| c.action == "added"),
            "{:?}",
            r.changes
        );

        let claude: Value =
            serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
                .unwrap();
        assert_eq!(
            claude["mcpServers"]["rust-anything"]["args"],
            json!(["mcp"])
        );
        assert_eq!(claude["mcpServers"]["other"]["command"], "x");
        // The existing file was copied before the change; new files need no copy.
        let saved = r.changes[0]
            .backup
            .clone()
            .expect("an existing file is backed up");
        assert!(
            std::fs::read_to_string(saved)
                .unwrap()
                .starts_with(r#"{"zeta": 1"#)
        );
        assert!(r.changes.iter().any(|c| c.backup.is_none()));
        let keys: Vec<&String> = claude.as_object().unwrap().keys().collect();
        assert_eq!(keys, ["zeta", "mcpServers", "alpha"], "key order kept");
        let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
        assert!(codex.starts_with("model = \"o4\""), "{codex}");
        assert!(codex.contains("[mcp_servers.rust-anything]\ncommand = \"/opt/bin/rust-anything\"\nargs = [\"mcp\"]"), "{codex}");
        assert!(codex.contains("[mcp_servers.other]"));
        assert_eq!(
            std::fs::read_to_string(home.join(".claude/skills/rust-anything/SKILL.md")).unwrap(),
            SKILL
        );
        assert!(
            home.join(".codex/skills/rust-anything/whole-app.md")
                .exists()
        );
        let cursor: Value =
            serde_json::from_str(&std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap())
                .unwrap();
        assert_eq!(
            cursor["mcpServers"]["rust-anything"]["command"],
            "/opt/bin/rust-anything"
        );
        assert!(home.join(".gemini/settings.json").exists());

        // Running again changes nothing.
        let again = setup(&opts(&home, all.clone())).unwrap();
        assert!(
            again.changes.iter().all(|c| c.action == "unchanged"),
            "{:?}",
            again.changes
        );

        // A moved binary updates the entries.
        let mut moved = opts(&home, vec![Agent::Codex]);
        moved.command = PathBuf::from("/usr/local/bin/rust-anything");
        let r = setup(&moved).unwrap();
        assert_eq!(r.changes[0].action, "updated");

        // Remove takes out only our entries.
        let mut remove = opts(&home, all);
        remove.remove = true;
        setup(&remove).unwrap();
        let claude: Value =
            serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
                .unwrap();
        assert!(claude["mcpServers"].get("rust-anything").is_none());
        assert_eq!(claude["mcpServers"]["other"]["command"], "x");
        assert!(!home.join(".claude/skills/rust-anything").exists());
        let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
        assert!(
            !codex.contains("rust-anything") && codex.contains("[mcp_servers.other]"),
            "{codex}"
        );
        std::fs::remove_dir_all(&home).unwrap();
    }

    #[test]
    fn finds_agents_and_never_breaks_a_bad_file() {
        let home = temp_home("detect");
        std::fs::create_dir_all(home.join(".cursor")).unwrap();
        std::fs::write(home.join(".cursor/mcp.json"), "{ not json").unwrap();
        // Only Cursor's folder exists (the commands may be on PATH on a developer machine).
        let found: Vec<Agent> = Agent::ALL
            .into_iter()
            .filter(|a| a.present(&home))
            .collect();
        assert!(found.contains(&Agent::Cursor));
        let err = setup(&opts(&home, vec![Agent::Cursor])).unwrap_err();
        assert!(format!("{err:#}").contains("not valid JSON"), "{err:#}");
        assert_eq!(
            std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap(),
            "{ not json"
        );

        // A dry run writes nothing.
        let mut dry = opts(&home, vec![Agent::Gemini]);
        dry.dry_run = true;
        let r = setup(&dry).unwrap();
        assert_eq!(r.changes[0].action, "added");
        assert!(!home.join(".gemini").exists());
        std::fs::remove_dir_all(&home).unwrap();
    }
}