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