Skip to main content

mars_agents/cli/
link.rs

1//! `mars link <dir>` — manage target directories materialized from `.mars/`.
2//!
3//! `mars link <target>` adds the target to `settings.targets` and copies
4//! content from `.mars/` into that target.
5//! `mars link --unlink <target>` removes the target from `settings.targets`
6//! and removes the target directory.
7
8use crate::diagnostic::{Diagnostic, DiagnosticCategory, DiagnosticCollector, DiagnosticLevel};
9use crate::error::MarsError;
10use crate::lock::{ItemId, ItemKind, LockFile};
11use crate::sync::apply::{ActionOutcome, ActionTaken};
12use crate::types::ItemName;
13use std::collections::HashSet;
14
15use super::output;
16
17/// Arguments for `mars link`.
18#[derive(Debug, clap::Args)]
19pub struct LinkArgs {
20    /// Target directory to materialize (e.g. `.claude`).
21    pub target: String,
22
23    /// Remove target management instead of adding it.
24    #[arg(long)]
25    pub unlink: bool,
26}
27
28/// Run `mars link`.
29pub fn run(args: &LinkArgs, ctx: &super::MarsContext, json: bool) -> Result<i32, MarsError> {
30    let target_name = normalize_target_name(&args.target)?;
31
32    if args.unlink {
33        return unlink_target(ctx, &target_name, json);
34    }
35
36    link_target(ctx, &target_name, json)
37}
38
39fn link_target(ctx: &super::MarsContext, target_name: &str, json: bool) -> Result<i32, MarsError> {
40    let config_path = ctx.project_root.join("mars.toml");
41    if !config_path.exists() {
42        return Err(MarsError::Link {
43            target: target_name.to_string(),
44            message: format!(
45                "mars.toml not found at {} — run `mars init` first",
46                ctx.project_root.display()
47            ),
48        });
49    }
50
51    if !json
52        && !super::WELL_KNOWN.contains(&target_name)
53        && !super::TOOL_DIRS.contains(&target_name)
54    {
55        output::print_warn(&format!(
56            "`{target_name}` is not a recognized tool directory — managing anyway"
57        ));
58    }
59
60    let mars_dir = ctx.project_root.join(".mars");
61    std::fs::create_dir_all(&mars_dir)?;
62    let lock_path = mars_dir.join("sync.lock");
63    let _sync_lock = crate::fs::FileLock::acquire(&lock_path)?;
64
65    let mut config = crate::config::load(&ctx.project_root)?;
66    let mut targets = config
67        .settings
68        .targets
69        .clone()
70        .unwrap_or_else(|| config.settings.managed_targets());
71    if !targets.iter().any(|target| target == target_name) {
72        targets.push(target_name.to_string());
73    }
74
75    let settings_changed = config.settings.targets.as_ref() != Some(&targets);
76
77    let lock = crate::lock::load(&ctx.project_root)?;
78    let outcomes = lock_items_as_sync_outcomes(&lock);
79    let previous_managed_paths = lock
80        .all_output_dest_paths()
81        .map(|dest_path| dest_path.to_string())
82        .collect::<HashSet<String>>();
83
84    let mut diag = DiagnosticCollector::new();
85    let target_outcomes = crate::target_sync::sync_managed_targets(
86        &ctx.project_root,
87        &mars_dir,
88        &[target_name.to_string()],
89        &outcomes,
90        &previous_managed_paths,
91        true,
92        &mut diag,
93    );
94    let mut diagnostics = diag.drain();
95    if let Some(diagnostic) = deprecated_agents_target_diagnostic(target_name) {
96        diagnostics.push(diagnostic);
97    }
98
99    let Some(outcome) = target_outcomes.first() else {
100        return Err(MarsError::Link {
101            target: target_name.to_string(),
102            message: "target sync produced no result".to_string(),
103        });
104    };
105
106    if !outcome.errors.is_empty() {
107        return Err(MarsError::Link {
108            target: target_name.to_string(),
109            message: outcome.errors.join("; "),
110        });
111    }
112
113    if settings_changed {
114        config.settings.targets = Some(targets);
115        crate::config::save(&ctx.project_root, &config)?;
116    }
117
118    if json {
119        output::print_json(&serde_json::json!({
120            "ok": true,
121            "target": target_name,
122            "settings_updated": settings_changed,
123            "synced": outcome.items_synced,
124            "removed": outcome.items_removed,
125            "diagnostics": diagnostics,
126        }));
127    } else {
128        output::print_success(&format!(
129            "managed target `{target_name}` (synced {}, removed {})",
130            outcome.items_synced, outcome.items_removed
131        ));
132        for diagnostic in diagnostics {
133            output::print_warn(&diagnostic.to_string());
134        }
135    }
136
137    Ok(0)
138}
139
140fn deprecated_agents_target_diagnostic(target_name: &str) -> Option<Diagnostic> {
141    (target_name == ".agents").then(|| Diagnostic {
142        level: DiagnosticLevel::Warning,
143        code: "deprecated-agents-target",
144        message: "`.agents` is a deprecated link target. Run `mars unlink .agents` to remove it. Skills are now emitted to native harness dirs automatically.".to_string(),
145        context: Some("link target".to_string()),
146        category: Some(DiagnosticCategory::Compatibility),
147    })
148}
149
150fn unlink_target(
151    ctx: &super::MarsContext,
152    target_name: &str,
153    json: bool,
154) -> Result<i32, MarsError> {
155    let mars_dir = ctx.project_root.join(".mars");
156    std::fs::create_dir_all(&mars_dir)?;
157    let lock_path = mars_dir.join("sync.lock");
158    let _sync_lock = crate::fs::FileLock::acquire(&lock_path)?;
159
160    let mut config = crate::config::load(&ctx.project_root)?;
161    let mut settings_updated = false;
162    let mut target_was_managed = false;
163
164    if config.settings.managed_root.as_deref() == Some(target_name) {
165        config.settings.managed_root = None;
166        settings_updated = true;
167        target_was_managed = true;
168    }
169
170    if let Some(targets) = config.settings.targets.as_mut() {
171        let old_len = targets.len();
172        targets.retain(|target| target != target_name);
173        if targets.len() != old_len {
174            settings_updated = true;
175            target_was_managed = true;
176        }
177        if targets.is_empty() {
178            config.settings.targets = None;
179        }
180    }
181
182    if settings_updated {
183        crate::config::save(&ctx.project_root, &config)?;
184    }
185
186    let target_dir = ctx.project_root.join(target_name);
187    let removed_dir = if target_was_managed && target_dir.exists() {
188        std::fs::remove_dir_all(&target_dir)?;
189        true
190    } else {
191        false
192    };
193
194    if json {
195        output::print_json(&serde_json::json!({
196            "ok": true,
197            "target": target_name,
198            "settings_updated": settings_updated,
199            "removed_dir": removed_dir,
200        }));
201    } else if removed_dir {
202        output::print_success(&format!("removed managed target `{target_name}`"));
203    } else {
204        output::print_info(&format!("removed `{target_name}` from settings.targets"));
205    }
206
207    Ok(0)
208}
209
210fn normalize_target_name(target: &str) -> Result<String, MarsError> {
211    let normalized = target.trim_end_matches('/').trim_end_matches('\\');
212    if normalized.contains('/') || normalized.contains('\\') {
213        return Err(MarsError::Link {
214            target: target.to_string(),
215            message: "link target must be a directory name, not a path".to_string(),
216        });
217    }
218    if normalized.is_empty() || normalized == "." || normalized == ".." {
219        return Err(MarsError::Link {
220            target: target.to_string(),
221            message: "invalid link target name".to_string(),
222        });
223    }
224    Ok(normalized.to_string())
225}
226
227fn lock_items_as_sync_outcomes(lock: &LockFile) -> Vec<ActionOutcome> {
228    lock.flat_items()
229        .into_iter()
230        .map(|(dest_path, item)| ActionOutcome {
231            item_id: ItemId {
232                kind: item.kind,
233                name: item_name_from_dest_path(&dest_path, item.kind),
234            },
235            action: ActionTaken::Skipped,
236            dest_path,
237            source_name: item.source,
238            source_checksum: None,
239            installed_checksum: Some(item.installed_checksum),
240        })
241        .collect()
242}
243
244fn item_name_from_dest_path(dest_path: &crate::types::DestPath, kind: ItemKind) -> ItemName {
245    let last = dest_path.as_str().rsplit('/').next().unwrap_or("");
246    let name = match kind {
247        ItemKind::Agent => last.strip_suffix(".md").unwrap_or(last).to_string(),
248        ItemKind::Skill | ItemKind::Hook | ItemKind::McpServer | ItemKind::BootstrapDoc => {
249            last.to_string()
250        }
251    };
252
253    ItemName::from(name)
254}
255
256#[cfg(test)]
257mod tests {
258    use super::normalize_target_name;
259
260    #[test]
261    fn normalize_strips_trailing_slash() {
262        assert_eq!(normalize_target_name(".claude/").unwrap(), ".claude");
263    }
264
265    #[test]
266    fn normalize_rejects_path() {
267        assert!(normalize_target_name("foo/bar").is_err());
268    }
269
270    #[test]
271    fn normalize_rejects_empty() {
272        assert!(normalize_target_name("").is_err());
273    }
274
275    #[test]
276    fn normalize_rejects_dots() {
277        assert!(normalize_target_name(".").is_err());
278        assert!(normalize_target_name("..").is_err());
279    }
280}