cmakefmt-rust 1.7.0

A fast, correct CMake formatter
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
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
// SPDX-FileCopyrightText: Copyright 2026 Puneet Matharu
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Structured error types returned by parsing, config loading, and formatting.
//!
//! Every fallible crate API returns [`Result`], which is
//! `std::result::Result<T, Error>`. The [`enum@Error`] enum
//! distinguishes sources:
//!
//! - [`Error::Parse`] — CMake source failed to parse; line/column
//!   info is 1-based.
//! - [`Error::Config`] — a `.cmakefmt.yaml|yml|toml` (or
//!   `from_yaml_str` input) failed to deserialise, or a programmatic
//!   [`crate::Config`] had an invalid regex pattern.
//! - [`Error::Spec`] — a `commands:` override file (or string)
//!   failed to deserialise, or the built-in spec file itself did.
//! - [`Error::Io`] — filesystem or stream I/O failure.
//! - [`Error::CliArg`] — a CLI argument validation failure
//!   (incompatible flag combinations, missing required arguments,
//!   conflicting overrides).
//! - [`Error::InvalidRegex`] — a regex pattern from the user (CLI
//!   flag, config file, or spec override) failed to compile.
//! - [`Error::Render`] — a failure rendering a Config or Spec to
//!   text (TOML / YAML / JSON), or building a machine-format
//!   report (SARIF / Checkstyle / JUnit / JSON edit).
//! - [`Error::LegacyMigration`] — a failure during legacy
//!   `cmake-format` config migration.
//! - [`Error::Formatter`] — miscellaneous higher-level formatter
//!   or CLI failure that does not fit any of the structured
//!   sub-variants above. Prefer [`Error::CliArg`],
//!   [`Error::InvalidRegex`], [`Error::Render`], or
//!   [`Error::LegacyMigration`] when applicable.
//! - [`Error::LayoutTooWide`] — *only* produced when
//!   [`crate::Config::require_valid_layout`] is enabled and a
//!   formatted line exceeded the configured width. Not a bug in the
//!   formatter — a signal to the caller.
//!
//! [`crate::error::FileParseError`] and
//! [`crate::error::ParseDiagnostic`] carry structured line/column
//! metadata (1-based, both) so editor integrations can point at the
//! offending source without re-parsing the error string.

use std::fmt;
use std::path::PathBuf;

use thiserror::Error;

/// Structured config/spec deserialization failure metadata used for
/// user-facing diagnostics.
///
/// When present, `line` and `column` are **1-based** (not 0-based),
/// matching the convention used by editors and the `ParseDiagnostic`
/// counterpart for CMake source errors.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct FileParseError {
    /// Parser format name, such as `TOML` or `YAML`.
    pub format: &'static str,
    /// Human-readable parser message.
    pub message: Box<str>,
    /// Optional 1-based line number.
    pub line: Option<usize>,
    /// Optional 1-based column number.
    pub column: Option<usize>,
}

impl fmt::Display for FileParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

/// Crate-owned parser diagnostics used by [`enum@Error`] without exposing `pest`
/// internals in the public API.
///
/// `line` and `column` are **1-based** and count columns by characters
/// (not bytes), so multi-byte UTF-8 characters occupy a single
/// column.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParseDiagnostic {
    /// Human-readable parser detail.
    pub message: Box<str>,
    /// 1-based source line number.
    pub line: usize,
    /// 1-based source column number.
    pub column: usize,
}

impl fmt::Display for ParseDiagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

/// Stable parse error returned by the public library API.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("parse error in {display_name}: {diagnostic}")]
#[non_exhaustive]
pub struct ParseError {
    /// Human-facing source name, for example a path or `<stdin>`.
    pub display_name: String,
    /// The source text that failed to parse.
    pub source_text: Box<str>,
    /// The 1-based source line number where this parser chunk started.
    pub start_line: usize,
    /// Structured parser diagnostic.
    pub diagnostic: ParseDiagnostic,
}

impl ParseError {
    fn with_display_name(mut self, display_name: impl Into<String>) -> Self {
        self.display_name = display_name.into();
        self
    }
}

/// Stable config-file parse error returned by the public library API.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("config error in {path}: {details}")]
#[non_exhaustive]
pub struct ConfigError {
    /// The config file that failed to deserialize.
    pub path: PathBuf,
    /// Structured parser details for the failure.
    pub details: FileParseError,
}

impl ConfigError {
    /// Build a `ConfigError` from its component parts. Used at the
    /// many call sites that wrap `serde` parser errors into the
    /// crate's structured error type.
    pub(crate) fn new(
        path: PathBuf,
        format: &'static str,
        message: impl Into<Box<str>>,
        line: Option<usize>,
        column: Option<usize>,
    ) -> Self {
        Self {
            path,
            details: FileParseError {
                format,
                message: message.into(),
                line,
                column,
            },
        }
    }
}

/// Stable command-spec parse error returned by the public library API.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("spec error in {path}: {details}")]
#[non_exhaustive]
pub struct SpecError {
    /// The spec file that failed to deserialize.
    pub path: PathBuf,
    /// Structured parser details for the failure.
    pub details: FileParseError,
}

impl SpecError {
    /// Build a `SpecError` from its component parts. Mirror of
    /// [`ConfigError::new`] for spec-file parse failures.
    pub(crate) fn new(
        path: PathBuf,
        format: &'static str,
        message: impl Into<Box<str>>,
        line: Option<usize>,
        column: Option<usize>,
    ) -> Self {
        Self {
            path,
            details: FileParseError {
                format,
                message: message.into(),
                line,
                column,
            },
        }
    }
}

/// Errors that can be returned by parsing, config loading, spec loading, or
/// formatting operations.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
    /// A parser error annotated with source text and line-offset context.
    #[error("{0}")]
    Parse(#[from] ParseError),

    /// A user config parse error.
    #[error("{0}")]
    Config(#[from] ConfigError),

    /// A built-in or user override spec parse error.
    #[error("{0}")]
    Spec(#[from] SpecError),

    /// A filesystem or stream I/O failure where no path is attached.
    /// Use [`Error::io_at`] (or the [`IoResultExt::with_path`] adapter)
    /// when reporting an error against a specific file — the
    /// path-bearing variant is far more useful in user-facing
    /// diagnostics.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// A filesystem I/O failure annotated with the path that caused
    /// it. Used at every site where we have a path in scope; far more
    /// actionable than a bare `permission denied` from [`Error::Io`].
    #[error("I/O error reading {path}: {source}")]
    #[non_exhaustive]
    IoAt {
        /// The file or directory that failed.
        path: PathBuf,
        /// The underlying I/O error.
        #[source]
        source: std::io::Error,
    },

    /// A higher-level formatter or CLI error that does not fit another
    /// structured variant. Prefer [`Error::CliArg`], [`Error::InvalidRegex`],
    /// [`Error::Render`], [`Error::LegacyMigration`], or [`Error::IoAt`]
    /// when the failure mode is one of those — `Error::Formatter` is the
    /// catch-all for the small set of cases that legitimately don't fit
    /// any of those categories (e.g. LSP runtime failures, semantic
    /// verification failures, watch-loop infrastructure, git subprocess
    /// failures, spec parsing from in-memory strings without a path).
    #[error("formatter error: {0}")]
    Formatter(String),

    /// A CLI argument validation failure — incompatible flag combinations,
    /// missing required arguments, conflicting overrides.
    #[error("{message}")]
    #[non_exhaustive]
    CliArg {
        /// Human-readable description of what argument combination is
        /// invalid.
        message: String,
    },

    /// A regex pattern from the user (CLI flag, config file, or spec
    /// override) failed to compile or apply.
    #[error("invalid regex {pattern:?}: {source}")]
    #[non_exhaustive]
    InvalidRegex {
        /// The pattern (or named config slot) that failed to compile.
        pattern: String,
        /// The underlying `regex` crate error.
        #[source]
        source: regex::Error,
    },

    /// A failure rendering a [`crate::Config`] or spec to text (TOML /
    /// YAML / JSON), or building a machine-format report (SARIF /
    /// Checkstyle / JUnit / JSON edit). The `format` field names the
    /// target format.
    #[error("failed to render {format}: {message}")]
    #[non_exhaustive]
    Render {
        /// Name of the target format (`"YAML"`, `"TOML"`, `"JSON"`,
        /// `"SARIF"`, etc.).
        format: String,
        /// Human-readable detail of what went wrong.
        message: String,
    },

    /// A failure during legacy `cmake-format` config migration —
    /// parsing the old format, converting it, or writing the
    /// modernised file. The `path` field carries the legacy file the
    /// user was trying to migrate.
    #[error("legacy migration failed for {}: {message}", path.display())]
    #[non_exhaustive]
    LegacyMigration {
        /// The legacy config file being migrated.
        path: PathBuf,
        /// Human-readable description of the migration failure.
        message: String,
    },

    /// A formatted line exceeded the configured line width and
    /// `require_valid_layout` is enabled.
    #[error(
        "line {line_no} is {width} characters wide, exceeding the configured limit of {limit}"
    )]
    #[non_exhaustive]
    LayoutTooWide {
        /// 1-based line number in the formatted output.
        line_no: usize,
        /// Actual character width of the offending line.
        width: usize,
        /// Configured [`crate::Config::line_width`] limit.
        limit: usize,
    },
}

/// Convenience alias for crate-level results.
pub type Result<T> = std::result::Result<T, Error>;

impl Error {
    /// Attach a human-facing source name (e.g. a file path) to a
    /// contextual [`ParseError`]. No-op for any other variant —
    /// `Config`, `Spec`, `Io`, `IoAt`, `Formatter`, `CliArg`,
    /// `InvalidRegex`, `Render`, `LegacyMigration`, and
    /// `LayoutTooWide` already carry the context they need and are
    /// returned unchanged.
    pub fn with_display_name(self, display_name: impl Into<String>) -> Self {
        match self {
            Self::Parse(parse) => Self::Parse(parse.with_display_name(display_name)),
            other => other,
        }
    }

    /// Build an [`Error::IoAt`] variant from a path and an underlying
    /// `io::Error`. Use this at every I/O call site where you have a
    /// path in scope — [`Error::Io`] is reserved for streams (stdout,
    /// stdin) and similar path-less I/O.
    pub fn io_at(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
        Self::IoAt {
            path: path.into(),
            source,
        }
    }

    /// Build an [`Error::CliArg`] variant from a human-readable
    /// description of the invalid argument combination.
    pub fn cli_arg(message: impl Into<String>) -> Self {
        Self::CliArg {
            message: message.into(),
        }
    }

    /// Build an [`Error::InvalidRegex`] variant from the pattern that
    /// failed to compile and the underlying [`regex::Error`].
    pub fn invalid_regex(pattern: impl Into<String>, source: regex::Error) -> Self {
        Self::InvalidRegex {
            pattern: pattern.into(),
            source,
        }
    }

    /// Build an [`Error::Render`] variant from the target format name
    /// and a human-readable failure message.
    pub fn render(format: impl Into<String>, message: impl Into<String>) -> Self {
        Self::Render {
            format: format.into(),
            message: message.into(),
        }
    }

    /// Build an [`Error::LegacyMigration`] variant from the legacy
    /// config path and a human-readable failure message.
    pub fn legacy_migration(path: impl Into<PathBuf>, message: impl Into<String>) -> Self {
        Self::LegacyMigration {
            path: path.into(),
            message: message.into(),
        }
    }
}

/// Extension trait for ergonomic conversion of `io::Result<T>` into
/// the crate's path-bearing `Result<T>`. Reads at call sites as
/// `std::fs::read_to_string(&path).with_path(&path)?` — one extra
/// token compared to `.map_err(Error::Io)?`, with much better
/// diagnostics on failure.
pub trait IoResultExt<T> {
    /// Wrap an `io::Error` with the path that produced it, returning
    /// an [`Error::IoAt`] on failure.
    fn with_path(self, path: impl Into<PathBuf>) -> Result<T>;
}

impl<T> IoResultExt<T> for std::io::Result<T> {
    fn with_path(self, path: impl Into<PathBuf>) -> Result<T> {
        self.map_err(|source| Error::io_at(path, source))
    }
}

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

    #[test]
    fn parse_diagnostic_display_shows_message() {
        let diag = ParseDiagnostic {
            message: "expected argument part".into(),
            line: 5,
            column: 10,
        };
        assert_eq!(diag.to_string(), "expected argument part");
    }

    #[test]
    fn parse_diagnostic_from_parse_error() {
        let source = "if(\n";
        let err = crate::parser::parse(source).unwrap_err();
        if let Error::Parse(ParseError { diagnostic, .. }) = err {
            assert!(diagnostic.line >= 1);
            assert!(diagnostic.column >= 1);
            assert!(!diagnostic.message.is_empty());
        } else {
            panic!("expected Parse, got {err:?}");
        }
    }

    #[test]
    fn error_parse_display() {
        let err = Error::Parse(ParseError {
            display_name: "test.cmake".to_owned(),
            source_text: "if(\n".into(),
            start_line: 1,
            diagnostic: ParseDiagnostic {
                message: "expected argument part".into(),
                line: 1,
                column: 4,
            },
        });
        let msg = err.to_string();
        assert!(msg.contains("test.cmake"));
        assert!(msg.contains("expected argument part"));
    }

    #[test]
    fn error_config_display() {
        let err = Error::Config(ConfigError {
            path: std::path::PathBuf::from("bad.yaml"),
            details: FileParseError {
                format: "YAML",
                message: "unexpected key".into(),
                line: Some(3),
                column: Some(1),
            },
        });
        let msg = err.to_string();
        assert!(msg.contains("bad.yaml"));
        assert!(msg.contains("unexpected key"));
    }

    #[test]
    fn error_spec_display() {
        let err = Error::Spec(SpecError {
            path: std::path::PathBuf::from("commands.yaml"),
            details: FileParseError {
                format: "YAML",
                message: "invalid nargs".into(),
                line: None,
                column: None,
            },
        });
        let msg = err.to_string();
        assert!(msg.contains("commands.yaml"));
        assert!(msg.contains("invalid nargs"));
    }

    #[test]
    fn error_io_display() {
        let err = Error::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "file not found",
        ));
        assert!(err.to_string().contains("file not found"));
    }

    #[test]
    fn error_formatter_display() {
        let err = Error::Formatter("something went wrong".to_owned());
        assert!(err.to_string().contains("something went wrong"));
    }

    #[test]
    fn error_cli_arg_display() {
        let err = Error::CliArg {
            message: "--foo cannot be combined with --bar".to_owned(),
        };
        let msg = err.to_string();
        assert!(msg.contains("--foo"));
        assert!(msg.contains("--bar"));
    }

    #[test]
    fn error_invalid_regex_display() {
        // Build a bad regex pattern at runtime so clippy's
        // `invalid_regex` lint doesn't trip on the literal.
        let bad_pattern = ["[", "invalid", "("].concat();
        let source = regex::Regex::new(&bad_pattern).unwrap_err();
        let err = Error::InvalidRegex {
            pattern: bad_pattern.clone(),
            source,
        };
        let msg = err.to_string();
        assert!(msg.contains(&bad_pattern));
        assert!(msg.contains("invalid regex"));
    }

    #[test]
    fn error_render_display() {
        let err = Error::Render {
            format: "YAML".to_owned(),
            message: "unsupported type".to_owned(),
        };
        let msg = err.to_string();
        assert!(msg.contains("YAML"));
        assert!(msg.contains("unsupported type"));
    }

    #[test]
    fn error_legacy_migration_display() {
        let err = Error::LegacyMigration {
            path: std::path::PathBuf::from("legacy.py"),
            message: "section is not a table".to_owned(),
        };
        let msg = err.to_string();
        assert!(msg.contains("legacy.py"));
        assert!(msg.contains("section is not a table"));
    }

    #[test]
    fn error_layout_too_wide_display() {
        let err = Error::LayoutTooWide {
            line_no: 42,
            width: 120,
            limit: 80,
        };
        let msg = err.to_string();
        assert!(msg.contains("42"));
        assert!(msg.contains("120"));
        assert!(msg.contains("80"));
    }

    #[test]
    fn with_display_name_updates_parse() {
        let err = Error::Parse(ParseError {
            display_name: "original".to_owned(),
            source_text: "set(\n".into(),
            start_line: 1,
            diagnostic: ParseDiagnostic {
                message: "test".into(),
                line: 1,
                column: 5,
            },
        });
        let renamed = err.with_display_name("renamed.cmake");
        match renamed {
            Error::Parse(ParseError { display_name, .. }) => {
                assert_eq!(display_name, "renamed.cmake");
            }
            _ => panic!("expected Parse"),
        }
    }

    #[test]
    fn with_display_name_passes_through_non_parse_errors() {
        let err = Error::Formatter("test".to_owned());
        let result = err.with_display_name("ignored");
        match result {
            Error::Formatter(msg) => assert_eq!(msg, "test"),
            _ => panic!("expected Formatter to pass through"),
        }
    }

    #[test]
    fn io_error_converts_from_std() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
        let err: Error = io_err.into();
        match err {
            Error::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied),
            _ => panic!("expected Io variant"),
        }
    }
}