harn-cli 0.10.122

CLI for the Harn programming language — run, test, REPL, format, and lint
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
use std::path::Path;
use std::process;

use harn_fmt::{format_source_opts, line_width_violations, FmtOptions};
use harn_parser::DiagnosticCode as Code;
use serde::Serialize;

use crate::commands::declares_expected_invalid;
use crate::json_envelope::{JsonEnvelope, JsonError};

pub(crate) const FMT_SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Clone, Serialize)]
pub(crate) struct FmtReport {
    pub files: Vec<FmtFileReport>,
    pub summary: FmtSummary,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct FmtFileReport {
    pub path: String,
    pub status: FmtFileStatus,
    pub diff_lines_changed: usize,
    pub diagnostics: Vec<FmtDiagnostic>,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum FmtFileStatus {
    Formatted,
    AlreadyFormatted,
    Skipped,
    Error,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct FmtDiagnostic {
    pub code: String,
    pub message: String,
}

#[derive(Debug, Clone, Default, Serialize)]
pub(crate) struct FmtSummary {
    pub formatted: usize,
    pub already_formatted: usize,
    pub skipped: usize,
    pub errors: usize,
}

/// Whether `harn fmt` should rewrite files in place or just report drift.
#[derive(Clone, Copy, Debug)]
pub(crate) enum FmtMode {
    /// Rewrite files that aren't already formatted.
    Write,
    /// Only report files that would be reformatted; never write to disk.
    Check,
}

impl FmtMode {
    pub(crate) fn from_check_flag(check: bool) -> Self {
        if check {
            Self::Check
        } else {
            Self::Write
        }
    }

    fn is_check(self) -> bool {
        matches!(self, Self::Check)
    }
}

/// Format one or more files or directories. Accepts multiple targets.
pub(crate) fn fmt_targets(targets: &[&str], mode: FmtMode, opts: &FmtOptions) {
    let report = fmt_targets_report(targets, mode, opts);
    print_text_report(&report);
    if report.summary.errors > 0 {
        process::exit(1);
    }
}

pub(crate) fn fmt_targets_json(
    targets: &[&str],
    mode: FmtMode,
    opts: &FmtOptions,
) -> JsonEnvelope<FmtReport> {
    let report = fmt_targets_report(targets, mode, opts);
    if report.summary.errors > 0 {
        JsonEnvelope {
            schema_version: FMT_SCHEMA_VERSION,
            ok: false,
            data: Some(report),
            error: Some(JsonError {
                code: "fmt_failed".to_string(),
                message: "one or more files failed formatting checks".to_string(),
                details: serde_json::Value::Null,
            }),
            warnings: Vec::new(),
        }
    } else {
        JsonEnvelope::ok(FMT_SCHEMA_VERSION, report)
    }
}

pub(crate) fn fmt_targets_report(targets: &[&str], mode: FmtMode, opts: &FmtOptions) -> FmtReport {
    let mut files = Vec::new();
    for target in targets {
        let path = Path::new(target);
        if path.is_dir() {
            files.extend(super::super::collect_source_targets(&[target], true, false).harn);
        } else {
            files.push(path.to_path_buf());
        }
    }
    files.sort();
    files.dedup();
    if files.is_empty() {
        return FmtReport {
            files: Vec::new(),
            summary: FmtSummary {
                errors: 1,
                ..FmtSummary::default()
            },
        };
    }
    let mut report = FmtReport {
        files: Vec::new(),
        summary: FmtSummary::default(),
    };
    for file in files {
        let path_str = file.to_string_lossy();
        let file_report = fmt_file_inner(&path_str, mode, opts);
        match file_report.status {
            FmtFileStatus::Formatted => report.summary.formatted += 1,
            FmtFileStatus::AlreadyFormatted => report.summary.already_formatted += 1,
            FmtFileStatus::Skipped => report.summary.skipped += 1,
            FmtFileStatus::Error => report.summary.errors += 1,
        }
        report.files.push(file_report);
    }
    report
}

/// Format a single file.
fn fmt_file_inner(path: &str, mode: FmtMode, opts: &FmtOptions) -> FmtFileReport {
    if !is_harn_source_path(Path::new(path)) {
        return fmt_error(
            path,
            "unsupported_extension",
            format!("harn fmt only formats .harn files; refusing explicit non-Harn target {path}"),
        );
    }

    let source = match std::fs::read_to_string(path) {
        Ok(source) => source,
        Err(error) => return fmt_error(path, "io", format!("Error reading {path}: {error}")),
    };

    let formatted = match format_source_opts(&source, opts) {
        Ok(formatted) => formatted,
        // A fixture that declares its own unparseability is not drift, and the
        // formatter has nothing to say about it. Only the parse failure is
        // excused: a declared-invalid fixture that parses is formatted like any
        // other file, which is why this fork lives here and not in the walk.
        Err(_) if declares_expected_invalid(Path::new(path)) => {
            return FmtFileReport {
                path: path.to_string(),
                status: FmtFileStatus::Skipped,
                diff_lines_changed: 0,
                diagnostics: Vec::new(),
            };
        }
        Err(error) => return fmt_error(path, "format", format!("{path}: {error}")),
    };

    if let Some(violation) = line_width_violations(&formatted, opts.line_width).first() {
        return fmt_error(
            path,
            "line_width",
            format!(
                "{path}: formatted line {} is {} columns wide (maximum {})",
                violation.line, violation.width, opts.line_width
            ),
        );
    }

    if mode.is_check() {
        if source != formatted {
            return FmtFileReport {
                path: path.to_string(),
                status: FmtFileStatus::Error,
                diff_lines_changed: diff_lines_changed(&source, &formatted),
                diagnostics: vec![FmtDiagnostic {
                    code: Code::FormatterWouldReformat.to_string(),
                    message: "would be reformatted".to_string(),
                }],
            };
        }
    } else if source != formatted {
        if let Err(error) = std::fs::write(path, &formatted) {
            return fmt_error(path, "io", format!("Error writing {path}: {error}"));
        }
        return FmtFileReport {
            path: path.to_string(),
            status: FmtFileStatus::Formatted,
            diff_lines_changed: diff_lines_changed(&source, &formatted),
            diagnostics: Vec::new(),
        };
    }

    FmtFileReport {
        path: path.to_string(),
        status: FmtFileStatus::AlreadyFormatted,
        diff_lines_changed: 0,
        diagnostics: Vec::new(),
    }
}

fn is_harn_source_path(path: &Path) -> bool {
    path.extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(|extension| extension == "harn")
}

fn fmt_error(path: &str, code: &str, message: String) -> FmtFileReport {
    FmtFileReport {
        path: path.to_string(),
        status: FmtFileStatus::Error,
        diff_lines_changed: 0,
        diagnostics: vec![FmtDiagnostic {
            code: code.to_string(),
            message,
        }],
    }
}

/// Render the format report for a human reader.
///
/// Denied per-function rather than per-module: this module's `--json` envelope
/// on stdout is correct, and the text report must not share that stream. See
/// [`super::outcome::print_lint_diagnostics`].
#[deny(clippy::print_stdout)]
fn print_text_report(report: &FmtReport) {
    if report.files.is_empty() {
        eprintln!("No .harn files found");
        return;
    }
    for file in &report.files {
        match file.status {
            FmtFileStatus::Formatted => eprintln!("formatted {}", file.path),
            FmtFileStatus::Error => {
                for diagnostic in &file.diagnostics {
                    if diagnostic.code == Code::FormatterWouldReformat.to_string() {
                        eprintln!(
                            "{}: {}: {}",
                            file.path,
                            Code::FormatterWouldReformat,
                            diagnostic.message
                        );
                    } else {
                        eprintln!("{}", diagnostic.message);
                    }
                }
            }
            FmtFileStatus::AlreadyFormatted | FmtFileStatus::Skipped => {}
        }
    }
    // Say what was left alone, in the same words `harn fix` uses. A silent skip
    // is indistinguishable from a fixture the walk never reached.
    let declared_invalid: Vec<&FmtFileReport> = report
        .files
        .iter()
        .filter(|file| matches!(file.status, FmtFileStatus::Skipped))
        .collect();
    if !declared_invalid.is_empty() {
        eprintln!(
            "left {} declared-invalid fixture(s) untouched (sibling `.error` file):",
            declared_invalid.len()
        );
        for file in declared_invalid {
            eprintln!("  {}", file.path);
        }
    }
    // `--check` drift is always auto-fixable by running the formatter in
    // write mode; point the user at it. In write mode these files get status
    // `Formatted` (not `Error`/`FormatterWouldReformat`), so the hint stays
    // silent — and genuine io/format errors are excluded.
    let reformattable = report
        .files
        .iter()
        .filter(|file| {
            matches!(file.status, FmtFileStatus::Error)
                && file
                    .diagnostics
                    .iter()
                    .any(|d| d.code == Code::FormatterWouldReformat.to_string())
        })
        .count();
    if reformattable > 0 {
        eprintln!(
            "\n{reformattable} file(s) would be reformatted — run `harn fmt` (without `--check`) to apply formatting."
        );
    }
}

fn diff_lines_changed(before: &str, after: &str) -> usize {
    let before_lines: Vec<&str> = before.lines().collect();
    let after_lines: Vec<&str> = after.lines().collect();
    let max_len = before_lines.len().max(after_lines.len());
    (0..max_len)
        .filter(|index| before_lines.get(*index) != after_lines.get(*index))
        .count()
}

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

    #[test]
    fn explicit_non_harn_file_targets_are_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("language-catalog.json");
        std::fs::write(&path, "[{ id: \"zig\" }]\n").unwrap();

        let report = fmt_targets_report(
            &[path.to_str().unwrap()],
            FmtMode::Write,
            &FmtOptions::default(),
        );

        assert_eq!(report.summary.errors, 1);
        assert_eq!(report.summary.formatted, 0);
        let file = report.files.first().expect("file report");
        assert!(matches!(file.status, FmtFileStatus::Error));
        assert_eq!(file.diagnostics[0].code, "unsupported_extension");
        assert!(
            file.diagnostics[0]
                .message
                .contains("only formats .harn files"),
            "{}",
            file.diagnostics[0].message
        );
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "[{ id: \"zig\" }]\n"
        );
    }

    #[test]
    fn width_overflow_is_reported_without_rewriting_the_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("main.harn");
        let source = "fn t() { return an_identifier_that_cannot_fit }\n";
        std::fs::write(&path, source).unwrap();

        let report = fmt_targets_report(
            &[path.to_str().unwrap()],
            FmtMode::Write,
            &FmtOptions {
                line_width: 20,
                ..FmtOptions::default()
            },
        );

        assert_eq!(report.summary.errors, 1);
        let file = report.files.first().expect("file report");
        assert_eq!(file.diagnostics[0].code, "line_width");
        assert!(file.diagnostics[0].message.contains("maximum 20"));
        assert_eq!(std::fs::read_to_string(&path).unwrap(), source);
    }

    /// The unparseable source both fixture tests share, so the only difference
    /// between them is whether a sibling `.error` file declares it.
    const UNPARSEABLE: &str = "fn t() { return\n";

    #[test]
    fn a_declared_invalid_fixture_is_skipped_rather_than_failed() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("missing_close_brace.harn");
        std::fs::write(&path, UNPARSEABLE).unwrap();
        std::fs::write(
            dir.path().join("missing_close_brace.error"),
            "HARN-FMT-001\n",
        )
        .unwrap();

        let report = fmt_targets_report(
            &[dir.path().to_str().unwrap()],
            FmtMode::Write,
            &FmtOptions::default(),
        );

        assert_eq!(report.summary.errors, 0, "declared fixture must not fail");
        assert_eq!(report.summary.skipped, 1);
        let file = report.files.first().expect("file report");
        assert!(matches!(file.status, FmtFileStatus::Skipped));
        assert!(file.diagnostics.is_empty());
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            UNPARSEABLE,
            "a skipped fixture must be left byte-identical"
        );
    }

    /// The negative control for the test above. Without this, that test would
    /// also pass if the fix had suppressed every parse failure, which is the
    /// one outcome the declaration must not buy.
    #[test]
    fn an_undeclared_parse_failure_still_fails_the_run() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("corrupt.harn");
        std::fs::write(&path, UNPARSEABLE).unwrap();

        let report = fmt_targets_report(
            &[dir.path().to_str().unwrap()],
            FmtMode::Write,
            &FmtOptions::default(),
        );

        assert_eq!(report.summary.errors, 1);
        assert_eq!(report.summary.skipped, 0);
        let file = report.files.first().expect("file report");
        assert!(matches!(file.status, FmtFileStatus::Error));
        assert_eq!(file.diagnostics[0].code, "format");
    }

    /// The declaration excuses a parse failure, not the file. A fixture that
    /// parses is still the formatter's business — `conformance/errors` carries
    /// runtime-error fixtures that are perfectly well-formed source.
    #[test]
    fn a_declared_invalid_fixture_that_parses_is_still_formatted() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("uncaught_throw.harn");
        std::fs::write(&path, "fn t(){return 1}\n").unwrap();
        std::fs::write(dir.path().join("uncaught_throw.error"), "HARN-RT-001\n").unwrap();

        let report = fmt_targets_report(
            &[dir.path().to_str().unwrap()],
            FmtMode::Write,
            &FmtOptions::default(),
        );

        assert_eq!(
            report.summary.skipped, 0,
            "parseable fixture is not skipped"
        );
        assert_eq!(report.summary.errors, 0);
        assert_eq!(report.summary.formatted, 1);
        assert_ne!(
            std::fs::read_to_string(&path).unwrap(),
            "fn t(){return 1}\n"
        );
    }
}