cmakefmt-rust 1.4.1

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
// 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::Formatter`] — higher-level formatter or CLI failure
//!   that doesn't fit another variant.
//! - [`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}")]
    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. In practice this covers: runtime regex
    /// validation failures on a programmatically-built [`crate::Config`]
    /// (before the config is saved to disk), CLI argument validation
    /// failures, and rendering failures in the config/spec pretty-printers.
    #[error("formatter error: {0}")]
    Formatter(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}"
    )]
    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`, 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,
        }
    }
}

/// 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_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"),
        }
    }
}