tftio-lib 0.1.0

Shared CLI, agent-mode, and prompt-handling library for tftio Rust tools
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
//! Health check and diagnostics module.
//!
//! This module provides a framework for running health checks on CLI tools
//! with tool-specific diagnostics.

use crate::{
    JsonOutput,
    types::{DoctorCheck, RepoInfo},
};
use serde_json::{Map, Value, json};
use std::fmt::Write as _;

/// Structured doctor report reusable for text and JSON output.
#[derive(Debug, Clone)]
pub struct DoctorReport {
    header: String,
    checks: Vec<DoctorCheck>,
    errors: Vec<String>,
    warnings: Vec<String>,
    info: Vec<String>,
    version: Option<String>,
    details: Map<String, Value>,
}

impl DoctorReport {
    /// Create an empty doctor report.
    #[must_use]
    pub fn new(header: impl Into<String>) -> Self {
        Self {
            header: header.into(),
            checks: Vec::new(),
            errors: Vec::new(),
            warnings: Vec::new(),
            info: Vec::new(),
            version: None,
            details: Map::new(),
        }
    }

    /// Create a doctor report scaffold for a tool using the standard header, version, and checks.
    #[must_use]
    pub fn for_tool<T: DoctorChecks>(tool: &T) -> Self {
        Self::with_tool_header(tool, format!("🏥 {} health check", T::repo_info().name))
    }

    /// Create a doctor report scaffold for a tool with a caller-provided header.
    #[must_use]
    pub fn with_tool_header<T: DoctorChecks>(tool: &T, header: impl Into<String>) -> Self {
        Self::new(header)
            .with_checks(tool.tool_checks())
            .with_version(T::current_version())
    }

    /// Set the report checks.
    #[must_use]
    pub fn with_checks(mut self, checks: Vec<DoctorCheck>) -> Self {
        self.checks = checks;
        self
    }

    /// Set the reported version string.
    #[must_use]
    pub fn with_version(mut self, version: impl Into<String>) -> Self {
        self.version = Some(version.into());
        self
    }

    /// Add an error line.
    #[must_use]
    pub fn with_error(mut self, error: impl Into<String>) -> Self {
        self.errors.push(error.into());
        self
    }

    /// Add a warning line.
    #[must_use]
    pub fn with_warning(mut self, warning: impl Into<String>) -> Self {
        self.warnings.push(warning.into());
        self
    }

    /// Add an informational line.
    #[must_use]
    pub fn with_info(mut self, info: impl Into<String>) -> Self {
        self.info.push(info.into());
        self
    }

    /// Add a custom JSON detail field.
    #[must_use]
    pub fn with_detail(mut self, key: impl Into<String>, value: Value) -> Self {
        self.details.insert(key.into(), value);
        self
    }

    /// Access the underlying checks.
    #[must_use]
    pub fn checks(&self) -> &[DoctorCheck] {
        &self.checks
    }

    fn failed_checks(&self) -> usize {
        self.checks.iter().filter(|check| !check.passed).count()
    }

    /// Return the process exit code implied by this report.
    #[must_use]
    pub fn exit_code(&self) -> i32 {
        i32::from(self.failed_checks() > 0 || !self.errors.is_empty())
    }

    /// Render the report as JSON.
    #[must_use]
    pub fn to_json_value(&self) -> Value {
        let mut value = json!({
            "ok": self.exit_code() == 0,
            "header": self.header,
            "checks": self
                .checks
                .iter()
                .map(|check| json!({
                    "name": check.name,
                    "passed": check.passed,
                    "message": check.message,
                }))
                .collect::<Vec<_>>(),
            "errors": self.errors,
            "warnings": self.warnings,
            "info": self.info,
            "version": self.version,
        });

        if let Some(object) = value.as_object_mut() {
            for (key, detail) in &self.details {
                object.insert(key.clone(), detail.clone());
            }
        }
        value
    }

    /// Render the report as plain text.
    #[must_use]
    pub fn render_text(&self) -> String {
        let mut output = String::new();
        output.push_str(&self.header);
        output.push('\n');
        output.push_str(&"=".repeat(self.header.chars().count()));
        output.push_str("\n\n");

        if !self.checks.is_empty() {
            output.push_str("Configuration:\n");
            for check in &self.checks {
                if check.passed {
                    writeln!(&mut output, "{}", check.name).unwrap_or_default();
                } else {
                    writeln!(&mut output, "{}", check.name).unwrap_or_default();
                    if let Some(message) = &check.message {
                        writeln!(&mut output, "     {message}").unwrap_or_default();
                    }
                }
            }
            output.push('\n');
        }

        if !self.info.is_empty() {
            output.push_str("Info:\n");
            for info in &self.info {
                writeln!(&mut output, "  ℹ️  {info}").unwrap_or_default();
            }
            output.push('\n');
        }

        if !self.warnings.is_empty() {
            output.push_str("Warnings:\n");
            for warning in &self.warnings {
                writeln!(&mut output, "  ⚠️  {warning}").unwrap_or_default();
            }
            output.push('\n');
        }

        if self.exit_code() == 0 {
            output.push_str("✨ Everything looks healthy!\n");
        } else {
            output.push_str("❌ Issues found - see above for details\n");
        }

        output
    }

    /// Emit the report in the selected format and return its exit code.
    #[must_use]
    pub fn emit_output(&self, output: JsonOutput) -> i32 {
        if output.is_json() {
            print_doctor_report_json(self)
        } else {
            print_doctor_report_text(self)
        }
    }
}

/// Trait for tools that support doctor health checks.
///
/// Implement this trait to provide tool-specific health checks.
pub trait DoctorChecks {
    /// Get the repository information for this tool.
    fn repo_info() -> RepoInfo;

    /// Get the current version of this tool.
    fn current_version() -> &'static str;

    /// Run tool-specific health checks.
    ///
    /// Return a vector of check results. Default implementation returns empty vector.
    fn tool_checks(&self) -> Vec<DoctorCheck> {
        Vec::new()
    }
}

/// Run doctor command to check health and configuration.
///
/// Returns exit code: 0 if healthy, 1 if issues found.
///
/// # Type Parameters
/// * `T` - A type that implements `DoctorChecks`
pub fn run_doctor<T: DoctorChecks>(tool: &T) -> i32 {
    let header = format!("🏥 {} health check", T::repo_info().name);
    run_doctor_with_output_and_header(tool, &header, JsonOutput::Text)
}

fn build_doctor_report<T: DoctorChecks>(tool: &T, header: &str) -> DoctorReport {
    DoctorReport::with_tool_header(tool, header)
}

fn render_doctor_with_header<T: DoctorChecks>(tool: &T, header: &str) -> (String, i32) {
    let report = build_doctor_report(tool, header);
    (report.render_text(), report.exit_code())
}

/// Run doctor output with a custom header.
pub fn run_doctor_with_header<T: DoctorChecks>(tool: &T, header: &str) -> i32 {
    run_doctor_with_output_and_header(tool, header, JsonOutput::Text)
}

/// Run doctor output in the selected format.
pub fn run_doctor_with_output<T: DoctorChecks>(tool: &T, output: JsonOutput) -> i32 {
    let header = format!("🏥 {} health check", T::repo_info().name);
    run_doctor_with_output_and_header(tool, &header, output)
}

/// Run doctor output with a custom header and output mode.
pub fn run_doctor_with_output_and_header<T: DoctorChecks>(
    tool: &T,
    header: &str,
    output: JsonOutput,
) -> i32 {
    if output.is_json() {
        let report = build_doctor_report(tool, header);
        print_doctor_report_json(&report)
    } else {
        let (rendered, exit_code) = render_doctor_with_header(tool, header);
        print!("{rendered}");
        exit_code
    }
}

/// Print a structured doctor report as JSON and return its exit code.
#[must_use]
pub fn print_doctor_report_json(report: &DoctorReport) -> i32 {
    let value = report.to_json_value();
    match serde_json::to_string_pretty(&value) {
        Ok(rendered) => println!("{rendered}"),
        Err(error) => println!("{}", json!({ "ok": false, "error": error.to_string() })),
    }
    report.exit_code()
}

/// Print a structured doctor report as plain text and return its exit code.
#[must_use]
pub fn print_doctor_report_text(report: &DoctorReport) -> i32 {
    print!("{}", report.render_text());
    report.exit_code()
}

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

    struct TestTool;

    impl DoctorChecks for TestTool {
        fn repo_info() -> RepoInfo {
            RepoInfo::new("workhelix", "test-tool")
        }

        fn current_version() -> &'static str {
            "1.0.0"
        }

        fn tool_checks(&self) -> Vec<DoctorCheck> {
            vec![
                DoctorCheck::pass("Test check 1"),
                DoctorCheck::fail("Test check 2", "This is a failure"),
            ]
        }
    }

    #[test]
    fn test_run_doctor() {
        let tool = TestTool;
        let exit_code = run_doctor(&tool);
        // Should return 1 because we have a failing check
        assert_eq!(exit_code, 1);
    }

    #[test]
    fn test_run_doctor_with_custom_header() {
        let tool = TestTool;
        let (output, exit_code) = render_doctor_with_header(&tool, "Custom Header");
        assert!(output.contains("Custom Header"));
        assert_eq!(exit_code, 1);
    }

    #[test]
    fn doctor_report_json_includes_details() {
        let report = DoctorReport::new("Header")
            .with_checks(vec![DoctorCheck::pass("check")])
            .with_detail("config_file_exists", json!(true));

        let value = report.to_json_value();
        assert_eq!(value["config_file_exists"], json!(true));
        assert_eq!(value["ok"], json!(true));
    }

    #[test]
    fn doctor_report_for_tool_uses_repo_name_version_and_checks() {
        let report = DoctorReport::for_tool(&TestTool);
        let value = report.to_json_value();

        assert_eq!(value["header"], json!("🏥 test-tool health check"));
        assert_eq!(value["version"], json!("1.0.0"));
        assert_eq!(value["checks"].as_array().map(Vec::len), Some(2));
    }

    #[test]
    fn doctor_report_emit_returns_exit_code_for_selected_format() {
        let report = DoctorReport::for_tool(&TestTool);
        assert_eq!(report.emit_output(JsonOutput::Json), 1);
    }

    #[test]
    fn run_doctor_with_output_supports_json_mode() {
        let tool = TestTool;
        let exit_code = run_doctor_with_output(&tool, JsonOutput::Json);
        assert_eq!(exit_code, 1);
    }

    #[test]
    fn doctor_report_accumulates_errors_warnings_and_info() {
        let report = DoctorReport::new("Header")
            .with_checks(vec![
                DoctorCheck::pass("c1"),
                DoctorCheck::fail("c2", "boom"),
            ])
            .with_error("an error")
            .with_warning("a warning")
            .with_info("some info");

        assert_eq!(report.checks().len(), 2);

        let value = report.to_json_value();
        assert_eq!(value["errors"], json!(["an error"]));
        assert_eq!(value["warnings"], json!(["a warning"]));
        assert_eq!(value["info"], json!(["some info"]));
        assert_eq!(value["ok"], json!(false));
    }

    #[test]
    fn doctor_report_exit_code_reflects_errors_without_failing_checks() {
        let clean = DoctorReport::new("Header").with_checks(vec![DoctorCheck::pass("ok")]);
        assert_eq!(clean.exit_code(), 0);

        let with_error = clean.with_error("something went wrong");
        assert_eq!(with_error.exit_code(), 1);
    }

    #[test]
    fn render_text_renders_checks_info_and_warnings() {
        let report = DoctorReport::new("Doctor Report")
            .with_checks(vec![
                DoctorCheck::pass("passing check"),
                DoctorCheck::fail("failing check", "the failure detail"),
            ])
            .with_info("informational note")
            .with_warning("cautionary note");

        let text = report.render_text();
        assert!(text.contains("Doctor Report"), "header missing: {text}");
        assert!(text.contains("Configuration:"), "checks section missing");
        assert!(text.contains("✅ passing check"), "passing mark missing");
        assert!(text.contains("❌ failing check"), "failing mark missing");
        assert!(
            text.contains("the failure detail"),
            "failure message missing"
        );
        assert!(text.contains("Info:"), "info section missing");
        assert!(text.contains("informational note"), "info line missing");
        assert!(text.contains("Warnings:"), "warnings section missing");
        assert!(text.contains("cautionary note"), "warning line missing");
        assert!(text.contains("Issues found"), "unhealthy footer missing");
    }

    #[test]
    fn render_text_reports_healthy_when_all_checks_pass() {
        let report = DoctorReport::new("Healthy").with_checks(vec![DoctorCheck::pass("all good")]);
        let text = report.render_text();
        assert!(
            text.contains("Everything looks healthy"),
            "healthy footer missing"
        );
        assert!(!text.contains("Issues found"), "should not report issues");
    }

    #[test]
    fn run_doctor_with_header_returns_failure_exit_code() {
        let tool = TestTool;
        let exit_code = run_doctor_with_header(&tool, "Custom Doctor Header");
        assert_eq!(exit_code, 1);
    }
}