Skip to main content

dodot_lib/commands/
mod.rs

1//! Public command API — the entry points for all dodot operations.
2//!
3//! Each function returns a `Result<T>` where `T: Serialize`. These
4//! types are the contract with standout's rendering layer — they
5//! carry everything needed to produce both human-readable (template)
6//! and machine-readable (JSON) output.
7
8pub mod addignore;
9pub mod adopt;
10pub mod down;
11pub mod fill;
12pub mod init;
13pub mod list;
14pub mod status;
15pub mod up;
16
17#[cfg(test)]
18mod tests;
19
20use serde::Serialize;
21
22// ── Shared display types ────────────────────────────────────────
23
24/// Handler symbols matching the Go implementation.
25pub fn handler_symbol(handler: &str) -> &'static str {
26    match handler {
27        "symlink" => "➞",
28        "shell" => "⚙",
29        "path" => "+",
30        "homebrew" => "⚙",
31        "install" => "×",
32        _ => "?",
33    }
34}
35
36/// Status string for standout template tag matching (maps to theme style names).
37pub fn status_style(deployed: bool) -> &'static str {
38    if deployed {
39        "deployed"
40    } else {
41        "pending"
42    }
43}
44
45/// Human-readable handler description for a file.
46pub fn handler_description(handler: &str, rel_path: &str, user_target: Option<&str>) -> String {
47    match handler {
48        "symlink" => {
49            // Callers normally pass a fully-resolved user_target (computed
50            // by `resolve_target` with the pack name in scope). The
51            // pack-namespaced XDG default cannot be reconstructed from
52            // `rel_path` alone, so when no target is provided we fall
53            // back to a generic "<symlink>" placeholder rather than
54            // guessing a wrong `~/.<name>` path.
55            user_target
56                .map(str::to_string)
57                .unwrap_or_else(|| "<symlink>".to_string())
58        }
59        "shell" => "shell profile".into(),
60        "path" => format!("$PATH/{rel_path}"),
61        "install" => "run script".into(),
62        "homebrew" => "brew install".into(),
63        _ => String::new(),
64    }
65}
66
67/// A file entry for pack status display.
68#[derive(Debug, Clone, Serialize)]
69pub struct DisplayFile {
70    pub name: String,
71    pub symbol: String,
72    pub description: String,
73    pub status: String,
74    pub status_label: String,
75    pub handler: String,
76    /// 1-based index into `PackStatusResult.notes`. `Some(N)` means the
77    /// row has a command-wide error/note attached; the template renders
78    /// `[N]` next to the status label and the body appears in the notes
79    /// section at the bottom of the output. Indices are assigned at
80    /// assembly time and are stable within a single command invocation.
81    #[serde(skip_serializing_if = "Option::is_none", default)]
82    pub note_ref: Option<u32>,
83}
84
85/// A pack entry for status display.
86#[derive(Debug, Clone, Serialize)]
87pub struct DisplayPack {
88    pub name: String,
89    pub files: Vec<DisplayFile>,
90}
91
92/// A command-wide note (error / inline conflict) referenced by
93/// `DisplayFile.note_ref`. Indices into `PackStatusResult.notes` are
94/// 1-based; position in the vec matches the `[N]` shown inline.
95#[derive(Debug, Clone, Serialize)]
96pub struct DisplayNote {
97    pub body: String,
98    #[serde(skip_serializing_if = "Option::is_none", default)]
99    pub hint: Option<String>,
100}
101
102/// One claimant of a cross-pack conflict, formatted for display.
103#[derive(Debug, Clone, Serialize)]
104pub struct DisplayClaimant {
105    /// Pack name.
106    pub pack: String,
107    /// Short, pack-relative source description (e.g. `git/env.sh`).
108    pub source: String,
109}
110
111/// A single cross-pack conflict, flattened for template rendering.
112#[derive(Debug, Clone, Serialize)]
113pub struct DisplayConflict {
114    /// Conflict kind. Serializes as `"symlink"` or `"path"` so the
115    /// template can branch on it.
116    pub kind: String,
117    /// Human-readable target (path for symlink, executable name for path).
118    pub target: String,
119    pub claimants: Vec<DisplayClaimant>,
120}
121
122impl DisplayConflict {
123    /// Convert a detection-layer conflict into its display form,
124    /// shortening paths relative to `home` when possible.
125    pub fn from_conflict(c: &crate::conflicts::Conflict, home: &std::path::Path) -> Self {
126        let kind = match c.kind {
127            crate::conflicts::ConflictKind::SymlinkTarget => "symlink",
128            crate::conflicts::ConflictKind::PathExecutable => "path",
129        };
130        let target = match c.kind {
131            crate::conflicts::ConflictKind::SymlinkTarget => shorten_path(&c.target, home),
132            crate::conflicts::ConflictKind::PathExecutable => c
133                .target
134                .file_name()
135                .map(|n| n.to_string_lossy().into_owned())
136                .unwrap_or_else(|| c.target.display().to_string()),
137        };
138        let claimants = c
139            .claimants
140            .iter()
141            .map(|cl| DisplayClaimant {
142                pack: cl.pack.clone(),
143                source: pack_relative_source(&cl.source, &cl.pack),
144            })
145            .collect();
146        DisplayConflict {
147            kind: kind.into(),
148            target,
149            claimants,
150        }
151    }
152}
153
154fn shorten_path(p: &std::path::Path, home: &std::path::Path) -> String {
155    if let Ok(rel) = p.strip_prefix(home) {
156        format!("~/{}", rel.display())
157    } else {
158        p.display().to_string()
159    }
160}
161
162/// Render a claimant source as `<pack>/<relative-path>` when possible,
163/// falling back to just the filename.
164fn pack_relative_source(source: &std::path::Path, pack: &str) -> String {
165    let s = source.to_string_lossy();
166    let marker = format!("/{pack}/");
167    if let Some(idx) = s.rfind(&marker) {
168        let rel = &s[idx + 1..];
169        return rel.to_string();
170    }
171    // Fallback: pack/filename
172    let fname = source
173        .file_name()
174        .map(|n| n.to_string_lossy().into_owned())
175        .unwrap_or_default();
176    format!("{pack}/{fname}")
177}
178
179/// Result type for commands that display pack status
180/// (status, up, down).
181#[derive(Debug, Clone, Serialize)]
182pub struct PackStatusResult {
183    #[serde(skip_serializing_if = "Option::is_none")]
184    pub message: Option<String>,
185    pub dry_run: bool,
186    pub packs: Vec<DisplayPack>,
187    /// Informational command-level messages not attached to any row
188    /// (e.g. "pack X is ignored, skipping"). Real errors belong in
189    /// `notes` so they can be referenced from an item row.
190    #[serde(skip_serializing_if = "Vec::is_empty")]
191    pub warnings: Vec<String>,
192    /// Command-wide error/note list. Each entry is referenced by a
193    /// `DisplayFile.note_ref` (1-based). Rendered at the end of the
194    /// output so per-item rows stay single-line and column-aligned.
195    #[serde(skip_serializing_if = "Vec::is_empty")]
196    pub notes: Vec<DisplayNote>,
197    /// Cross-pack conflicts to display at the end of the output.
198    #[serde(skip_serializing_if = "Vec::is_empty")]
199    pub conflicts: Vec<DisplayConflict>,
200    /// Names of pack-shaped directories skipped because they carry a
201    /// `.dodotignore` marker. Surfaced by `status` so users aren't
202    /// baffled when a directory they expected doesn't appear.
203    #[serde(skip_serializing_if = "Vec::is_empty")]
204    pub ignored_packs: Vec<String>,
205}