checkmate-cli 0.4.1

Checkmate - API Testing Framework CLI
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
//! Run history - Git-connected test run tracking
//!
//! Records test runs with git context (commit, branch, dirty status)
//! for tracking when tests started failing and correlating with code changes.

use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::process::Command;

use serde::{Deserialize, Serialize};

use crate::project::CheckmateProject;
use crate::runner::TestSuiteResult;

fn default_run_type() -> String {
    "test".to_string()
}

/// A recorded test run with git context
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RunRecord {
    /// Unique run ID (e.g., cm-run-a3f)
    pub id: String,
    /// ISO 8601 timestamp
    pub timestamp: String,
    /// Run type: "test" or "diff"
    #[serde(default = "default_run_type")]
    pub run_type: String,
    /// Git context at time of run
    pub git: Option<GitContext>,
    /// Summary of test results
    pub summary: RunSummary,
    /// Diff-specific summary (only for run_type: "diff")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub diff_summary: Option<DiffSummary>,
    /// Spec file that was run
    pub spec_file: Option<String>,
}

/// Git state at time of test run
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GitContext {
    /// Short commit hash
    pub commit: String,
    /// Current branch name
    pub branch: String,
    /// Whether there are uncommitted changes
    pub dirty: bool,
    /// First line of commit message
    pub message: Option<String>,
}

/// Summary statistics for a test run
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RunSummary {
    pub total: usize,
    pub passed: usize,
    pub failed: usize,
    pub errors: usize,
    pub duration_ms: u64,
}

/// Summary of structural differences found in a diff run
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DiffSummary {
    pub additions: usize,
    pub removals: usize,
    pub value_changes: usize,
    pub type_changes: usize,
}

impl RunRecord {
    /// Generate a unique run ID
    pub fn generate_id() -> String {
        format!("cm-run-{}", nanoid::nanoid!(4))
    }

    /// Create a new run record from test results
    pub fn from_suite_result(result: &TestSuiteResult, spec_file: Option<&str>) -> Self {
        let summary = RunSummary {
            total: result.summary.total,
            passed: result.summary.passed,
            failed: result.summary.failed,
            errors: result.summary.errors,
            duration_ms: result.duration_ms,
        };

        Self {
            id: Self::generate_id(),
            timestamp: chrono_lite_timestamp(),
            run_type: "test".to_string(),
            git: GitContext::capture(),
            summary,
            diff_summary: None,
            spec_file: spec_file.map(String::from),
        }
    }

    /// Create a new run record from diff results
    pub fn from_diff_result(
        result: &TestSuiteResult,
        diff_summary: DiffSummary,
        spec_file: Option<&str>,
    ) -> Self {
        let summary = RunSummary {
            total: result.summary.total,
            passed: result.summary.passed,
            failed: result.summary.failed,
            errors: result.summary.errors,
            duration_ms: result.duration_ms,
        };

        Self {
            id: Self::generate_id(),
            timestamp: chrono_lite_timestamp(),
            run_type: "diff".to_string(),
            git: GitContext::capture(),
            summary,
            diff_summary: Some(diff_summary),
            spec_file: spec_file.map(String::from),
        }
    }
}

impl GitContext {
    /// Capture current git state
    pub fn capture() -> Option<Self> {
        // Check if we're in a git repo
        let status = Command::new("git")
            .args(["rev-parse", "--git-dir"])
            .output()
            .ok()?;

        if !status.status.success() {
            return None;
        }

        let commit = Command::new("git")
            .args(["rev-parse", "--short", "HEAD"])
            .output()
            .ok()
            .and_then(|o| {
                if o.status.success() {
                    Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
                } else {
                    None
                }
            })?;

        let branch = Command::new("git")
            .args(["branch", "--show-current"])
            .output()
            .ok()
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
            .unwrap_or_default();

        let dirty = Command::new("git")
            .args(["status", "--porcelain"])
            .output()
            .ok()
            .map(|o| !o.stdout.is_empty())
            .unwrap_or(false);

        let message = Command::new("git")
            .args(["log", "-1", "--format=%s"])
            .output()
            .ok()
            .and_then(|o| {
                if o.status.success() {
                    let msg = String::from_utf8_lossy(&o.stdout).trim().to_string();
                    if msg.is_empty() { None } else { Some(msg) }
                } else {
                    None
                }
            });

        Some(GitContext {
            commit,
            branch,
            dirty,
            message,
        })
    }
}

/// Save a run record to the project's runs.jsonl
pub fn save_run(project: &CheckmateProject, record: &RunRecord) -> Result<(), std::io::Error> {
    let runs_file = project.runs_file();

    // Ensure parent directory exists
    if let Some(parent) = runs_file.parent() {
        fs::create_dir_all(parent)?;
    }

    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(&runs_file)?;

    let json = serde_json::to_string(record)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;

    writeln!(file, "{}", json)?;
    Ok(())
}

/// Load run history from project
pub fn load_history(project: &CheckmateProject) -> Result<Vec<RunRecord>, std::io::Error> {
    let runs_file = project.runs_file();

    if !runs_file.exists() {
        return Ok(Vec::new());
    }

    let file = fs::File::open(&runs_file)?;
    let reader = BufReader::new(file);

    let mut records = Vec::new();
    for line in reader.lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        if let Ok(record) = serde_json::from_str::<RunRecord>(&line) {
            records.push(record);
        }
    }

    Ok(records)
}

/// Load history filtered by various criteria
pub fn load_history_filtered(
    project: &CheckmateProject,
    commit: Option<&str>,
    spec: Option<&str>,
    limit: usize,
) -> Result<Vec<RunRecord>, std::io::Error> {
    let mut records = load_history(project)?;

    // Filter by commit
    if let Some(commit_filter) = commit {
        records.retain(|r| {
            r.git.as_ref()
                .map(|g| g.commit.starts_with(commit_filter))
                .unwrap_or(false)
        });
    }

    // Filter by spec file
    if let Some(spec_filter) = spec {
        records.retain(|r| {
            r.spec_file.as_ref()
                .map(|s| s.contains(spec_filter))
                .unwrap_or(false)
        });
    }

    // Reverse to show most recent first, then limit
    records.reverse();
    records.truncate(limit);

    Ok(records)
}

/// Find a specific run by ID
pub fn find_run(project: &CheckmateProject, run_id: &str) -> Result<Option<RunRecord>, std::io::Error> {
    let records = load_history(project)?;
    Ok(records.into_iter().find(|r| r.id == run_id))
}

/// Simple ISO 8601 timestamp without external dependency
fn chrono_lite_timestamp() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};

    let duration = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();

    let secs = duration.as_secs();

    // Convert to date/time components (simplified, assumes UTC)
    let days_since_epoch = secs / 86400;
    let time_of_day = secs % 86400;

    // Calculate year, month, day from days since 1970-01-01
    let (year, month, day) = days_to_ymd(days_since_epoch as i64);

    let hours = time_of_day / 3600;
    let minutes = (time_of_day % 3600) / 60;
    let seconds = time_of_day % 60;

    format!(
        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
        year, month, day, hours, minutes, seconds
    )
}

/// Convert days since epoch to year/month/day
fn days_to_ymd(days: i64) -> (i32, u32, u32) {
    // Simplified calculation
    let mut remaining_days = days;
    let mut year = 1970i32;

    loop {
        let days_in_year = if is_leap_year(year) { 366 } else { 365 };
        if remaining_days < days_in_year {
            break;
        }
        remaining_days -= days_in_year;
        year += 1;
    }

    let days_in_months: [i64; 12] = if is_leap_year(year) {
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    };

    let mut month = 1u32;
    for days_in_month in days_in_months.iter() {
        if remaining_days < *days_in_month {
            break;
        }
        remaining_days -= days_in_month;
        month += 1;
    }

    let day = remaining_days as u32 + 1;

    (year, month, day)
}

fn is_leap_year(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

/// Format a run record for display
pub fn format_run_short(record: &RunRecord) -> String {
    let status = if record.summary.failed > 0 || record.summary.errors > 0 {
        "✗"
    } else {
        "✓"
    };

    let git_info = record.git.as_ref()
        .map(|g| {
            let dirty_marker = if g.dirty { "*" } else { "" };
            format!(" @ {}{}", g.commit, dirty_marker)
        })
        .unwrap_or_default();

    let type_tag = if record.run_type == "diff" { " [diff]" } else { "" };

    format!(
        "{} {} {} {}/{} passed{}{}",
        status,
        record.id,
        &record.timestamp[..10],
        record.summary.passed,
        record.summary.total,
        type_tag,
        git_info
    )
}

/// Format a run record for detailed display
pub fn format_run_detail(record: &RunRecord) -> String {
    let mut out = String::new();

    out.push_str(&format!("Run: {}\n", record.id));
    out.push_str(&format!("Type: {}\n", record.run_type));
    out.push_str(&format!("Time: {}\n", record.timestamp));

    if let Some(ref spec) = record.spec_file {
        out.push_str(&format!("Spec: {}\n", spec));
    }

    out.push_str(&format!(
        "Results: {}/{} passed, {} failed, {} errors ({}ms)\n",
        record.summary.passed,
        record.summary.total,
        record.summary.failed,
        record.summary.errors,
        record.summary.duration_ms
    ));

    if let Some(ref ds) = record.diff_summary {
        out.push_str(&format!(
            "\nDiff Summary: +{} -{} ~{} value, ~{} type\n",
            ds.additions, ds.removals, ds.value_changes, ds.type_changes
        ));
    }

    if let Some(ref git) = record.git {
        out.push_str("\nGit Context:\n");
        out.push_str(&format!("  Commit: {}\n", git.commit));
        if !git.branch.is_empty() {
            out.push_str(&format!("  Branch: {}\n", git.branch));
        }
        out.push_str(&format!("  Dirty: {}\n", if git.dirty { "yes" } else { "no" }));
        if let Some(ref msg) = git.message {
            out.push_str(&format!("  Message: {}\n", msg));
        }
    }

    out
}

// CLI command handlers

/// Run the history command
pub fn run_history(
    commit: Option<&str>,
    spec: Option<&str>,
    limit: usize,
) -> Result<(), Box<dyn std::error::Error>> {
    let project = CheckmateProject::discover().ok_or_else(|| {
        "No .checkmate/ found. Run 'cm init' first."
    })?;

    let records = load_history_filtered(&project, commit, spec, limit)?;

    if records.is_empty() {
        println!("No runs recorded yet.");
        println!("Run 'cm test run' or 'cm diff run' to record history.");
        return Ok(());
    }

    println!("Run History (most recent first):\n");

    for record in &records {
        println!("{}", format_run_short(record));
    }

    if records.len() == limit {
        println!("\n(showing {} most recent, use -n to see more)", limit);
    }

    Ok(())
}

/// Run the show command
pub fn run_show(run_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let project = CheckmateProject::discover().ok_or_else(|| {
        "No .checkmate/ found. Run 'cm init' first."
    })?;

    let record = find_run(&project, run_id)?;

    match record {
        Some(r) => {
            println!("{}", format_run_detail(&r));
        }
        None => {
            eprintln!("Run '{}' not found.", run_id);
            eprintln!("Use 'cm history' to see available runs.");
            std::process::exit(1);
        }
    }

    Ok(())
}