Skip to main content

gitflow_core/
doctor.rs

1//! Environment diagnostic types and traits for `gf doctor`.
2
3use serde::Serialize;
4
5/// Status of a single health check item.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
7#[serde(rename_all = "snake_case")]
8pub enum CheckStatus {
9    /// Check passed.
10    Pass,
11    /// Check passed with warnings.
12    Warn,
13    /// Check failed.
14    Fail,
15}
16
17/// A single diagnostic check result.
18#[derive(Debug, Clone, Serialize)]
19pub struct CheckItem {
20    /// Check category (e.g., `platform_cli`, `agent`, `gf_self`, `agent_env`).
21    pub category: String,
22    /// Check item name (e.g., "gh CLI installed").
23    pub name: String,
24    /// Result status.
25    pub status: CheckStatus,
26    /// Human-readable description (Chinese-first).
27    pub message: String,
28    /// Fix suggestion (provided on Fail/Warn).
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub hint: Option<String>,
31    /// Additional detail (e.g., version string, path).
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub detail: Option<String>,
34}
35
36/// Summary counts for a doctor report.
37#[derive(Debug, Clone, Serialize)]
38pub struct DoctorSummary {
39    /// Total number of checks.
40    pub total: usize,
41    /// Number of passing checks.
42    pub passed: usize,
43    /// Number of warnings.
44    pub warned: usize,
45    /// Number of failures.
46    pub failed: usize,
47}
48
49impl DoctorSummary {
50    /// Compute summary from a slice of check items.
51    #[must_use]
52    pub fn from_items(items: &[CheckItem]) -> Self {
53        let total = items.len();
54        let passed = items
55            .iter()
56            .filter(|i| i.status == CheckStatus::Pass)
57            .count();
58        let warned = items
59            .iter()
60            .filter(|i| i.status == CheckStatus::Warn)
61            .count();
62        let failed = items
63            .iter()
64            .filter(|i| i.status == CheckStatus::Fail)
65            .count();
66        Self {
67            total,
68            passed,
69            warned,
70            failed,
71        }
72    }
73}
74
75/// Complete diagnostic report.
76#[derive(Debug, Clone, Serialize)]
77pub struct DoctorReport {
78    /// All check items.
79    pub items: Vec<CheckItem>,
80    /// Summary counts.
81    pub summary: DoctorSummary,
82    /// ISO 8601 timestamp.
83    pub timestamp: String,
84}
85
86impl DoctorReport {
87    /// Create a report from check items, computing summary and timestamp.
88    #[must_use]
89    pub fn from_items(items: Vec<CheckItem>) -> Self {
90        let summary = DoctorSummary::from_items(&items);
91        let timestamp = std::time::SystemTime::now()
92            .duration_since(std::time::UNIX_EPOCH)
93            .map_or_else(|_| "unknown".to_string(), |d| format!("{}s", d.as_secs()));
94        Self {
95            items,
96            summary,
97            timestamp,
98        }
99    }
100}
101
102/// Trait for health check categories.
103///
104/// Each category implements this trait to provide a group of related checks.
105/// The `gf doctor` command iterates over all registered categories and collects results.
106pub trait HealthCheck: Send + Sync {
107    /// Category name for grouping (e.g., `platform_cli`).
108    fn category(&self) -> &'static str;
109
110    /// Run all checks in this category, returning results.
111    /// Must not fail fast — collect all results even if some checks fail.
112    fn run(&self) -> Vec<CheckItem>;
113}
114
115impl CheckItem {
116    /// Create a passing check item.
117    #[must_use]
118    pub fn pass(
119        category: impl Into<String>,
120        name: impl Into<String>,
121        message: impl Into<String>,
122    ) -> Self {
123        Self {
124            category: category.into(),
125            name: name.into(),
126            status: CheckStatus::Pass,
127            message: message.into(),
128            hint: None,
129            detail: None,
130        }
131    }
132
133    /// Create a warning check item.
134    #[must_use]
135    pub fn warn(
136        category: impl Into<String>,
137        name: impl Into<String>,
138        message: impl Into<String>,
139        hint: impl Into<String>,
140    ) -> Self {
141        Self {
142            category: category.into(),
143            name: name.into(),
144            status: CheckStatus::Warn,
145            message: message.into(),
146            hint: Some(hint.into()),
147            detail: None,
148        }
149    }
150
151    /// Create a failing check item.
152    #[must_use]
153    pub fn fail(
154        category: impl Into<String>,
155        name: impl Into<String>,
156        message: impl Into<String>,
157        hint: impl Into<String>,
158    ) -> Self {
159        Self {
160            category: category.into(),
161            name: name.into(),
162            status: CheckStatus::Fail,
163            message: message.into(),
164            hint: Some(hint.into()),
165            detail: None,
166        }
167    }
168
169    /// Attach a detail string to this check item (builder pattern).
170    #[must_use]
171    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
172        self.detail = Some(detail.into());
173        self
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[test]
182    fn test_should_calculate_summary_counts() {
183        let items = vec![
184            CheckItem::pass("cat", "a", "ok"),
185            CheckItem::pass("cat", "b", "ok"),
186            CheckItem::warn("cat", "c", "meh", "fix it"),
187            CheckItem::fail("cat", "d", "bad", "fix now"),
188        ];
189        let summary = DoctorSummary::from_items(&items);
190        assert_eq!(summary.total, 4);
191        assert_eq!(summary.passed, 2);
192        assert_eq!(summary.warned, 1);
193        assert_eq!(summary.failed, 1);
194    }
195
196    #[test]
197    fn test_should_create_report_from_items() {
198        let items = vec![
199            CheckItem::pass("cat", "a", "ok"),
200            CheckItem::fail("cat", "b", "bad", "fix"),
201        ];
202        let report = DoctorReport::from_items(items);
203        assert_eq!(report.summary.total, 2);
204        assert_eq!(report.summary.passed, 1);
205        assert_eq!(report.summary.failed, 1);
206        assert!(!report.timestamp.is_empty());
207    }
208
209    #[test]
210    fn test_should_serialize_report_to_json() {
211        let items = vec![
212            CheckItem::pass("platform_cli", "gh installed", "gh found").with_detail("v2.65.0"),
213            CheckItem::fail(
214                "platform_cli",
215                "gc auth",
216                "not authenticated",
217                "run gc auth login",
218            ),
219        ];
220        let report = DoctorReport::from_items(items);
221        let json = serde_json::to_string(&report).expect("serialize");
222        assert!(json.contains("\"status\":\"pass\""));
223        assert!(json.contains("\"status\":\"fail\""));
224        assert!(json.contains("\"detail\":\"v2.65.0\""));
225        // hint is present on fail item
226        assert!(json.contains("gc auth login"));
227    }
228
229    #[test]
230    fn test_should_skip_none_fields_in_json() {
231        let item = CheckItem::pass("cat", "name", "msg");
232        let json = serde_json::to_string(&item).expect("serialize");
233        assert!(!json.contains("\"hint\""));
234        assert!(!json.contains("\"detail\""));
235    }
236
237    #[test]
238    fn test_should_create_pass_item() {
239        let item = CheckItem::pass("cat", "name", "message");
240        assert_eq!(item.status, CheckStatus::Pass);
241        assert!(item.hint.is_none());
242    }
243
244    #[test]
245    fn test_should_create_warn_item_with_hint() {
246        let item = CheckItem::warn("cat", "name", "message", "hint text");
247        assert_eq!(item.status, CheckStatus::Warn);
248        assert_eq!(item.hint.as_deref(), Some("hint text"));
249    }
250
251    #[test]
252    fn test_should_create_fail_item_with_hint() {
253        let item = CheckItem::fail("cat", "name", "message", "fix this");
254        assert_eq!(item.status, CheckStatus::Fail);
255        assert_eq!(item.hint.as_deref(), Some("fix this"));
256    }
257
258    #[test]
259    fn test_should_attach_detail_via_builder() {
260        let item = CheckItem::pass("cat", "name", "msg").with_detail("v1.0.0");
261        assert_eq!(item.detail.as_deref(), Some("v1.0.0"));
262    }
263}