Skip to main content

cmakefmt/config/
file.rs

1// SPDX-FileCopyrightText: Copyright 2026 Puneet Matharu
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Config-file loading and starter template generation.
6
7use std::collections::HashMap;
8use std::path::{Path, PathBuf};
9
10use serde::Deserialize;
11#[cfg(feature = "cli")]
12use serde::Serialize;
13
14use crate::config::{
15    CaseStyle, Config, DangleAlign, FractionalTabPolicy, LineEnding, PerCommandConfig,
16};
17use crate::error::{Error, FileParseError, Result};
18
19/// The user-config file structure for `.cmakefmt.yaml`, `.cmakefmt.yml`, and
20/// `.cmakefmt.toml`.
21///
22/// All fields are optional — only specified values override the defaults.
23#[derive(Debug, Clone, Deserialize, Default)]
24#[cfg_attr(feature = "cli", derive(schemars::JsonSchema))]
25#[cfg_attr(feature = "cli", schemars(title = "cmakefmt configuration"))]
26#[serde(default, deny_unknown_fields)]
27struct FileConfig {
28    /// JSON Schema reference (ignored at runtime, used by editors for
29    /// autocomplete and validation).
30    #[serde(rename = "$schema")]
31    #[cfg_attr(feature = "cli", schemars(skip))]
32    _schema: Option<String>,
33    /// Command spec overrides (parsed separately by the spec registry).
34    #[cfg_attr(feature = "cli", schemars(skip))]
35    commands: Option<serde_yaml::Value>,
36    /// Formatting options controlling line width, indentation, casing, and layout.
37    format: FormatSection,
38    /// Comment markup processing options.
39    markup: MarkupSection,
40    /// Per-command configuration overrides keyed by lowercase command name.
41    #[serde(rename = "per_command_overrides")]
42    per_command_overrides: HashMap<String, PerCommandConfig>,
43    #[serde(rename = "per_command")]
44    #[cfg_attr(feature = "cli", schemars(skip))]
45    legacy_per_command: HashMap<String, PerCommandConfig>,
46}
47
48#[derive(Debug, Clone, Deserialize, Default)]
49#[cfg_attr(feature = "cli", derive(schemars::JsonSchema))]
50#[serde(default)]
51#[serde(deny_unknown_fields)]
52struct FormatSection {
53    /// Disable formatting entirely and return the source unchanged.
54    disable: Option<bool>,
55    /// Output line-ending style: `unix` (LF), `windows` (CRLF), or `auto` (detect from input).
56    line_ending: Option<LineEnding>,
57    /// Maximum rendered line width before cmakefmt wraps a call. Default: `80`.
58    line_width: Option<usize>,
59    /// Number of spaces per indentation level when `use_tabs` is `false`. Default: `2`.
60    tab_size: Option<usize>,
61    /// Indent with tab characters instead of spaces.
62    use_tabs: Option<bool>,
63    /// How to handle fractional indentation when `use_tabs` is `true`: `use-space` or `round-up`.
64    fractional_tab_policy: Option<FractionalTabPolicy>,
65    /// Maximum number of consecutive blank lines to preserve. Default: `1`.
66    max_empty_lines: Option<usize>,
67    /// Maximum wrapped lines to tolerate before switching to a more vertical layout. Default: `2`.
68    max_hanging_wrap_lines: Option<usize>,
69    /// Maximum positional arguments to keep in a hanging-wrap layout. Default: `6`.
70    max_hanging_wrap_positional_args: Option<usize>,
71    /// Maximum keyword/flag subgroups to keep in a hanging-wrap layout. Default: `2`.
72    max_hanging_wrap_groups: Option<usize>,
73    /// Maximum rows a hanging-wrap positional group may consume before nesting is forced. Default: `2`.
74    max_rows_cmdline: Option<usize>,
75    /// Command names (lowercase) that must always use vertical layout regardless of line width.
76    always_wrap: Option<Vec<String>>,
77    /// Return an error if any formatted output line exceeds `line_width`.
78    require_valid_layout: Option<bool>,
79    /// Place the closing `)` on its own line when a call wraps.
80    dangle_parens: Option<bool>,
81    /// Alignment strategy for a dangling `)`: `prefix`, `open`, or `close`.
82    dangle_align: Option<DangleAlign>,
83    /// Lower heuristic bound used when deciding between compact and wrapped layouts. Default: `4`.
84    min_prefix_length: Option<usize>,
85    /// Upper heuristic bound used when deciding between compact and wrapped layouts. Default: `10`.
86    max_prefix_length: Option<usize>,
87    /// Insert a space before `(` for control-flow commands such as `if`, `foreach`, `while`.
88    space_before_control_paren: Option<bool>,
89    /// Insert a space before `(` for `function()` and `macro()` definitions.
90    space_before_definition_paren: Option<bool>,
91    /// Output casing for command names: `lower`, `upper`, or `unchanged`.
92    command_case: Option<CaseStyle>,
93    /// Output casing for recognized keywords and flags: `lower`, `upper`, or `unchanged`.
94    keyword_case: Option<CaseStyle>,
95}
96
97#[derive(Debug, Clone, Deserialize, Default)]
98#[cfg_attr(feature = "cli", derive(schemars::JsonSchema))]
99#[serde(default)]
100#[serde(deny_unknown_fields)]
101struct MarkupSection {
102    /// Enable markup-aware comment handling.
103    enable_markup: Option<bool>,
104    /// Reflow plain line comments to fit within the configured line width.
105    reflow_comments: Option<bool>,
106    /// Preserve the first comment block in a file literally.
107    first_comment_is_literal: Option<bool>,
108    /// Regex for comments that should never be reflowed.
109    literal_comment_pattern: Option<String>,
110    /// Preferred bullet character when normalizing markup lists. Default: `*`.
111    bullet_char: Option<String>,
112    /// Preferred punctuation for numbered lists when normalizing markup. Default: `.`.
113    enum_char: Option<String>,
114    /// Regex describing fenced literal comment blocks.
115    fence_pattern: Option<String>,
116    /// Regex describing ruler-style comments that should be treated specially.
117    ruler_pattern: Option<String>,
118    /// Minimum ruler length before a hash-only line is treated as a ruler. Default: `10`.
119    hashruler_min_length: Option<usize>,
120    /// Normalize ruler comments when markup handling is enabled.
121    canonicalize_hashrulers: Option<bool>,
122    /// Regex pattern for inline comments explicitly trailing their preceding argument. Default: `#<`.
123    explicit_trailing_pattern: Option<String>,
124}
125
126const CONFIG_FILE_NAME_TOML: &str = ".cmakefmt.toml";
127const CONFIG_FILE_NAME_YAML: &str = ".cmakefmt.yaml";
128const CONFIG_FILE_NAME_YML: &str = ".cmakefmt.yml";
129const CONFIG_FILE_NAMES: &[&str] = &[
130    CONFIG_FILE_NAME_YAML,
131    CONFIG_FILE_NAME_YML,
132    CONFIG_FILE_NAME_TOML,
133];
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub(crate) enum ConfigFileFormat {
137    Toml,
138    Yaml,
139}
140
141impl ConfigFileFormat {
142    pub(crate) fn as_str(self) -> &'static str {
143        match self {
144            Self::Toml => "TOML",
145            Self::Yaml => "YAML",
146        }
147    }
148}
149
150/// Supported `cmakefmt config dump` output formats.
151#[cfg(feature = "cli")]
152#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
153pub enum DumpConfigFormat {
154    /// Emit YAML.
155    Yaml,
156    /// Emit TOML.
157    Toml,
158}
159
160#[cfg(feature = "cli")]
161/// Render a commented starter config in the requested format.
162///
163/// The template is intentionally verbose: every option is introduced by a
164/// short explanatory comment so users can understand the surface without
165/// needing to cross-reference the docs immediately.
166pub fn default_config_template_for(format: DumpConfigFormat) -> String {
167    match format {
168        DumpConfigFormat::Yaml => default_config_template_yaml(),
169        DumpConfigFormat::Toml => default_config_template_toml(),
170    }
171}
172
173#[cfg(feature = "cli")]
174/// Render a resolved runtime config back into the user-facing config schema.
175///
176/// This is primarily used by CLI introspection commands such as
177/// `cmakefmt config show`.
178pub fn render_effective_config(config: &Config, format: DumpConfigFormat) -> Result<String> {
179    let view = EffectiveConfigFile::from(config);
180    match format {
181        DumpConfigFormat::Yaml => serde_yaml::to_string(&view).map_err(|err| {
182            Error::Formatter(format!("failed to render effective config as YAML: {err}"))
183        }),
184        DumpConfigFormat::Toml => toml::to_string_pretty(&view).map_err(|err| {
185            Error::Formatter(format!("failed to render effective config as TOML: {err}"))
186        }),
187    }
188}
189
190/// Render a commented starter config using the default user-facing dump format.
191pub fn default_config_template() -> String {
192    default_config_template_yaml()
193}
194
195#[cfg(feature = "cli")]
196/// Generate a JSON Schema for the cmakefmt config file format.
197///
198/// The output is a pretty-printed JSON string suitable for publishing to
199/// `cmakefmt.dev/schemas/v{version}/schema.json`.
200pub fn generate_json_schema() -> String {
201    let schema = schemars::schema_for!(FileConfig);
202    serde_json::to_string_pretty(&schema).expect("JSON schema serialization failed")
203}
204
205#[cfg(feature = "cli")]
206fn default_config_template_toml() -> String {
207    format!(
208        concat!(
209            "# Default cmakefmt configuration.\n",
210            "# Copy this to .cmakefmt.toml and uncomment the optional settings\n",
211            "# you want to customize.\n\n",
212            "[format]\n",
213            "# Disable formatting entirely (return source unchanged).\n",
214            "# disable = true\n\n",
215            "# Output line-ending style: unix (LF), windows (CRLF), or auto (detect from input).\n",
216            "# line_ending = \"windows\"\n\n",
217            "# Maximum rendered line width before cmakefmt wraps a call.\n",
218            "line_width = {line_width}\n\n",
219            "# Number of spaces per indentation level when use_tabs is false.\n",
220            "tab_size = {tab_size}\n\n",
221            "# Indent with tab characters instead of spaces.\n",
222            "# use_tabs = true\n\n",
223            "# How to handle fractional indentation when use_tabs is true: use-space or round-up.\n",
224            "# fractional_tab_policy = \"round-up\"\n\n",
225            "# Maximum number of consecutive blank lines to preserve.\n",
226            "max_empty_lines = {max_empty_lines}\n\n",
227            "# Maximum wrapped lines to tolerate before switching to a more vertical layout.\n",
228            "max_hanging_wrap_lines = {max_lines_hwrap}\n\n",
229            "# Maximum positional arguments to keep in a hanging-wrap layout.\n",
230            "max_hanging_wrap_positional_args = {max_pargs_hwrap}\n\n",
231            "# Maximum keyword/flag subgroups to keep in a hanging-wrap layout.\n",
232            "max_hanging_wrap_groups = {max_subgroups_hwrap}\n\n",
233            "# Maximum rows a hanging-wrap positional group may consume before nesting is forced.\n",
234            "max_rows_cmdline = {max_rows_cmdline}\n\n",
235            "# Commands that must always use vertical (wrapped) layout.\n",
236            "# always_wrap = [\"target_link_libraries\"]\n\n",
237            "# Return an error if any formatted line exceeds line_width.\n",
238            "# require_valid_layout = true\n\n",
239            "# Put the closing ')' on its own line when a call wraps.\n",
240            "dangle_parens = {dangle_parens}\n\n",
241            "# Alignment strategy for a dangling ')': prefix, open, or close.\n",
242            "dangle_align = \"{dangle_align}\"\n\n",
243            "# Lower heuristic bound used when deciding between compact and wrapped layouts.\n",
244            "min_prefix_length = {min_prefix_chars}\n\n",
245            "# Upper heuristic bound used when deciding between compact and wrapped layouts.\n",
246            "max_prefix_length = {max_prefix_chars}\n\n",
247            "# Insert a space before '(' for control-flow commands like if/foreach.\n",
248            "# space_before_control_paren = true\n\n",
249            "# Insert a space before '(' for function() and macro() definitions.\n",
250            "# space_before_definition_paren = true\n\n",
251            "# Output casing for command names: lower, upper, or unchanged.\n",
252            "command_case = \"{command_case}\"\n\n",
253            "# Output casing for recognized keywords and flags: lower, upper, or unchanged.\n",
254            "keyword_case = \"{keyword_case}\"\n\n",
255            "[markup]\n",
256            "# Enable markup-aware comment handling.\n",
257            "enable_markup = {enable_markup}\n\n",
258            "# Reflow plain line comments to fit within the configured line width.\n",
259            "# reflow_comments = true\n\n",
260            "# Preserve the first comment block in a file literally.\n",
261            "first_comment_is_literal = {first_comment_is_literal}\n\n",
262            "# Preserve comments matching a custom regex literally.\n",
263            "# literal_comment_pattern = \"^\\\\s*NOTE:\"\n\n",
264            "# Preferred bullet character when normalizing markup lists.\n",
265            "bullet_char = \"{bullet_char}\"\n\n",
266            "# Preferred punctuation for numbered lists when normalizing markup.\n",
267            "enum_char = \"{enum_char}\"\n\n",
268            "# Regex describing fenced literal comment blocks.\n",
269            "fence_pattern = '{fence_pattern}'\n\n",
270            "# Regex describing ruler-style comments that should be treated specially.\n",
271            "ruler_pattern = '{ruler_pattern}'\n\n",
272            "# Minimum ruler length before a hash-only line is treated as a ruler.\n",
273            "hashruler_min_length = {hashruler_min_length}\n\n",
274            "# Normalize ruler comments when markup handling is enabled.\n",
275            "canonicalize_hashrulers = {canonicalize_hashrulers}\n\n",
276            "# Regex pattern for inline comments that are explicitly trailing their preceding\n",
277            "# argument (rendered on the same line). Default: '#<'.\n",
278            "# explicit_trailing_pattern = \"#<\"\n\n",
279            "# Uncomment and edit a block like this to override formatting knobs\n",
280            "# for a specific command. This changes layout behavior for that\n",
281            "# command name only; it does not define new command syntax.\n",
282            "#\n",
283            "# [per_command_overrides.my_custom_command]\n",
284            "# Override the line width just for this command.\n",
285            "# line_width = 120\n\n",
286            "# Override command casing just for this command.\n",
287            "# command_case = \"unchanged\"\n\n",
288            "# Override keyword casing just for this command.\n",
289            "# keyword_case = \"upper\"\n\n",
290            "# Override indentation width just for this command.\n",
291            "# tab_size = 4\n\n",
292            "# Override dangling-paren placement just for this command.\n",
293            "# dangle_parens = false\n\n",
294            "# Override dangling-paren alignment just for this command.\n",
295            "# dangle_align = \"prefix\"\n\n",
296            "# Override the positional-argument hanging-wrap threshold just for this command.\n",
297            "# max_hanging_wrap_positional_args = 8\n\n",
298            "# Override the subgroup hanging-wrap threshold just for this command.\n",
299            "# max_hanging_wrap_groups = 3\n\n",
300            "# TOML custom-command specs live under [commands.<name>]. For\n",
301            "# user config, prefer YAML once these specs grow beyond a couple\n",
302            "# of simple flags/kwargs.\n",
303            "# Command specs tell the formatter which tokens are positional\n",
304            "# arguments, standalone flags, and keyword sections.\n",
305            "#\n",
306            "# Example: one positional argument, one flag, and two keyword\n",
307            "# sections that each take one or more values.\n",
308            "#\n",
309            "# [commands.my_custom_command]\n",
310            "# pargs = 1\n",
311            "# flags = [\"QUIET\"]\n",
312            "# kwargs = {{ SOURCES = {{ nargs = \"+\" }}, LIBRARIES = {{ nargs = \"+\" }} }}\n",
313        ),
314        line_width = Config::default().line_width,
315        tab_size = Config::default().tab_size,
316        max_empty_lines = Config::default().max_empty_lines,
317        max_lines_hwrap = Config::default().max_lines_hwrap,
318        max_pargs_hwrap = Config::default().max_pargs_hwrap,
319        max_subgroups_hwrap = Config::default().max_subgroups_hwrap,
320        max_rows_cmdline = Config::default().max_rows_cmdline,
321        dangle_parens = Config::default().dangle_parens,
322        dangle_align = "prefix",
323        min_prefix_chars = Config::default().min_prefix_chars,
324        max_prefix_chars = Config::default().max_prefix_chars,
325        command_case = "lower",
326        keyword_case = "upper",
327        enable_markup = Config::default().enable_markup,
328        first_comment_is_literal = Config::default().first_comment_is_literal,
329        bullet_char = Config::default().bullet_char,
330        enum_char = Config::default().enum_char,
331        fence_pattern = Config::default().fence_pattern,
332        ruler_pattern = Config::default().ruler_pattern,
333        hashruler_min_length = Config::default().hashruler_min_length,
334        canonicalize_hashrulers = Config::default().canonicalize_hashrulers,
335    )
336}
337
338#[cfg(feature = "cli")]
339#[derive(Debug, Clone, Serialize)]
340struct EffectiveConfigFile {
341    format: EffectiveFormatSection,
342    markup: EffectiveMarkupSection,
343    per_command_overrides: HashMap<String, PerCommandConfig>,
344}
345
346#[derive(Debug, Clone, Serialize)]
347#[cfg(feature = "cli")]
348struct EffectiveFormatSection {
349    #[serde(skip_serializing_if = "std::ops::Not::not")]
350    disable: bool,
351    line_ending: LineEnding,
352    line_width: usize,
353    tab_size: usize,
354    use_tabs: bool,
355    fractional_tab_policy: FractionalTabPolicy,
356    max_empty_lines: usize,
357    max_hanging_wrap_lines: usize,
358    max_hanging_wrap_positional_args: usize,
359    max_hanging_wrap_groups: usize,
360    max_rows_cmdline: usize,
361    #[serde(skip_serializing_if = "Vec::is_empty")]
362    always_wrap: Vec<String>,
363    #[serde(skip_serializing_if = "std::ops::Not::not")]
364    require_valid_layout: bool,
365    dangle_parens: bool,
366    dangle_align: DangleAlign,
367    min_prefix_length: usize,
368    max_prefix_length: usize,
369    space_before_control_paren: bool,
370    space_before_definition_paren: bool,
371    command_case: CaseStyle,
372    keyword_case: CaseStyle,
373}
374
375#[derive(Debug, Clone, Serialize)]
376#[cfg(feature = "cli")]
377struct EffectiveMarkupSection {
378    enable_markup: bool,
379    reflow_comments: bool,
380    first_comment_is_literal: bool,
381    literal_comment_pattern: String,
382    bullet_char: String,
383    enum_char: String,
384    fence_pattern: String,
385    ruler_pattern: String,
386    hashruler_min_length: usize,
387    canonicalize_hashrulers: bool,
388    explicit_trailing_pattern: String,
389}
390
391#[cfg(feature = "cli")]
392impl From<&Config> for EffectiveConfigFile {
393    fn from(config: &Config) -> Self {
394        Self {
395            format: EffectiveFormatSection {
396                disable: config.disable,
397                line_ending: config.line_ending,
398                line_width: config.line_width,
399                tab_size: config.tab_size,
400                use_tabs: config.use_tabchars,
401                fractional_tab_policy: config.fractional_tab_policy,
402                max_empty_lines: config.max_empty_lines,
403                max_hanging_wrap_lines: config.max_lines_hwrap,
404                max_hanging_wrap_positional_args: config.max_pargs_hwrap,
405                max_hanging_wrap_groups: config.max_subgroups_hwrap,
406                max_rows_cmdline: config.max_rows_cmdline,
407                always_wrap: config.always_wrap.clone(),
408                require_valid_layout: config.require_valid_layout,
409                dangle_parens: config.dangle_parens,
410                dangle_align: config.dangle_align,
411                min_prefix_length: config.min_prefix_chars,
412                max_prefix_length: config.max_prefix_chars,
413                space_before_control_paren: config.separate_ctrl_name_with_space,
414                space_before_definition_paren: config.separate_fn_name_with_space,
415                command_case: config.command_case,
416                keyword_case: config.keyword_case,
417            },
418            markup: EffectiveMarkupSection {
419                enable_markup: config.enable_markup,
420                reflow_comments: config.reflow_comments,
421                first_comment_is_literal: config.first_comment_is_literal,
422                literal_comment_pattern: config.literal_comment_pattern.clone(),
423                bullet_char: config.bullet_char.clone(),
424                enum_char: config.enum_char.clone(),
425                fence_pattern: config.fence_pattern.clone(),
426                ruler_pattern: config.ruler_pattern.clone(),
427                hashruler_min_length: config.hashruler_min_length,
428                canonicalize_hashrulers: config.canonicalize_hashrulers,
429                explicit_trailing_pattern: config.explicit_trailing_pattern.clone(),
430            },
431            per_command_overrides: config.per_command_overrides.clone(),
432        }
433    }
434}
435
436fn default_config_template_yaml() -> String {
437    format!(
438        concat!(
439            "# yaml-language-server: $schema=https://cmakefmt.dev/schemas/latest/schema.json\n",
440            "# Default cmakefmt configuration.\n",
441            "# Copy this to .cmakefmt.yaml and uncomment the optional settings\n",
442            "# you want to customize.\n\n",
443            "format:\n",
444            "  # Disable formatting entirely (return source unchanged).\n",
445            "  # disable: true\n\n",
446            "  # Output line-ending style: unix (LF), windows (CRLF), or auto (detect from input).\n",
447            "  # line_ending: windows\n\n",
448            "  # Maximum rendered line width before cmakefmt wraps a call.\n",
449            "  line_width: {line_width}\n\n",
450            "  # Number of spaces per indentation level when use_tabs is false.\n",
451            "  tab_size: {tab_size}\n\n",
452            "  # Indent with tab characters instead of spaces.\n",
453            "  # use_tabs: true\n\n",
454            "  # How to handle fractional indentation when use_tabs is true: use-space or round-up.\n",
455            "  # fractional_tab_policy: round-up\n\n",
456            "  # Maximum number of consecutive blank lines to preserve.\n",
457            "  max_empty_lines: {max_empty_lines}\n\n",
458            "  # Maximum wrapped lines to tolerate before switching to a more vertical layout.\n",
459            "  max_hanging_wrap_lines: {max_lines_hwrap}\n\n",
460            "  # Maximum positional arguments to keep in a hanging-wrap layout.\n",
461            "  max_hanging_wrap_positional_args: {max_pargs_hwrap}\n\n",
462            "  # Maximum keyword/flag subgroups to keep in a hanging-wrap layout.\n",
463            "  max_hanging_wrap_groups: {max_subgroups_hwrap}\n\n",
464            "  # Maximum rows a hanging-wrap positional group may consume before nesting is forced.\n",
465            "  max_rows_cmdline: {max_rows_cmdline}\n\n",
466            "  # Commands that must always use vertical (wrapped) layout.\n",
467            "  # always_wrap:\n",
468            "  #   - target_link_libraries\n\n",
469            "  # Return an error if any formatted line exceeds line_width.\n",
470            "  # require_valid_layout: true\n\n",
471            "  # Put the closing ')' on its own line when a call wraps.\n",
472            "  dangle_parens: {dangle_parens}\n\n",
473            "  # Alignment strategy for a dangling ')': prefix, open, or close.\n",
474            "  dangle_align: {dangle_align}\n\n",
475            "  # Lower heuristic bound used when deciding between compact and wrapped layouts.\n",
476            "  min_prefix_length: {min_prefix_chars}\n\n",
477            "  # Upper heuristic bound used when deciding between compact and wrapped layouts.\n",
478            "  max_prefix_length: {max_prefix_chars}\n\n",
479            "  # Insert a space before '(' for control-flow commands like if/foreach.\n",
480            "  # space_before_control_paren: true\n\n",
481            "  # Insert a space before '(' for function() and macro() definitions.\n",
482            "  # space_before_definition_paren: true\n\n",
483            "  # Output casing for command names: lower, upper, or unchanged.\n",
484            "  command_case: {command_case}\n\n",
485            "  # Output casing for recognized keywords and flags: lower, upper, or unchanged.\n",
486            "  keyword_case: {keyword_case}\n\n",
487            "markup:\n",
488            "  # Enable markup-aware comment handling.\n",
489            "  enable_markup: {enable_markup}\n\n",
490            "  # Reflow plain line comments to fit within the configured line width.\n",
491            "  # reflow_comments: true\n\n",
492            "  # Preserve the first comment block in a file literally.\n",
493            "  first_comment_is_literal: {first_comment_is_literal}\n\n",
494            "  # Preserve comments matching a custom regex literally.\n",
495            "  # literal_comment_pattern: '^\\s*NOTE:'\n\n",
496            "  # Preferred bullet character when normalizing markup lists.\n",
497            "  bullet_char: '{bullet_char}'\n\n",
498            "  # Preferred punctuation for numbered lists when normalizing markup.\n",
499            "  enum_char: '{enum_char}'\n\n",
500            "  # Regex describing fenced literal comment blocks.\n",
501            "  fence_pattern: '{fence_pattern}'\n\n",
502            "  # Regex describing ruler-style comments that should be treated specially.\n",
503            "  ruler_pattern: '{ruler_pattern}'\n\n",
504            "  # Minimum ruler length before a hash-only line is treated as a ruler.\n",
505            "  hashruler_min_length: {hashruler_min_length}\n\n",
506            "  # Normalize ruler comments when markup handling is enabled.\n",
507            "  canonicalize_hashrulers: {canonicalize_hashrulers}\n\n",
508            "  # Regex pattern for inline comments that are explicitly trailing their preceding\n",
509            "  # argument (rendered on the same line). Default: '#<'.\n",
510            "  # explicit_trailing_pattern: '#<'\n\n",
511            "# Uncomment and edit a block like this to override formatting knobs\n",
512            "# for a specific command. This changes layout behavior for that\n",
513            "# command name only; it does not define new command syntax.\n",
514            "#\n",
515            "# per_command_overrides:\n",
516            "#   my_custom_command:\n",
517            "#     # Override the line width just for this command.\n",
518            "#     line_width: 120\n",
519            "#\n",
520            "#     # Override command casing just for this command.\n",
521            "#     command_case: unchanged\n",
522            "#\n",
523            "#     # Override keyword casing just for this command.\n",
524            "#     keyword_case: upper\n",
525            "#\n",
526            "#     # Override indentation width just for this command.\n",
527            "#     tab_size: 4\n",
528            "#\n",
529            "#     # Override dangling-paren placement just for this command.\n",
530            "#     dangle_parens: false\n",
531            "#\n",
532            "#     # Override dangling-paren alignment just for this command.\n",
533            "#     dangle_align: prefix\n",
534            "#\n",
535            "#     # Override the positional-argument hanging-wrap threshold just for this command.\n",
536            "#     max_hanging_wrap_positional_args: 8\n",
537            "#\n",
538            "#     # Override the subgroup hanging-wrap threshold just for this command.\n",
539            "#     max_hanging_wrap_groups: 3\n\n",
540            "# YAML custom-command specs live under commands:<name>. Command\n",
541            "# specs tell the formatter which tokens are positional arguments,\n",
542            "# standalone flags, and keyword sections.\n",
543            "#\n",
544            "# Example: one positional argument, one flag, and two keyword\n",
545            "# sections that each take one or more values.\n",
546            "#\n",
547            "# commands:\n",
548            "#   my_custom_command:\n",
549            "#     pargs: 1\n",
550            "#     flags:\n",
551            "#       - QUIET\n",
552            "#     kwargs:\n",
553            "#       SOURCES:\n",
554            "#         nargs: \"+\"\n",
555            "#       LIBRARIES:\n",
556            "#         nargs: \"+\"\n",
557        ),
558        line_width = Config::default().line_width,
559        tab_size = Config::default().tab_size,
560        max_empty_lines = Config::default().max_empty_lines,
561        max_lines_hwrap = Config::default().max_lines_hwrap,
562        max_pargs_hwrap = Config::default().max_pargs_hwrap,
563        max_subgroups_hwrap = Config::default().max_subgroups_hwrap,
564        max_rows_cmdline = Config::default().max_rows_cmdline,
565        dangle_parens = Config::default().dangle_parens,
566        dangle_align = "prefix",
567        min_prefix_chars = Config::default().min_prefix_chars,
568        max_prefix_chars = Config::default().max_prefix_chars,
569        command_case = "lower",
570        keyword_case = "upper",
571        enable_markup = Config::default().enable_markup,
572        first_comment_is_literal = Config::default().first_comment_is_literal,
573        bullet_char = Config::default().bullet_char,
574        enum_char = Config::default().enum_char,
575        fence_pattern = Config::default().fence_pattern,
576        ruler_pattern = Config::default().ruler_pattern,
577        hashruler_min_length = Config::default().hashruler_min_length,
578        canonicalize_hashrulers = Config::default().canonicalize_hashrulers,
579    )
580}
581
582impl Config {
583    /// Load configuration for a file at the given path.
584    ///
585    /// Searches for the nearest supported user config (`.cmakefmt.yaml`,
586    /// `.cmakefmt.yml`, then `.cmakefmt.toml`) starting from the file's
587    /// directory and walking up to the repository/filesystem root. If none is
588    /// found, falls back to the same filenames in the home directory.
589    pub fn for_file(file_path: &Path) -> Result<Self> {
590        let config_paths = find_config_files(file_path);
591        Self::from_files(&config_paths)
592    }
593
594    /// Load configuration from a specific supported config file.
595    pub fn from_file(path: &Path) -> Result<Self> {
596        let paths = [path.to_path_buf()];
597        Self::from_files(&paths)
598    }
599
600    /// Load configuration by merging several supported config files in order.
601    ///
602    /// Later files override earlier files.
603    pub fn from_files(paths: &[PathBuf]) -> Result<Self> {
604        let mut config = Config::default();
605        for path in paths {
606            let file_config = load_config_file(path)?;
607            config.apply(file_config);
608        }
609        config.validate_patterns().map_err(Error::Formatter)?;
610        Ok(config)
611    }
612
613    /// Parse a YAML config string through the same `FileConfig` schema used by
614    /// config files. Returns the resolved config and the extracted `commands:`
615    /// section (if present) for separate registry merging.
616    ///
617    /// This validates sections (`format:`, `markup:`) and rejects
618    /// unknown fields, matching the behavior of file-based config loading.
619    pub fn from_yaml_str(yaml: &str) -> Result<(Self, Option<serde_yaml::Value>)> {
620        let file_config: FileConfig =
621            serde_yaml::from_str(yaml).map_err(|source| Error::Config {
622                path: std::path::PathBuf::from("<yaml-string>"),
623                details: FileParseError {
624                    format: "yaml",
625                    message: source.to_string().into_boxed_str(),
626                    line: source.location().map(|loc| loc.line()),
627                    column: source.location().map(|loc| loc.column()),
628                },
629                source_message: source.to_string().into_boxed_str(),
630            })?;
631        if !file_config.legacy_per_command.is_empty() {
632            return Err(Error::Config {
633                path: std::path::PathBuf::from("<yaml-string>"),
634                details: FileParseError {
635                    format: "yaml",
636                    message: "`per_command` has been renamed to `per_command_overrides`"
637                        .to_owned()
638                        .into_boxed_str(),
639                    line: None,
640                    column: None,
641                },
642                source_message: "`per_command` has been renamed to `per_command_overrides`"
643                    .to_owned()
644                    .into_boxed_str(),
645            });
646        }
647        let commands = file_config.commands.clone();
648        let mut config = Config::default();
649        config.apply(file_config);
650        config.validate_patterns().map_err(|msg| Error::Config {
651            path: std::path::PathBuf::from("<yaml-string>"),
652            details: FileParseError {
653                format: "yaml",
654                message: msg.clone().into_boxed_str(),
655                line: None,
656                column: None,
657            },
658            source_message: msg.into_boxed_str(),
659        })?;
660        Ok((config, commands))
661    }
662
663    /// Return the config files that would be applied for the given file.
664    ///
665    /// When config discovery is used, this is either the nearest
666    /// supported config file found by walking upward from the file, or a home
667    /// directory config if no nearer config exists.
668    pub fn config_sources_for(file_path: &Path) -> Vec<PathBuf> {
669        find_config_files(file_path)
670    }
671
672    fn apply(&mut self, fc: FileConfig) {
673        // Format section
674        if let Some(v) = fc.format.disable {
675            self.disable = v;
676        }
677        if let Some(v) = fc.format.line_ending {
678            self.line_ending = v;
679        }
680        if let Some(v) = fc.format.line_width {
681            self.line_width = v;
682        }
683        if let Some(v) = fc.format.tab_size {
684            self.tab_size = v;
685        }
686        if let Some(v) = fc.format.use_tabs {
687            self.use_tabchars = v;
688        }
689        if let Some(v) = fc.format.fractional_tab_policy {
690            self.fractional_tab_policy = v;
691        }
692        if let Some(v) = fc.format.max_empty_lines {
693            self.max_empty_lines = v;
694        }
695        if let Some(v) = fc.format.max_hanging_wrap_lines {
696            self.max_lines_hwrap = v;
697        }
698        if let Some(v) = fc.format.max_hanging_wrap_positional_args {
699            self.max_pargs_hwrap = v;
700        }
701        if let Some(v) = fc.format.max_hanging_wrap_groups {
702            self.max_subgroups_hwrap = v;
703        }
704        if let Some(v) = fc.format.max_rows_cmdline {
705            self.max_rows_cmdline = v;
706        }
707        if let Some(v) = fc.format.always_wrap {
708            self.always_wrap = v.into_iter().map(|s| s.to_ascii_lowercase()).collect();
709        }
710        if let Some(v) = fc.format.require_valid_layout {
711            self.require_valid_layout = v;
712        }
713        if let Some(v) = fc.format.dangle_parens {
714            self.dangle_parens = v;
715        }
716        if let Some(v) = fc.format.dangle_align {
717            self.dangle_align = v;
718        }
719        if let Some(v) = fc.format.min_prefix_length {
720            self.min_prefix_chars = v;
721        }
722        if let Some(v) = fc.format.max_prefix_length {
723            self.max_prefix_chars = v;
724        }
725        if let Some(v) = fc.format.space_before_control_paren {
726            self.separate_ctrl_name_with_space = v;
727        }
728        if let Some(v) = fc.format.space_before_definition_paren {
729            self.separate_fn_name_with_space = v;
730        }
731        if let Some(v) = fc.format.command_case {
732            self.command_case = v;
733        }
734        if let Some(v) = fc.format.keyword_case {
735            self.keyword_case = v;
736        }
737
738        // Markup section
739        if let Some(v) = fc.markup.enable_markup {
740            self.enable_markup = v;
741        }
742        if let Some(v) = fc.markup.reflow_comments {
743            self.reflow_comments = v;
744        }
745        if let Some(v) = fc.markup.first_comment_is_literal {
746            self.first_comment_is_literal = v;
747        }
748        if let Some(v) = fc.markup.literal_comment_pattern {
749            self.literal_comment_pattern = v;
750        }
751        if let Some(v) = fc.markup.bullet_char {
752            self.bullet_char = v;
753        }
754        if let Some(v) = fc.markup.enum_char {
755            self.enum_char = v;
756        }
757        if let Some(v) = fc.markup.fence_pattern {
758            self.fence_pattern = v;
759        }
760        if let Some(v) = fc.markup.ruler_pattern {
761            self.ruler_pattern = v;
762        }
763        if let Some(v) = fc.markup.hashruler_min_length {
764            self.hashruler_min_length = v;
765        }
766        if let Some(v) = fc.markup.canonicalize_hashrulers {
767            self.canonicalize_hashrulers = v;
768        }
769        if let Some(v) = fc.markup.explicit_trailing_pattern {
770            self.explicit_trailing_pattern = v;
771        }
772
773        // Per-command overrides (merge, don't replace)
774        for (name, overrides) in fc.per_command_overrides {
775            self.per_command_overrides.insert(name, overrides);
776        }
777    }
778}
779
780fn load_config_file(path: &Path) -> Result<FileConfig> {
781    let contents = std::fs::read_to_string(path).map_err(Error::Io)?;
782    let config: FileConfig = match detect_config_format(path)? {
783        ConfigFileFormat::Toml => toml::from_str(&contents).map_err(|source| {
784            let (line, column) = toml_line_col(&contents, source.span().map(|span| span.start));
785            Error::Config {
786                path: path.to_path_buf(),
787                details: FileParseError {
788                    format: ConfigFileFormat::Toml.as_str(),
789                    message: source.to_string().into_boxed_str(),
790                    line,
791                    column,
792                },
793                source_message: source.to_string().into_boxed_str(),
794            }
795        }),
796        ConfigFileFormat::Yaml => serde_yaml::from_str(&contents).map_err(|source| {
797            let location = source.location();
798            let line = location.as_ref().map(|loc| loc.line());
799            let column = location.as_ref().map(|loc| loc.column());
800            Error::Config {
801                path: path.to_path_buf(),
802                details: FileParseError {
803                    format: ConfigFileFormat::Yaml.as_str(),
804                    message: source.to_string().into_boxed_str(),
805                    line,
806                    column,
807                },
808                source_message: source.to_string().into_boxed_str(),
809            }
810        }),
811    }?;
812
813    if !config.legacy_per_command.is_empty() {
814        return Err(Error::Formatter(format!(
815            "{}: `per_command` has been renamed to `per_command_overrides`",
816            path.display()
817        )));
818    }
819
820    Ok(config)
821}
822
823/// Find the config files that apply to `file_path`.
824///
825/// The nearest supported config discovered while walking upward wins. If
826/// multiple supported config filenames exist in the same directory, YAML is
827/// preferred over TOML. If no project-local config is found, the user home
828/// config is returned when present.
829fn find_config_files(file_path: &Path) -> Vec<PathBuf> {
830    let start_dir = if file_path.is_dir() {
831        file_path.to_path_buf()
832    } else {
833        file_path
834            .parent()
835            .map(Path::to_path_buf)
836            .unwrap_or_else(|| PathBuf::from("."))
837    };
838
839    let mut dir = Some(start_dir.as_path());
840    while let Some(d) = dir {
841        if let Some(candidate) = preferred_config_in_dir(d) {
842            return vec![candidate];
843        }
844
845        if d.join(".git").exists() {
846            break;
847        }
848
849        dir = d.parent();
850    }
851
852    if let Some(home) = home_dir() {
853        if let Some(home_config) = preferred_config_in_dir(&home) {
854            return vec![home_config];
855        }
856    }
857
858    Vec::new()
859}
860
861pub(crate) fn detect_config_format(path: &Path) -> Result<ConfigFileFormat> {
862    let file_name = path
863        .file_name()
864        .and_then(|name| name.to_str())
865        .unwrap_or_default();
866    if file_name == CONFIG_FILE_NAME_TOML
867        || path.extension().and_then(|ext| ext.to_str()) == Some("toml")
868    {
869        return Ok(ConfigFileFormat::Toml);
870    }
871    if matches!(file_name, CONFIG_FILE_NAME_YAML | CONFIG_FILE_NAME_YML)
872        || matches!(
873            path.extension().and_then(|ext| ext.to_str()),
874            Some("yaml" | "yml")
875        )
876    {
877        return Ok(ConfigFileFormat::Yaml);
878    }
879
880    Err(Error::Formatter(format!(
881        "{}: unsupported config format; use .cmakefmt.yaml, .cmakefmt.yml, or .cmakefmt.toml",
882        path.display()
883    )))
884}
885
886fn preferred_config_in_dir(dir: &Path) -> Option<PathBuf> {
887    CONFIG_FILE_NAMES
888        .iter()
889        .map(|name| dir.join(name))
890        .find(|candidate| candidate.is_file())
891}
892
893pub(crate) fn toml_line_col(
894    contents: &str,
895    offset: Option<usize>,
896) -> (Option<usize>, Option<usize>) {
897    let Some(offset) = offset else {
898        return (None, None);
899    };
900    let mut line = 1usize;
901    let mut column = 1usize;
902    for (index, ch) in contents.char_indices() {
903        if index >= offset {
904            break;
905        }
906        if ch == '\n' {
907            line += 1;
908            column = 1;
909        } else {
910            column += 1;
911        }
912    }
913    (Some(line), Some(column))
914}
915
916fn home_dir() -> Option<PathBuf> {
917    std::env::var_os("HOME")
918        .or_else(|| std::env::var_os("USERPROFILE"))
919        .map(PathBuf::from)
920}
921
922#[cfg(test)]
923mod tests {
924    use super::*;
925    use std::fs;
926
927    #[test]
928    fn parse_empty_config() {
929        let config: FileConfig = toml::from_str("").unwrap();
930        assert!(config.format.line_width.is_none());
931    }
932
933    #[test]
934    fn parse_full_config() {
935        let toml_str = r#"
936[format]
937line_width = 120
938tab_size = 4
939use_tabs = true
940max_empty_lines = 2
941dangle_parens = true
942dangle_align = "open"
943space_before_control_paren = true
944space_before_definition_paren = true
945max_hanging_wrap_positional_args = 3
946max_hanging_wrap_groups = 1
947command_case = "upper"
948keyword_case = "lower"
949
950[markup]
951enable_markup = false
952hashruler_min_length = 20
953
954[per_command_overrides.message]
955dangle_parens = true
956line_width = 100
957"#;
958        let config: FileConfig = toml::from_str(toml_str).unwrap();
959        assert_eq!(config.format.line_width, Some(120));
960        assert_eq!(config.format.tab_size, Some(4));
961        assert_eq!(config.format.use_tabs, Some(true));
962        assert_eq!(config.format.dangle_parens, Some(true));
963        assert_eq!(config.format.dangle_align, Some(DangleAlign::Open));
964        assert_eq!(config.format.command_case, Some(CaseStyle::Upper));
965        assert_eq!(config.format.keyword_case, Some(CaseStyle::Lower));
966        assert_eq!(config.markup.enable_markup, Some(false));
967
968        let msg = config.per_command_overrides.get("message").unwrap();
969        assert_eq!(msg.dangle_parens, Some(true));
970        assert_eq!(msg.line_width, Some(100));
971    }
972
973    #[test]
974    fn old_format_key_aliases_are_rejected() {
975        let toml_str = r#"
976[format]
977use_tabchars = true
978max_lines_hwrap = 4
979max_pargs_hwrap = 3
980max_subgroups_hwrap = 2
981min_prefix_chars = 5
982max_prefix_chars = 11
983separate_ctrl_name_with_space = true
984separate_fn_name_with_space = true
985"#;
986        let err = toml::from_str::<FileConfig>(toml_str)
987            .unwrap_err()
988            .to_string();
989        assert!(err.contains("unknown field"));
990    }
991
992    #[test]
993    fn config_from_file_applies_overrides() {
994        let dir = tempfile::tempdir().unwrap();
995        let config_path = dir.path().join(CONFIG_FILE_NAME_TOML);
996        fs::write(
997            &config_path,
998            r#"
999[format]
1000line_width = 100
1001tab_size = 4
1002command_case = "upper"
1003"#,
1004        )
1005        .unwrap();
1006
1007        let config = Config::from_file(&config_path).unwrap();
1008        assert_eq!(config.line_width, 100);
1009        assert_eq!(config.tab_size, 4);
1010        assert_eq!(config.command_case, CaseStyle::Upper);
1011        // Unspecified values keep defaults
1012        assert!(!config.use_tabchars);
1013        assert_eq!(config.max_empty_lines, 1);
1014    }
1015
1016    #[test]
1017    fn default_yaml_config_template_parses() {
1018        let template = default_config_template();
1019        let parsed: FileConfig = serde_yaml::from_str(&template).unwrap();
1020        assert_eq!(parsed.format.line_width, Some(Config::default().line_width));
1021        assert_eq!(
1022            parsed.format.command_case,
1023            Some(Config::default().command_case)
1024        );
1025        assert_eq!(
1026            parsed.markup.enable_markup,
1027            Some(Config::default().enable_markup)
1028        );
1029    }
1030
1031    #[test]
1032    fn toml_config_template_parses() {
1033        let template = default_config_template_for(DumpConfigFormat::Toml);
1034        let parsed: FileConfig = toml::from_str(&template).unwrap();
1035        assert_eq!(parsed.format.line_width, Some(Config::default().line_width));
1036        assert_eq!(
1037            parsed.format.command_case,
1038            Some(Config::default().command_case)
1039        );
1040        assert_eq!(
1041            parsed.markup.enable_markup,
1042            Some(Config::default().enable_markup)
1043        );
1044    }
1045
1046    #[test]
1047    fn missing_config_file_uses_defaults() {
1048        let dir = tempfile::tempdir().unwrap();
1049        let fake_file = dir.path().join("CMakeLists.txt");
1050        fs::write(&fake_file, "").unwrap();
1051
1052        let config = Config::for_file(&fake_file).unwrap();
1053        assert_eq!(config, Config::default());
1054    }
1055
1056    #[test]
1057    fn config_file_in_parent_is_found() {
1058        let dir = tempfile::tempdir().unwrap();
1059        // Create a .git dir to act as root
1060        fs::create_dir(dir.path().join(".git")).unwrap();
1061        fs::write(
1062            dir.path().join(CONFIG_FILE_NAME_TOML),
1063            "[format]\nline_width = 120\n",
1064        )
1065        .unwrap();
1066
1067        let subdir = dir.path().join("src");
1068        fs::create_dir(&subdir).unwrap();
1069        let file = subdir.join("CMakeLists.txt");
1070        fs::write(&file, "").unwrap();
1071
1072        let config = Config::for_file(&file).unwrap();
1073        assert_eq!(config.line_width, 120);
1074    }
1075
1076    #[test]
1077    fn closer_config_wins() {
1078        let dir = tempfile::tempdir().unwrap();
1079        fs::create_dir(dir.path().join(".git")).unwrap();
1080        fs::write(
1081            dir.path().join(CONFIG_FILE_NAME_TOML),
1082            "[format]\nline_width = 120\ntab_size = 4\n",
1083        )
1084        .unwrap();
1085
1086        let subdir = dir.path().join("src");
1087        fs::create_dir(&subdir).unwrap();
1088        fs::write(
1089            subdir.join(CONFIG_FILE_NAME_TOML),
1090            "[format]\nline_width = 100\n",
1091        )
1092        .unwrap();
1093
1094        let file = subdir.join("CMakeLists.txt");
1095        fs::write(&file, "").unwrap();
1096
1097        let config = Config::for_file(&file).unwrap();
1098        // Only the nearest config is used automatically.
1099        assert_eq!(config.line_width, 100);
1100        assert_eq!(config.tab_size, Config::default().tab_size);
1101    }
1102
1103    #[test]
1104    fn from_files_merges_in_order() {
1105        let dir = tempfile::tempdir().unwrap();
1106        let first = dir.path().join("first.toml");
1107        let second = dir.path().join("second.toml");
1108        fs::write(&first, "[format]\nline_width = 120\ntab_size = 4\n").unwrap();
1109        fs::write(&second, "[format]\nline_width = 100\n").unwrap();
1110
1111        let config = Config::from_files(&[first, second]).unwrap();
1112        assert_eq!(config.line_width, 100);
1113        assert_eq!(config.tab_size, 4);
1114    }
1115
1116    #[test]
1117    fn yaml_config_from_file_applies_overrides() {
1118        let dir = tempfile::tempdir().unwrap();
1119        let config_path = dir.path().join(CONFIG_FILE_NAME_YAML);
1120        fs::write(
1121            &config_path,
1122            "format:\n  line_width: 100\n  tab_size: 4\n  command_case: upper\n",
1123        )
1124        .unwrap();
1125
1126        let config = Config::from_file(&config_path).unwrap();
1127        assert_eq!(config.line_width, 100);
1128        assert_eq!(config.tab_size, 4);
1129        assert_eq!(config.command_case, CaseStyle::Upper);
1130    }
1131
1132    #[test]
1133    fn yml_config_from_file_applies_overrides() {
1134        let dir = tempfile::tempdir().unwrap();
1135        let config_path = dir.path().join(CONFIG_FILE_NAME_YML);
1136        fs::write(
1137            &config_path,
1138            "format:\n  keyword_case: lower\n  line_width: 90\n",
1139        )
1140        .unwrap();
1141
1142        let config = Config::from_file(&config_path).unwrap();
1143        assert_eq!(config.line_width, 90);
1144        assert_eq!(config.keyword_case, CaseStyle::Lower);
1145    }
1146
1147    #[test]
1148    fn yaml_is_preferred_over_toml_during_discovery() {
1149        let dir = tempfile::tempdir().unwrap();
1150        fs::create_dir(dir.path().join(".git")).unwrap();
1151        fs::write(
1152            dir.path().join(CONFIG_FILE_NAME_TOML),
1153            "[format]\nline_width = 120\n",
1154        )
1155        .unwrap();
1156        fs::write(
1157            dir.path().join(CONFIG_FILE_NAME_YAML),
1158            "format:\n  line_width: 90\n",
1159        )
1160        .unwrap();
1161
1162        let file = dir.path().join("CMakeLists.txt");
1163        fs::write(&file, "").unwrap();
1164
1165        let config = Config::for_file(&file).unwrap();
1166        assert_eq!(config.line_width, 90);
1167        assert_eq!(
1168            Config::config_sources_for(&file),
1169            vec![dir.path().join(CONFIG_FILE_NAME_YAML)]
1170        );
1171    }
1172
1173    #[test]
1174    fn invalid_config_returns_error() {
1175        let dir = tempfile::tempdir().unwrap();
1176        let path = dir.path().join(CONFIG_FILE_NAME_TOML);
1177        fs::write(&path, "this is not valid toml {{{").unwrap();
1178
1179        let result = Config::from_file(&path);
1180        assert!(result.is_err());
1181        let err = result.unwrap_err();
1182        assert!(err.to_string().contains("config error"));
1183    }
1184
1185    #[test]
1186    fn config_from_yaml_file_applies_all_sections_and_overrides() {
1187        let dir = tempfile::tempdir().unwrap();
1188        let config_path = dir.path().join(CONFIG_FILE_NAME_YAML);
1189        fs::write(
1190            &config_path,
1191            r#"
1192format:
1193  line_width: 96
1194  tab_size: 3
1195  use_tabs: true
1196  max_empty_lines: 2
1197  max_hanging_wrap_lines: 4
1198  max_hanging_wrap_positional_args: 7
1199  max_hanging_wrap_groups: 5
1200  dangle_parens: true
1201  dangle_align: open
1202  min_prefix_length: 2
1203  max_prefix_length: 12
1204  space_before_control_paren: true
1205  space_before_definition_paren: true
1206  command_case: unchanged
1207  keyword_case: lower
1208markup:
1209  enable_markup: false
1210  reflow_comments: true
1211  first_comment_is_literal: false
1212  literal_comment_pattern: '^\\s*KEEP'
1213  bullet_char: '-'
1214  enum_char: ')'
1215  fence_pattern: '^\\s*(```+).*'
1216  ruler_pattern: '^\\s*={5,}\\s*$'
1217  hashruler_min_length: 42
1218  canonicalize_hashrulers: false
1219per_command_overrides:
1220  my_custom_command:
1221    line_width: 101
1222    tab_size: 5
1223    dangle_parens: false
1224    dangle_align: prefix
1225    max_hanging_wrap_positional_args: 8
1226    max_hanging_wrap_groups: 9
1227"#,
1228        )
1229        .unwrap();
1230
1231        let config = Config::from_file(&config_path).unwrap();
1232        assert_eq!(config.line_width, 96);
1233        assert_eq!(config.tab_size, 3);
1234        assert!(config.use_tabchars);
1235        assert_eq!(config.max_empty_lines, 2);
1236        assert_eq!(config.max_lines_hwrap, 4);
1237        assert_eq!(config.max_pargs_hwrap, 7);
1238        assert_eq!(config.max_subgroups_hwrap, 5);
1239        assert!(config.dangle_parens);
1240        assert_eq!(config.dangle_align, DangleAlign::Open);
1241        assert_eq!(config.min_prefix_chars, 2);
1242        assert_eq!(config.max_prefix_chars, 12);
1243        assert!(config.separate_ctrl_name_with_space);
1244        assert!(config.separate_fn_name_with_space);
1245        assert_eq!(config.command_case, CaseStyle::Unchanged);
1246        assert_eq!(config.keyword_case, CaseStyle::Lower);
1247        assert!(!config.enable_markup);
1248        assert!(config.reflow_comments);
1249        assert!(!config.first_comment_is_literal);
1250        assert_eq!(config.literal_comment_pattern, "^\\\\s*KEEP");
1251        assert_eq!(config.bullet_char, "-");
1252        assert_eq!(config.enum_char, ")");
1253        assert_eq!(config.fence_pattern, "^\\\\s*(```+).*");
1254        assert_eq!(config.ruler_pattern, "^\\\\s*={5,}\\\\s*$");
1255        assert_eq!(config.hashruler_min_length, 42);
1256        assert!(!config.canonicalize_hashrulers);
1257        let per_command = config
1258            .per_command_overrides
1259            .get("my_custom_command")
1260            .unwrap();
1261        assert_eq!(per_command.line_width, Some(101));
1262        assert_eq!(per_command.tab_size, Some(5));
1263        assert_eq!(per_command.dangle_parens, Some(false));
1264        assert_eq!(per_command.dangle_align, Some(DangleAlign::Prefix));
1265        assert_eq!(per_command.max_pargs_hwrap, Some(8));
1266        assert_eq!(per_command.max_subgroups_hwrap, Some(9));
1267    }
1268
1269    #[test]
1270    fn detect_config_format_supports_yaml_and_rejects_unknown() {
1271        assert!(matches!(
1272            detect_config_format(Path::new(".cmakefmt.yml")).unwrap(),
1273            ConfigFileFormat::Yaml
1274        ));
1275        assert!(matches!(
1276            detect_config_format(Path::new("tooling/settings.yaml")).unwrap(),
1277            ConfigFileFormat::Yaml
1278        ));
1279        assert!(matches!(
1280            detect_config_format(Path::new("project.toml")).unwrap(),
1281            ConfigFileFormat::Toml
1282        ));
1283        let err = detect_config_format(Path::new("config.json")).unwrap_err();
1284        assert!(err.to_string().contains("unsupported config format"));
1285    }
1286
1287    #[test]
1288    fn yaml_config_with_legacy_per_command_key_is_rejected() {
1289        let dir = tempfile::tempdir().unwrap();
1290        let config_path = dir.path().join(CONFIG_FILE_NAME_YAML);
1291        fs::write(
1292            &config_path,
1293            "per_command:\n  message:\n    line_width: 120\n",
1294        )
1295        .unwrap();
1296        let err = Config::from_file(&config_path).unwrap_err();
1297        assert!(err
1298            .to_string()
1299            .contains("`per_command` has been renamed to `per_command_overrides`"));
1300    }
1301
1302    #[test]
1303    fn invalid_yaml_reports_line_and_column() {
1304        let dir = tempfile::tempdir().unwrap();
1305        let config_path = dir.path().join(CONFIG_FILE_NAME_YAML);
1306        fs::write(&config_path, "format:\n  line_width: [\n").unwrap();
1307
1308        let err = Config::from_file(&config_path).unwrap_err();
1309        match err {
1310            Error::Config { details, .. } => {
1311                assert_eq!(details.format, "YAML");
1312                assert!(details.line.is_some());
1313                assert!(details.column.is_some());
1314            }
1315            other => panic!("expected config parse error, got {other:?}"),
1316        }
1317    }
1318
1319    #[test]
1320    fn toml_line_col_returns_none_when_offset_is_missing() {
1321        assert_eq!(toml_line_col("line = true\n", None), (None, None));
1322    }
1323
1324    // ── from_yaml_str tests ─────────────────────────────────────────────
1325
1326    #[test]
1327    fn from_yaml_str_parses_format_section() {
1328        let (config, commands) =
1329            Config::from_yaml_str("format:\n  line_width: 120\n  tab_size: 4").unwrap();
1330        assert_eq!(config.line_width, 120);
1331        assert_eq!(config.tab_size, 4);
1332        assert!(commands.is_none());
1333    }
1334
1335    #[test]
1336    fn from_yaml_str_parses_casing_in_format_section() {
1337        let (config, _) = Config::from_yaml_str("format:\n  command_case: upper").unwrap();
1338        assert_eq!(config.command_case, CaseStyle::Upper);
1339    }
1340
1341    #[test]
1342    fn from_yaml_str_parses_markup_section() {
1343        let (config, _) = Config::from_yaml_str("markup:\n  enable_markup: false").unwrap();
1344        assert!(!config.enable_markup);
1345    }
1346
1347    #[test]
1348    fn from_yaml_str_extracts_commands() {
1349        let (_, commands) = Config::from_yaml_str("commands:\n  my_cmd:\n    pargs: 1").unwrap();
1350        assert!(commands.is_some());
1351    }
1352
1353    #[test]
1354    fn from_yaml_str_rejects_unknown_top_level_field() {
1355        let result = Config::from_yaml_str("bogus_section:\n  foo: bar");
1356        assert!(result.is_err());
1357    }
1358
1359    #[test]
1360    fn from_yaml_str_rejects_unknown_format_field() {
1361        let result = Config::from_yaml_str("format:\n  nonexistent: 42");
1362        assert!(result.is_err());
1363    }
1364
1365    #[test]
1366    fn from_yaml_str_rejects_invalid_yaml() {
1367        let result = Config::from_yaml_str("{{invalid");
1368        assert!(result.is_err());
1369    }
1370
1371    #[test]
1372    fn from_yaml_str_empty_string_returns_defaults() {
1373        let (config, commands) = Config::from_yaml_str("").unwrap();
1374        assert_eq!(config.line_width, Config::default().line_width);
1375        assert!(commands.is_none());
1376    }
1377
1378    #[test]
1379    fn from_yaml_str_multiple_sections() {
1380        let (config, _) =
1381            Config::from_yaml_str("format:\n  line_width: 100\n  command_case: upper").unwrap();
1382        assert_eq!(config.line_width, 100);
1383        assert_eq!(config.command_case, CaseStyle::Upper);
1384    }
1385
1386    #[test]
1387    fn from_yaml_str_rejects_legacy_per_command() {
1388        let result = Config::from_yaml_str("per_command:\n  message:\n    line_width: 120");
1389        assert!(result.is_err());
1390        let err = result.unwrap_err().to_string();
1391        assert!(
1392            err.contains("per_command_overrides"),
1393            "error should mention the new key name: {err}"
1394        );
1395    }
1396}