1use std::cell::Cell;
2use std::fs::File;
3use std::io::{Error, ErrorKind, Read};
4use std::path::{Path, PathBuf};
5use std::{env, fs};
6
7use thiserror::Error;
8
9use crate::config::config_type::ConfigType;
10#[allow(unreachable_pub)]
11pub use crate::config::file_lines::{FileLines, FileName, Range};
12#[allow(unreachable_pub)]
13pub use crate::config::macro_names::MacroSelector;
14#[allow(unreachable_pub)]
15pub use crate::config::options::*;
16
17#[macro_use]
18pub(crate) mod config_type;
19#[macro_use]
20#[allow(unreachable_pub)]
21pub(crate) mod options;
22
23pub(crate) mod file_lines;
24#[allow(unreachable_pub)]
25pub(crate) mod lists;
26pub(crate) mod macro_names;
27pub(crate) mod style_edition;
28
29create_config! {
34 max_width: MaxWidth, true, "Maximum width of each line";
36 hard_tabs: HardTabs, true, "Use tab characters for indentation, spaces for alignment";
37 tab_spaces: TabSpaces, true, "Number of spaces per tab";
38 newline_style: NewlineStyleConfig, true, "Unix or Windows line endings";
39 indent_style: IndentStyleConfig, false, "How do we indent expressions or items";
40
41 use_small_heuristics: UseSmallHeuristics, true, "Whether to use different \
43 formatting for items and expressions if they satisfy a heuristic notion of 'small'";
44 width_heuristics: WidthHeuristicsConfig, false, "'small' heuristic values";
45 fn_call_width: FnCallWidth, true, "Maximum width of the args of a function call before \
46 falling back to vertical formatting.";
47 attr_fn_like_width: AttrFnLikeWidth, true, "Maximum width of the args of a function-like \
48 attributes before falling back to vertical formatting.";
49 struct_lit_width: StructLitWidth, true, "Maximum width in the body of a struct lit before \
50 falling back to vertical formatting.";
51 struct_variant_width: StructVariantWidth, true, "Maximum width in the body of a struct variant \
52 before falling back to vertical formatting.";
53 array_width: ArrayWidth, true, "Maximum width of an array literal before falling \
54 back to vertical formatting.";
55 chain_width: ChainWidth, true, "Maximum length of a chain to fit on a single line.";
56 single_line_if_else_max_width: SingleLineIfElseMaxWidth, true, "Maximum line length for single \
57 line if-else expressions. A value of zero means always break if-else expressions.";
58 single_line_let_else_max_width: SingleLineLetElseMaxWidth, true, "Maximum line length for \
59 single line let-else statements. A value of zero means always format the divergent `else` \
60 block over multiple lines.";
61
62 wrap_comments: WrapComments, false, "Break comments to fit on the line";
64 format_code_in_doc_comments: FormatCodeInDocComments, false, "Format the code snippet in \
65 doc comments.";
66 doc_comment_code_block_width: DocCommentCodeBlockWidth, false, "Maximum width for code \
67 snippets in doc comments. No effect unless format_code_in_doc_comments = true";
68 doc_comment_code_block_small_heuristics: DocUseSmallHeuristics, false,
69 "Value for use_small_heuristics for code blocks in doc comments. \
70 No effect unless format_code_in_doc_comments = true";
71 comment_width: CommentWidth, false,
72 "Maximum length of comments. No effect unless wrap_comments = true";
73 normalize_comments: NormalizeComments, false, "Convert /* */ comments to // comments where \
74 possible";
75 normalize_doc_attributes: NormalizeDocAttributes, false, "Normalize doc attributes as doc \
76 comments";
77 format_strings: FormatStrings, false, "Format string literals where necessary";
78 format_macro_matchers: FormatMacroMatchers, false,
79 "Format the metavariable matching patterns in macros";
80 format_macro_bodies: FormatMacroBodies, false,
81 "Format the bodies of declarative macro definitions";
82 skip_macro_invocations: SkipMacroInvocations, false,
83 "Skip formatting the bodies of macros invoked with the following names.";
84 hex_literal_case: HexLiteralCaseConfig, true, "Format hexadecimal integer literals";
85 float_literal_trailing_zero: FloatLiteralTrailingZeroConfig, false,
86 "Add or remove trailing zero in floating-point literals";
87
88 empty_item_single_line: EmptyItemSingleLine, false,
90 "Put empty-body functions and impls on a single line";
91 struct_lit_single_line: StructLitSingleLine, false,
92 "Put small struct literals on a single line";
93 fn_single_line: FnSingleLine, false, "Put single-expression functions on a single line";
94 where_single_line: WhereSingleLine, false, "Force where-clauses to be on a single line";
95
96 imports_indent: ImportsIndent, false, "Indent of imports";
98 imports_layout: ImportsLayout, false, "Item layout inside a import block";
99 imports_granularity: ImportsGranularityConfig, false,
100 "Merge or split imports to the provided granularity";
101 group_imports: GroupImportsTacticConfig, false,
102 "Controls the strategy for how imports are grouped together";
103 merge_imports: MergeImports, false, "(deprecated: use imports_granularity instead)";
104
105 reorder_imports: ReorderImports, true, "Reorder import and extern crate statements \
107 alphabetically";
108 reorder_modules: ReorderModules, true, "Reorder module statements alphabetically in group";
109 reorder_impl_items: ReorderImplItems, false, "Reorder impl items";
110
111 type_punctuation_density: TypePunctuationDensity, false,
113 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
114 space_before_colon: SpaceBeforeColon, false, "Leave a space before the colon";
115 space_after_colon: SpaceAfterColon, false, "Leave a space after the colon";
116 spaces_around_ranges: SpacesAroundRanges, false, "Put spaces around the .. and ..= range \
117 operators";
118 binop_separator: BinopSeparator, false,
119 "Where to put a binary operator when a binary expression goes multiline";
120
121 remove_nested_parens: RemoveNestedParens, true, "Remove nested parens";
123 combine_control_expr: CombineControlExpr, false, "Combine control expressions with function \
124 calls";
125 short_array_element_width_threshold: ShortArrayElementWidthThreshold, true,
126 "Width threshold for an array element to be considered short";
127 overflow_delimited_expr: OverflowDelimitedExpr, false,
128 "Allow trailing bracket/brace delimited expressions to overflow";
129 struct_field_align_threshold: StructFieldAlignThreshold, false,
130 "Align struct fields if their diffs fits within threshold";
131 enum_discrim_align_threshold: EnumDiscrimAlignThreshold, false,
132 "Align enum variants discrims, if their diffs fit within threshold";
133 match_arm_blocks: MatchArmBlocks, false, "Wrap the body of arms in blocks when it does not fit \
134 on the same line with the pattern of arms";
135 match_arm_leading_pipes: MatchArmLeadingPipeConfig, true,
136 "Determines whether leading pipes are emitted on match arms";
137 match_arm_indent: MatchArmIndent, false,
138 "Determines whether match arms are indented";
139 force_multiline_blocks: ForceMultilineBlocks, false,
140 "Force multiline closure bodies and match arms to be wrapped in a block";
141 fn_args_layout: FnArgsLayout, true,
142 "(deprecated: use fn_params_layout instead)";
143 fn_params_layout: FnParamsLayout, true,
144 "Control the layout of parameters in function signatures.";
145 brace_style: BraceStyleConfig, false, "Brace style for items";
146 control_brace_style: ControlBraceStyleConfig, false,
147 "Brace style for control flow constructs";
148 trailing_semicolon: TrailingSemicolon, false,
149 "Add trailing semicolon after break, continue and return";
150 trailing_comma: TrailingComma, false,
151 "How to handle trailing commas for lists";
152 match_block_trailing_comma: MatchBlockTrailingComma, true,
153 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
154 blank_lines_upper_bound: BlankLinesUpperBound, false,
155 "Maximum number of blank lines which can be put between items";
156 blank_lines_lower_bound: BlankLinesLowerBound, false,
157 "Minimum number of blank lines which must be put between items";
158 edition: EditionConfig, true, "The edition of the parser (RFC 2052)";
159 style_edition: StyleEditionConfig, true, "The edition of the Style Guide (RFC 3338)";
160 version: VersionConfig, false, "Version of formatting rules";
161 inline_attribute_width: InlineAttributeWidth, false,
162 "Write an item and its attribute on the same line \
163 if their combined width is below a threshold";
164 format_generated_files: FormatGeneratedFiles, false, "Format generated files";
165 generated_marker_line_search_limit: GeneratedMarkerLineSearchLimit, false, "Number of lines to \
166 check for a `@generated` marker when `format_generated_files` is enabled";
167
168 merge_derives: MergeDerives, true, "Merge multiple `#[derive(...)]` into a single one";
170 use_try_shorthand: UseTryShorthand, true, "Replace uses of the try! macro by the ? shorthand";
171 use_field_init_shorthand: UseFieldInitShorthand, true, "Use field initialization shorthand if \
172 possible";
173 force_explicit_abi: ForceExplicitAbi, true, "Always print the abi for extern items";
174 condense_wildcard_suffixes: CondenseWildcardSuffixes, false, "Replace strings of _ wildcards \
175 by a single .. in tuple patterns";
176
177 color: ColorConfig, false,
179 "What Color option to use when none is supplied: Always, Never, Auto";
180 required_version: RequiredVersion, false,
181 "Require a specific version of rustfmt";
182 unstable_features: UnstableFeatures, false,
183 "Enables unstable features. Only available on nightly channel";
184 disable_all_formatting: DisableAllFormatting, true, "Don't reformat anything";
185 skip_children: SkipChildren, false, "Don't reformat out of line modules";
186 hide_parse_errors: HideParseErrors, false, "Hide errors from the parser";
187 show_parse_errors: ShowParseErrors, false, "Show errors from the parser (unstable)";
188 error_on_line_overflow: ErrorOnLineOverflow, false, "Error if unable to get all lines within \
189 max_width";
190 error_on_unformatted: ErrorOnUnformatted, false,
191 "Error if unable to get comments or string literals within max_width, \
192 or they are left with trailing whitespaces";
193 ignore: Ignore, false,
194 "Skip formatting the specified files and directories";
195
196 verbose: Verbose, false, "How much to information to emit to the user";
198 file_lines: FileLinesConfig, false,
199 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
200 via the --file-lines option";
201 emit_mode: EmitModeConfig, false,
202 "What emit Mode to use when none is supplied";
203 make_backup: MakeBackup, false, "Backup changed files";
204 print_misformatted_file_names: PrintMisformattedFileNames, true,
205 "Prints the names of mismatched files that were formatted. Prints the names of \
206 files that would be formatted when used with `--check` mode. ";
207}
208
209#[derive(Error, Debug)]
210#[error("Could not output config: {0}")]
211pub struct ToTomlError(toml::ser::Error);
212
213impl PartialConfig {
214 pub fn to_toml(&self) -> Result<String, ToTomlError> {
215 let mut cloned = self.clone();
217 cloned.file_lines = None;
218 cloned.verbose = None;
219 cloned.width_heuristics = None;
220 cloned.print_misformatted_file_names = None;
221 cloned.merge_imports = None;
222 cloned.fn_args_layout = None;
223 cloned.hide_parse_errors = None;
224
225 ::toml::to_string(&cloned).map_err(ToTomlError)
226 }
227
228 pub(super) fn to_parsed_config(
229 self,
230 style_edition_override: Option<StyleEdition>,
231 edition_override: Option<Edition>,
232 version_override: Option<Version>,
233 dir: &Path,
234 ) -> Config {
235 Config::default_for_possible_style_edition(
236 style_edition_override.or(self.style_edition),
237 edition_override.or(self.edition),
238 version_override.or(self.version),
239 )
240 .fill_from_parsed_config(self, dir)
241 }
242}
243
244fn check_semver_version(range_requirement: &str, actual: &str) -> bool {
245 let mut version_req = match semver::VersionReq::parse(range_requirement) {
246 Ok(r) => r,
247 Err(e) => {
248 eprintln!("Error: failed to parse required version {range_requirement:?}: {e}");
249 return false;
250 }
251 };
252 let actual_version = match semver::Version::parse(actual) {
253 Ok(v) => v,
254 Err(e) => {
255 eprintln!("Error: failed to parse current version {actual:?}: {e}");
256 return false;
257 }
258 };
259
260 range_requirement
261 .split(',')
262 .enumerate()
263 .for_each(|(i, label)| {
264 let Some(comparator) = version_req.comparators.get_mut(i) else {
266 return;
267 };
268
269 if !label.starts_with('^') && comparator.op == semver::Op::Caret {
274 comparator.op = semver::Op::Exact;
275 }
276 });
277
278 version_req.matches(&actual_version)
279}
280
281impl Config {
282 pub fn default_for_possible_style_edition(
283 style_edition: Option<StyleEdition>,
284 edition: Option<Edition>,
285 version: Option<Version>,
286 ) -> Config {
287 match (style_edition, version, edition) {
294 (Some(se), _, _) => Self::default_with_style_edition(se),
295 (None, Some(Version::Two), _) => {
296 Self::default_with_style_edition(StyleEdition::Edition2024)
297 }
298 (None, Some(Version::One), _) => {
299 Self::default_with_style_edition(StyleEdition::Edition2015)
300 }
301 (None, None, Some(e)) => Self::default_with_style_edition(e.into()),
302 (None, None, None) => Config::default(),
303 }
304 }
305
306 pub(crate) fn version_meets_requirement(&self) -> bool {
307 if self.was_set().required_version() {
308 let version = env!("CARGO_PKG_VERSION");
309 let required_version = self.required_version();
310 if !check_semver_version(&required_version, version) {
311 eprintln!(
312 "Error: rustfmt version ({}) doesn't match the required version ({})",
313 version, required_version
314 );
315 return false;
316 }
317 }
318
319 true
320 }
321
322 pub(super) fn from_toml_path(
330 file_path: &Path,
331 edition: Option<Edition>,
332 style_edition: Option<StyleEdition>,
333 version: Option<Version>,
334 ) -> Result<Config, Error> {
335 let mut file = File::open(&file_path)?;
336 let mut toml = String::new();
337 file.read_to_string(&mut toml)?;
338 Config::from_toml_for_style_edition(&toml, file_path, edition, style_edition, version)
339 .map_err(|err| Error::new(ErrorKind::InvalidData, err))
340 }
341
342 pub(super) fn from_resolved_toml_path(
352 dir: &Path,
353 edition: Option<Edition>,
354 style_edition: Option<StyleEdition>,
355 version: Option<Version>,
356 ) -> Result<(Config, Option<PathBuf>), Error> {
357 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
361 let mut current = if dir.is_relative() {
362 env::current_dir()?.join(dir)
363 } else {
364 dir.to_path_buf()
365 };
366
367 current = fs::canonicalize(current)?;
368
369 loop {
370 match get_toml_path(¤t) {
371 Ok(Some(path)) => return Ok(Some(path)),
372 Err(e) => return Err(e),
373 _ => (),
374 }
375
376 if !current.pop() {
378 break;
379 }
380 }
381
382 if let Some(home_dir) = dirs::home_dir() {
384 if let Some(path) = get_toml_path(&home_dir)? {
385 return Ok(Some(path));
386 }
387 }
388
389 if let Some(mut config_dir) = dirs::config_dir() {
391 config_dir.push("rustfmt");
392 if let Some(path) = get_toml_path(&config_dir)? {
393 return Ok(Some(path));
394 }
395 }
396
397 Ok(None)
398 }
399
400 match resolve_project_file(dir)? {
401 None => Ok((
402 Config::default_for_possible_style_edition(style_edition, edition, version),
403 None,
404 )),
405 Some(path) => Config::from_toml_path(&path, edition, style_edition, version)
406 .map(|config| (config, Some(path))),
407 }
408 }
409
410 #[allow(dead_code)]
411 pub(super) fn from_toml(toml: &str, file_path: &Path) -> Result<Config, String> {
412 Self::from_toml_for_style_edition(toml, file_path, None, None, None)
413 }
414
415 pub(crate) fn from_toml_for_style_edition(
416 toml: &str,
417 file_path: &Path,
418 edition: Option<Edition>,
419 style_edition: Option<StyleEdition>,
420 version: Option<Version>,
421 ) -> Result<Config, String> {
422 let parsed: ::toml::Value =
423 toml::from_str(toml).map_err(|e| format!("Could not parse TOML: {}", e))?;
424 let mut err = String::new();
425 let table = parsed
426 .as_table()
427 .ok_or_else(|| String::from("Parsed config was not table"))?;
428 for key in table.keys() {
429 if !Config::is_valid_name(key) {
430 let msg = &format!("Warning: Unknown configuration option `{key}`\n");
431 err.push_str(msg)
432 }
433 }
434
435 match parsed.try_into::<PartialConfig>() {
436 Ok(parsed_config) => {
437 if !err.is_empty() {
438 eprint!("{err}");
439 }
440 let dir = file_path.parent().ok_or_else(|| {
441 format!("failed to get parent directory for {}", file_path.display())
442 })?;
443
444 Ok(parsed_config.to_parsed_config(style_edition, edition, version, dir))
445 }
446 Err(e) => {
447 let err_msg = format!(
448 "The file `{}` failed to parse.\nError details: {e}",
449 file_path.display()
450 );
451 err.push_str(&err_msg);
452 Err(err_msg)
453 }
454 }
455 }
456}
457
458pub fn load_config<O: CliOptions>(
461 file_path: Option<&Path>,
462 options: Option<O>,
463) -> Result<(Config, Option<PathBuf>), Error> {
464 let (over_ride, edition, style_edition, version) = match options {
465 Some(ref opts) => (
466 config_path(opts)?,
467 opts.edition(),
468 opts.style_edition(),
469 opts.version(),
470 ),
471 None => (None, None, None, None),
472 };
473
474 let result = if let Some(over_ride) = over_ride {
475 Config::from_toml_path(over_ride.as_ref(), edition, style_edition, version)
476 .map(|p| (p, Some(over_ride.to_owned())))
477 } else if let Some(file_path) = file_path {
478 Config::from_resolved_toml_path(file_path, edition, style_edition, version)
479 } else {
480 Ok((
481 Config::default_for_possible_style_edition(style_edition, edition, version),
482 None,
483 ))
484 };
485
486 result.map(|(mut c, p)| {
487 if let Some(options) = options {
488 options.apply_to(&mut c);
489 }
490 (c, p)
491 })
492}
493
494fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
498 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
499 for config_file_name in &CONFIG_FILE_NAMES {
500 let config_file = dir.join(config_file_name);
501 match fs::metadata(&config_file) {
502 Ok(ref md) if md.is_file() => return Ok(Some(config_file.canonicalize()?)),
505 Err(e) => {
510 if !matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) {
511 let ctx = format!("Failed to get metadata for config file {:?}", &config_file);
512 let err = anyhow::Error::new(e).context(ctx);
513 return Err(Error::new(ErrorKind::Other, err));
514 }
515 }
516 _ => {}
517 }
518 }
519 Ok(None)
520}
521
522fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
523 let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
524 Err(Error::new(
525 ErrorKind::NotFound,
526 format!(
527 "Error: unable to find a config file for the given path: `{}`",
528 path
529 ),
530 ))
531 };
532
533 match options.config_path() {
536 Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
537 Some(path) if path.is_dir() => {
538 let config_file_path = get_toml_path(path)?;
539 if config_file_path.is_some() {
540 Ok(config_file_path)
541 } else {
542 config_path_not_found(path.to_str().unwrap())
543 }
544 }
545 Some(path) => Ok(Some(
546 path.canonicalize()?,
548 )),
549 None => Ok(None),
550 }
551}
552
553#[cfg(test)]
554mod test {
555 use super::*;
556 use std::str;
557
558 use crate::config::macro_names::{MacroName, MacroSelectors};
559 use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test};
560
561 #[allow(dead_code)]
562 mod mock {
563 use super::super::*;
564 use rustfmt_config_proc_macro::config_type;
565
566 #[config_type]
567 pub(crate) enum PartiallyUnstableOption {
568 V1,
569 V2,
570 #[unstable_variant]
571 V3,
572 }
573
574 config_option_with_style_edition_default!(
575 StableOption, bool, _ => false;
576 UnstableOption, bool, _ => false;
577 PartiallyUnstable, PartiallyUnstableOption, _ => PartiallyUnstableOption::V1;
578 );
579
580 create_config! {
581 max_width: MaxWidth, true, "Maximum width of each line";
583 required_version: RequiredVersion, false, "Require a specific version of rustfmt.";
584 ignore: Ignore, false, "Skip formatting the specified files and directories.";
585 verbose: Verbose, false, "How much to information to emit to the user";
586 file_lines: FileLinesConfig, false,
587 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
588 via the --file-lines option";
589
590 imports_granularity: ImportsGranularityConfig, false, "Merge imports";
592 merge_imports: MergeImports, false, "(deprecated: use imports_granularity instead)";
593
594 fn_args_layout: FnArgsLayout, true, "(deprecated: use fn_params_layout instead)";
596 fn_params_layout: FnParamsLayout, true,
597 "Control the layout of parameters in a function signatures.";
598
599 hide_parse_errors: HideParseErrors, false,
601 "(deprecated: use show_parse_errors instead)";
602 show_parse_errors: ShowParseErrors, false,
603 "Show errors from the parser (unstable)";
604
605
606 use_small_heuristics: UseSmallHeuristics, true,
608 "Whether to use different formatting for items and \
609 expressions if they satisfy a heuristic notion of 'small'.";
610 width_heuristics: WidthHeuristicsConfig, false, "'small' heuristic values";
611
612 fn_call_width: FnCallWidth, true, "Maximum width of the args of a function call before \
613 falling back to vertical formatting.";
614 attr_fn_like_width: AttrFnLikeWidth, true, "Maximum width of the args of a \
615 function-like attributes before falling back to vertical formatting.";
616 struct_lit_width: StructLitWidth, true, "Maximum width in the body of a struct lit \
617 before falling back to vertical formatting.";
618 struct_variant_width: StructVariantWidth, true, "Maximum width in the body of a struct \
619 variant before falling back to vertical formatting.";
620 array_width: ArrayWidth, true, "Maximum width of an array literal before falling \
621 back to vertical formatting.";
622 chain_width: ChainWidth, true, "Maximum length of a chain to fit on a single line.";
623 single_line_if_else_max_width: SingleLineIfElseMaxWidth, true, "Maximum line length \
624 for single line if-else expressions. A value of zero means always break if-else \
625 expressions.";
626 single_line_let_else_max_width: SingleLineLetElseMaxWidth, false, "Maximum line length \
627 for single line let-else statements. A value of zero means always format the \
628 divergent `else` block over multiple lines.";
629
630 stable_option: StableOption, true, "A stable option";
632 unstable_option: UnstableOption, false, "An unstable option";
633 partially_unstable_option: PartiallyUnstable, true, "A partially unstable option";
634 edition: EditionConfig, true, "blah";
635 style_edition: StyleEditionConfig, true, "blah";
636 version: VersionConfig, false, "blah blah"
637 }
638
639 #[cfg(test)]
640 mod partially_unstable_option {
641 use super::{Config, PartialConfig, PartiallyUnstableOption};
642 use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test};
643 use std::path::Path;
644
645 #[test]
647 fn test_from_toml_stable_value() {
648 let toml = r#"
649 partially_unstable_option = "V2"
650 "#;
651 let partial_config: PartialConfig = toml::from_str(toml).unwrap();
652 let config = Config::default();
653 let config = config.fill_from_parsed_config(partial_config, Path::new(""));
654 assert_eq!(
655 config.partially_unstable_option(),
656 PartiallyUnstableOption::V2
657 );
658 }
659
660 #[stable_only_test]
662 #[test]
663 fn test_from_toml_unstable_value_on_stable() {
664 let toml = r#"
665 partially_unstable_option = "V3"
666 "#;
667 let partial_config: PartialConfig = toml::from_str(toml).unwrap();
668 let config = Config::default();
669 let config = config.fill_from_parsed_config(partial_config, Path::new(""));
670 assert_eq!(
671 config.partially_unstable_option(),
672 PartiallyUnstableOption::V1
674 );
675 }
676
677 #[nightly_only_test]
679 #[test]
680 fn test_from_toml_unstable_value_on_nightly() {
681 let toml = r#"
682 partially_unstable_option = "V3"
683 "#;
684 let partial_config: PartialConfig = toml::from_str(toml).unwrap();
685 let config = Config::default();
686 let config = config.fill_from_parsed_config(partial_config, Path::new(""));
687 assert_eq!(
688 config.partially_unstable_option(),
689 PartiallyUnstableOption::V3
690 );
691 }
692 }
693 }
694
695 #[test]
696 fn test_config_set() {
697 let mut config = Config::default();
698 config.set().verbose(Verbosity::Quiet);
699 assert_eq!(config.verbose(), Verbosity::Quiet);
700 config.set().verbose(Verbosity::Normal);
701 assert_eq!(config.verbose(), Verbosity::Normal);
702 }
703
704 #[test]
705 fn test_config_used_to_toml() {
706 let config = Config::default();
707
708 let merge_derives = config.merge_derives();
709 let skip_children = config.skip_children();
710
711 let used_options = config.used_options();
712 let toml = used_options.to_toml().unwrap();
713 assert_eq!(
714 toml,
715 format!("merge_derives = {merge_derives}\nskip_children = {skip_children}\n",)
716 );
717 }
718
719 #[test]
720 fn test_was_set() {
721 let config = Config::from_toml("hard_tabs = true", Path::new("./rustfmt.toml")).unwrap();
722
723 assert_eq!(config.was_set().hard_tabs(), true);
724 assert_eq!(config.was_set().verbose(), false);
725 }
726
727 const PRINT_DOCS_STABLE_OPTION: &str = "stable_option <boolean> Default: false";
728 const PRINT_DOCS_UNSTABLE_OPTION: &str = "unstable_option <boolean> Default: false (unstable)";
729 const PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION: &str =
730 "partially_unstable_option [V1|V2|V3 (unstable)] Default: V1";
731
732 #[test]
733 fn test_print_docs_exclude_unstable() {
734 use self::mock::Config;
735
736 let mut output = Vec::new();
737 Config::print_docs(&mut output, false);
738
739 let s = str::from_utf8(&output).unwrap();
740 assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true);
741 assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), false);
742 assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true);
743 }
744
745 #[test]
746 fn test_print_docs_include_unstable() {
747 use self::mock::Config;
748
749 let mut output = Vec::new();
750 Config::print_docs(&mut output, true);
751
752 let s = str::from_utf8(&output).unwrap();
753 assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true);
754 assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), true);
755 assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true);
756 }
757
758 #[test]
759 fn test_dump_default_config() {
760 let default_config = format!(
761 r#"max_width = 100
762hard_tabs = false
763tab_spaces = 4
764newline_style = "Auto"
765indent_style = "Block"
766use_small_heuristics = "Default"
767fn_call_width = 60
768attr_fn_like_width = 70
769struct_lit_width = 18
770struct_variant_width = 35
771array_width = 60
772chain_width = 60
773single_line_if_else_max_width = 50
774single_line_let_else_max_width = 50
775wrap_comments = false
776format_code_in_doc_comments = false
777doc_comment_code_block_width = 100
778doc_comment_code_block_small_heuristics = "Inherit"
779comment_width = 80
780normalize_comments = false
781normalize_doc_attributes = false
782format_strings = false
783format_macro_matchers = false
784format_macro_bodies = true
785skip_macro_invocations = []
786hex_literal_case = "Preserve"
787float_literal_trailing_zero = "Preserve"
788empty_item_single_line = true
789struct_lit_single_line = true
790fn_single_line = false
791where_single_line = false
792imports_indent = "Block"
793imports_layout = "Mixed"
794imports_granularity = "Preserve"
795group_imports = "Preserve"
796reorder_imports = true
797reorder_modules = true
798reorder_impl_items = false
799type_punctuation_density = "Wide"
800space_before_colon = false
801space_after_colon = true
802spaces_around_ranges = false
803binop_separator = "Front"
804remove_nested_parens = true
805combine_control_expr = true
806short_array_element_width_threshold = 10
807overflow_delimited_expr = false
808struct_field_align_threshold = 0
809enum_discrim_align_threshold = 0
810match_arm_blocks = true
811match_arm_leading_pipes = "Never"
812match_arm_indent = true
813force_multiline_blocks = false
814fn_params_layout = "Tall"
815brace_style = "SameLineWhere"
816control_brace_style = "AlwaysSameLine"
817trailing_semicolon = true
818trailing_comma = "Vertical"
819match_block_trailing_comma = false
820blank_lines_upper_bound = 1
821blank_lines_lower_bound = 0
822edition = "2015"
823style_edition = "2015"
824version = "One"
825inline_attribute_width = 0
826format_generated_files = true
827generated_marker_line_search_limit = 5
828merge_derives = true
829use_try_shorthand = false
830use_field_init_shorthand = false
831force_explicit_abi = true
832condense_wildcard_suffixes = false
833color = "Auto"
834required_version = "{}"
835unstable_features = false
836disable_all_formatting = false
837skip_children = false
838show_parse_errors = true
839error_on_line_overflow = false
840error_on_unformatted = false
841ignore = []
842emit_mode = "Files"
843make_backup = false
844"#,
845 env!("CARGO_PKG_VERSION")
846 );
847 let toml = Config::default().all_options().to_toml().unwrap();
848 assert_eq!(&toml, &default_config);
849 }
850
851 #[test]
852 fn test_dump_style_edition_2024_config() {
853 let edition_2024_config = format!(
854 r#"max_width = 100
855hard_tabs = false
856tab_spaces = 4
857newline_style = "Auto"
858indent_style = "Block"
859use_small_heuristics = "Default"
860fn_call_width = 60
861attr_fn_like_width = 70
862struct_lit_width = 18
863struct_variant_width = 35
864array_width = 60
865chain_width = 60
866single_line_if_else_max_width = 50
867single_line_let_else_max_width = 50
868wrap_comments = false
869format_code_in_doc_comments = false
870doc_comment_code_block_width = 100
871doc_comment_code_block_small_heuristics = "Inherit"
872comment_width = 80
873normalize_comments = false
874normalize_doc_attributes = false
875format_strings = false
876format_macro_matchers = false
877format_macro_bodies = true
878skip_macro_invocations = []
879hex_literal_case = "Preserve"
880float_literal_trailing_zero = "Preserve"
881empty_item_single_line = true
882struct_lit_single_line = true
883fn_single_line = false
884where_single_line = false
885imports_indent = "Block"
886imports_layout = "Mixed"
887imports_granularity = "Preserve"
888group_imports = "Preserve"
889reorder_imports = true
890reorder_modules = true
891reorder_impl_items = false
892type_punctuation_density = "Wide"
893space_before_colon = false
894space_after_colon = true
895spaces_around_ranges = false
896binop_separator = "Front"
897remove_nested_parens = true
898combine_control_expr = true
899short_array_element_width_threshold = 10
900overflow_delimited_expr = false
901struct_field_align_threshold = 0
902enum_discrim_align_threshold = 0
903match_arm_blocks = true
904match_arm_leading_pipes = "Never"
905match_arm_indent = true
906force_multiline_blocks = false
907fn_params_layout = "Tall"
908brace_style = "SameLineWhere"
909control_brace_style = "AlwaysSameLine"
910trailing_semicolon = true
911trailing_comma = "Vertical"
912match_block_trailing_comma = false
913blank_lines_upper_bound = 1
914blank_lines_lower_bound = 0
915edition = "2015"
916style_edition = "2024"
917version = "Two"
918inline_attribute_width = 0
919format_generated_files = true
920generated_marker_line_search_limit = 5
921merge_derives = true
922use_try_shorthand = false
923use_field_init_shorthand = false
924force_explicit_abi = true
925condense_wildcard_suffixes = false
926color = "Auto"
927required_version = "{}"
928unstable_features = false
929disable_all_formatting = false
930skip_children = false
931show_parse_errors = true
932error_on_line_overflow = false
933error_on_unformatted = false
934ignore = []
935emit_mode = "Files"
936make_backup = false
937"#,
938 env!("CARGO_PKG_VERSION")
939 );
940 let toml = Config::default_with_style_edition(StyleEdition::Edition2024)
941 .all_options()
942 .to_toml()
943 .unwrap();
944 assert_eq!(&toml, &edition_2024_config);
945 }
946
947 #[test]
948 fn test_editions_2015_2018_2021_identical() {
949 let get_edition_toml = |style_edition: StyleEdition| {
950 Config::default_with_style_edition(style_edition)
951 .all_options()
952 .to_toml()
953 .unwrap()
954 };
955 let edition2015 = get_edition_toml(StyleEdition::Edition2015);
956 let edition2018 = get_edition_toml(StyleEdition::Edition2018);
957 let edition2021 = get_edition_toml(StyleEdition::Edition2021);
958 assert_eq!(edition2015, edition2018);
959 assert_eq!(edition2018, edition2021);
960 }
961
962 #[stable_only_test]
963 #[test]
964 fn test_as_not_nightly_channel() {
965 let mut config = Config::default();
966 assert_eq!(config.was_set().unstable_features(), false);
967 config.set().unstable_features(true);
968 assert_eq!(config.was_set().unstable_features(), false);
969 }
970
971 #[nightly_only_test]
972 #[test]
973 fn test_as_nightly_channel() {
974 let mut config = Config::default();
975 config.set().unstable_features(true);
976 assert_eq!(config.was_set().unstable_features(), false);
979 config.set().unstable_features(true);
980 assert_eq!(config.unstable_features(), true);
981 }
982
983 #[nightly_only_test]
984 #[test]
985 fn test_unstable_from_toml() {
986 let config =
987 Config::from_toml("unstable_features = true", Path::new("./rustfmt.toml")).unwrap();
988 assert_eq!(config.was_set().unstable_features(), true);
989 assert_eq!(config.unstable_features(), true);
990 }
991
992 #[test]
993 fn test_set_cli() {
994 let mut config = Config::default();
995 assert_eq!(config.was_set().edition(), false);
996 assert_eq!(config.was_set_cli().edition(), false);
997 config.set().edition(Edition::Edition2021);
998 assert_eq!(config.was_set().edition(), false);
999 assert_eq!(config.was_set_cli().edition(), false);
1000 config.set_cli().edition(Edition::Edition2021);
1001 assert_eq!(config.was_set().edition(), false);
1002 assert_eq!(config.was_set_cli().edition(), true);
1003 assert_eq!(config.was_set_cli().emit_mode(), false);
1004 }
1005
1006 #[cfg(test)]
1007 mod deprecated_option_merge_imports {
1008 use super::*;
1009
1010 #[nightly_only_test]
1011 #[test]
1012 fn test_old_option_set() {
1013 let toml = r#"
1014 unstable_features = true
1015 merge_imports = true
1016 "#;
1017 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1018 assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
1019 }
1020
1021 #[nightly_only_test]
1022 #[test]
1023 fn test_both_set() {
1024 let toml = r#"
1025 unstable_features = true
1026 merge_imports = true
1027 imports_granularity = "Preserve"
1028 "#;
1029 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1030 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
1031 }
1032
1033 #[nightly_only_test]
1034 #[test]
1035 fn test_new_overridden() {
1036 let toml = r#"
1037 unstable_features = true
1038 merge_imports = true
1039 "#;
1040 let mut config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1041 config.override_value("imports_granularity", "Preserve");
1042 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
1043 }
1044
1045 #[nightly_only_test]
1046 #[test]
1047 fn test_old_overridden() {
1048 let toml = r#"
1049 unstable_features = true
1050 imports_granularity = "Module"
1051 "#;
1052 let mut config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1053 config.override_value("merge_imports", "true");
1054 assert_eq!(config.imports_granularity(), ImportGranularity::Module);
1056 }
1057 }
1058
1059 #[cfg(test)]
1060 mod use_small_heuristics {
1061 use super::*;
1062
1063 #[test]
1064 fn test_default_sets_correct_widths() {
1065 let toml = r#"
1066 use_small_heuristics = "Default"
1067 max_width = 200
1068 "#;
1069 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1070 assert_eq!(config.array_width(), 120);
1071 assert_eq!(config.attr_fn_like_width(), 140);
1072 assert_eq!(config.chain_width(), 120);
1073 assert_eq!(config.fn_call_width(), 120);
1074 assert_eq!(config.single_line_if_else_max_width(), 100);
1075 assert_eq!(config.struct_lit_width(), 36);
1076 assert_eq!(config.struct_variant_width(), 70);
1077 }
1078
1079 #[test]
1080 fn test_max_sets_correct_widths() {
1081 let toml = r#"
1082 use_small_heuristics = "Max"
1083 max_width = 120
1084 "#;
1085 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1086 assert_eq!(config.array_width(), 120);
1087 assert_eq!(config.attr_fn_like_width(), 120);
1088 assert_eq!(config.chain_width(), 120);
1089 assert_eq!(config.fn_call_width(), 120);
1090 assert_eq!(config.single_line_if_else_max_width(), 120);
1091 assert_eq!(config.struct_lit_width(), 120);
1092 assert_eq!(config.struct_variant_width(), 120);
1093 }
1094
1095 #[test]
1096 fn test_off_sets_correct_widths() {
1097 let toml = r#"
1098 use_small_heuristics = "Off"
1099 max_width = 100
1100 "#;
1101 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1102 assert_eq!(config.array_width(), usize::MAX);
1103 assert_eq!(config.attr_fn_like_width(), usize::MAX);
1104 assert_eq!(config.chain_width(), usize::MAX);
1105 assert_eq!(config.fn_call_width(), usize::MAX);
1106 assert_eq!(config.single_line_if_else_max_width(), 0);
1107 assert_eq!(config.struct_lit_width(), 0);
1108 assert_eq!(config.struct_variant_width(), 0);
1109 }
1110
1111 #[test]
1112 fn test_override_works_with_default() {
1113 let toml = r#"
1114 use_small_heuristics = "Default"
1115 array_width = 20
1116 attr_fn_like_width = 40
1117 chain_width = 20
1118 fn_call_width = 90
1119 single_line_if_else_max_width = 40
1120 struct_lit_width = 30
1121 struct_variant_width = 34
1122 "#;
1123 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1124 assert_eq!(config.array_width(), 20);
1125 assert_eq!(config.attr_fn_like_width(), 40);
1126 assert_eq!(config.chain_width(), 20);
1127 assert_eq!(config.fn_call_width(), 90);
1128 assert_eq!(config.single_line_if_else_max_width(), 40);
1129 assert_eq!(config.struct_lit_width(), 30);
1130 assert_eq!(config.struct_variant_width(), 34);
1131 }
1132
1133 #[test]
1134 fn test_override_with_max() {
1135 let toml = r#"
1136 use_small_heuristics = "Max"
1137 array_width = 20
1138 attr_fn_like_width = 40
1139 chain_width = 20
1140 fn_call_width = 90
1141 single_line_if_else_max_width = 40
1142 struct_lit_width = 30
1143 struct_variant_width = 34
1144 "#;
1145 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1146 assert_eq!(config.array_width(), 20);
1147 assert_eq!(config.attr_fn_like_width(), 40);
1148 assert_eq!(config.chain_width(), 20);
1149 assert_eq!(config.fn_call_width(), 90);
1150 assert_eq!(config.single_line_if_else_max_width(), 40);
1151 assert_eq!(config.struct_lit_width(), 30);
1152 assert_eq!(config.struct_variant_width(), 34);
1153 }
1154
1155 #[test]
1156 fn test_override_with_off() {
1157 let toml = r#"
1158 use_small_heuristics = "Off"
1159 array_width = 20
1160 attr_fn_like_width = 40
1161 chain_width = 20
1162 fn_call_width = 90
1163 single_line_if_else_max_width = 40
1164 struct_lit_width = 30
1165 struct_variant_width = 34
1166 "#;
1167 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1168 assert_eq!(config.array_width(), 20);
1169 assert_eq!(config.attr_fn_like_width(), 40);
1170 assert_eq!(config.chain_width(), 20);
1171 assert_eq!(config.fn_call_width(), 90);
1172 assert_eq!(config.single_line_if_else_max_width(), 40);
1173 assert_eq!(config.struct_lit_width(), 30);
1174 assert_eq!(config.struct_variant_width(), 34);
1175 }
1176
1177 #[test]
1178 fn test_fn_call_width_config_exceeds_max_width() {
1179 let toml = r#"
1180 max_width = 90
1181 fn_call_width = 95
1182 "#;
1183 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1184 assert_eq!(config.fn_call_width(), 90);
1185 }
1186
1187 #[test]
1188 fn test_attr_fn_like_width_config_exceeds_max_width() {
1189 let toml = r#"
1190 max_width = 80
1191 attr_fn_like_width = 90
1192 "#;
1193 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1194 assert_eq!(config.attr_fn_like_width(), 80);
1195 }
1196
1197 #[test]
1198 fn test_struct_lit_config_exceeds_max_width() {
1199 let toml = r#"
1200 max_width = 78
1201 struct_lit_width = 90
1202 "#;
1203 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1204 assert_eq!(config.struct_lit_width(), 78);
1205 }
1206
1207 #[test]
1208 fn test_struct_variant_width_config_exceeds_max_width() {
1209 let toml = r#"
1210 max_width = 80
1211 struct_variant_width = 90
1212 "#;
1213 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1214 assert_eq!(config.struct_variant_width(), 80);
1215 }
1216
1217 #[test]
1218 fn test_array_width_config_exceeds_max_width() {
1219 let toml = r#"
1220 max_width = 60
1221 array_width = 80
1222 "#;
1223 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1224 assert_eq!(config.array_width(), 60);
1225 }
1226
1227 #[test]
1228 fn test_chain_width_config_exceeds_max_width() {
1229 let toml = r#"
1230 max_width = 80
1231 chain_width = 90
1232 "#;
1233 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1234 assert_eq!(config.chain_width(), 80);
1235 }
1236
1237 #[test]
1238 fn test_single_line_if_else_max_width_config_exceeds_max_width() {
1239 let toml = r#"
1240 max_width = 70
1241 single_line_if_else_max_width = 90
1242 "#;
1243 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1244 assert_eq!(config.single_line_if_else_max_width(), 70);
1245 }
1246
1247 #[test]
1248 fn test_override_fn_call_width_exceeds_max_width() {
1249 let mut config = Config::default();
1250 config.override_value("fn_call_width", "101");
1251 assert_eq!(config.fn_call_width(), 100);
1252 }
1253
1254 #[test]
1255 fn test_override_attr_fn_like_width_exceeds_max_width() {
1256 let mut config = Config::default();
1257 config.override_value("attr_fn_like_width", "101");
1258 assert_eq!(config.attr_fn_like_width(), 100);
1259 }
1260
1261 #[test]
1262 fn test_override_struct_lit_exceeds_max_width() {
1263 let mut config = Config::default();
1264 config.override_value("struct_lit_width", "101");
1265 assert_eq!(config.struct_lit_width(), 100);
1266 }
1267
1268 #[test]
1269 fn test_override_struct_variant_width_exceeds_max_width() {
1270 let mut config = Config::default();
1271 config.override_value("struct_variant_width", "101");
1272 assert_eq!(config.struct_variant_width(), 100);
1273 }
1274
1275 #[test]
1276 fn test_override_array_width_exceeds_max_width() {
1277 let mut config = Config::default();
1278 config.override_value("array_width", "101");
1279 assert_eq!(config.array_width(), 100);
1280 }
1281
1282 #[test]
1283 fn test_override_chain_width_exceeds_max_width() {
1284 let mut config = Config::default();
1285 config.override_value("chain_width", "101");
1286 assert_eq!(config.chain_width(), 100);
1287 }
1288
1289 #[test]
1290 fn test_override_single_line_if_else_max_width_exceeds_max_width() {
1291 let mut config = Config::default();
1292 config.override_value("single_line_if_else_max_width", "101");
1293 assert_eq!(config.single_line_if_else_max_width(), 100);
1294 }
1295 }
1296
1297 #[cfg(test)]
1298 mod partially_unstable_option {
1299 use super::mock::{Config, PartiallyUnstableOption};
1300
1301 #[test]
1303 fn test_override_stable_value() {
1304 let mut config = Config::default();
1305 config.override_value("partially_unstable_option", "V2");
1306 assert_eq!(
1307 config.partially_unstable_option(),
1308 PartiallyUnstableOption::V2
1309 );
1310 }
1311
1312 #[test]
1314 fn test_override_unstable_value() {
1315 let mut config = Config::default();
1316 config.override_value("partially_unstable_option", "V3");
1317 assert_eq!(
1318 config.partially_unstable_option(),
1319 PartiallyUnstableOption::V3
1320 );
1321 }
1322 }
1323
1324 #[test]
1325 fn test_override_skip_macro_invocations() {
1326 let mut config = Config::default();
1327 config.override_value("skip_macro_invocations", r#"["*", "println"]"#);
1328 assert_eq!(
1329 config.skip_macro_invocations(),
1330 MacroSelectors(vec![
1331 MacroSelector::All,
1332 MacroSelector::Name(MacroName::new("println".to_owned()))
1333 ])
1334 );
1335 }
1336
1337 #[cfg(test)]
1338 mod required_version {
1339 use super::*;
1340
1341 #[allow(dead_code)] fn get_current_version() -> semver::Version {
1343 semver::Version::parse(env!("CARGO_PKG_VERSION")).unwrap()
1344 }
1345
1346 #[nightly_only_test]
1347 #[test]
1348 fn test_required_version_default() {
1349 let config = Config::default();
1350 assert!(config.version_meets_requirement());
1351 }
1352
1353 #[nightly_only_test]
1354 #[test]
1355 fn test_current_required_version() {
1356 let toml = format!("required_version=\"{}\"", env!("CARGO_PKG_VERSION"));
1357 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1358
1359 assert!(config.version_meets_requirement());
1360 }
1361
1362 #[nightly_only_test]
1363 #[test]
1364 fn test_required_version_above() {
1365 let toml = "required_version=\"1000.0.0\"";
1366 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1367
1368 assert!(!config.version_meets_requirement());
1369 }
1370
1371 #[nightly_only_test]
1372 #[test]
1373 fn test_required_version_below() {
1374 let versions = vec!["0.0.0", "0.0.1", "0.1.0"];
1375
1376 for version in versions {
1377 let toml = format!("required_version=\"{}\"", version.to_string());
1378 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1379
1380 assert!(!config.version_meets_requirement());
1381 }
1382 }
1383
1384 #[nightly_only_test]
1385 #[test]
1386 fn test_required_version_tilde() {
1387 let toml = format!("required_version=\"~{}\"", env!("CARGO_PKG_VERSION"));
1388 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1389
1390 assert!(config.version_meets_requirement());
1391 }
1392
1393 #[nightly_only_test]
1394 #[test]
1395 fn test_required_version_caret() {
1396 let current_version = get_current_version();
1397
1398 for minor in current_version.minor..0 {
1399 let toml = format!(
1400 "required_version=\"^{}.{}.0\"",
1401 current_version.major.to_string(),
1402 minor.to_string()
1403 );
1404 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1405
1406 assert!(!config.version_meets_requirement());
1407 }
1408 }
1409
1410 #[nightly_only_test]
1411 #[test]
1412 fn test_required_version_greater_than() {
1413 let toml = "required_version=\">1.0.0\"";
1414 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1415
1416 assert!(config.version_meets_requirement());
1417 }
1418
1419 #[nightly_only_test]
1420 #[test]
1421 fn test_required_version_less_than() {
1422 let toml = "required_version=\"<1.0.0\"";
1423 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1424
1425 assert!(!config.version_meets_requirement());
1426 }
1427
1428 #[nightly_only_test]
1429 #[test]
1430 fn test_required_version_range() {
1431 let current_version = get_current_version();
1432
1433 let toml = format!(
1434 "required_version=\">={}.0.0, <{}.0.0\"",
1435 current_version.major,
1436 current_version.major + 1
1437 );
1438 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1439
1440 assert!(config.version_meets_requirement());
1441 }
1442
1443 #[nightly_only_test]
1444 #[test]
1445 fn test_required_version_exact_boundary() {
1446 let toml = format!("required_version=\"{}\"", get_current_version().to_string());
1447 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1448
1449 assert!(config.version_meets_requirement());
1450 }
1451
1452 #[nightly_only_test]
1453 #[test]
1454 fn test_required_version_pre_release() {
1455 let toml = format!(
1456 "required_version=\"^{}-alpha\"",
1457 get_current_version().to_string()
1458 );
1459 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1460
1461 assert!(config.version_meets_requirement());
1462 }
1463
1464 #[nightly_only_test]
1465 #[test]
1466 fn test_required_version_with_build_metadata() {
1467 let toml = format!(
1468 "required_version=\"{}+build.1\"",
1469 get_current_version().to_string()
1470 );
1471
1472 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1473
1474 assert!(config.version_meets_requirement());
1475 }
1476
1477 #[nightly_only_test]
1478 #[test]
1479 fn test_required_version_invalid_specification() {
1480 let toml = "required_version=\"not.a.version\"";
1481 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1482
1483 assert!(!config.version_meets_requirement())
1484 }
1485
1486 #[nightly_only_test]
1487 #[test]
1488 fn test_required_version_complex_range() {
1489 let current_version = get_current_version();
1490
1491 let toml = format!(
1492 "required_version=\">={}.0.0, <{}.0.0, ~{}.{}.0\"",
1493 current_version.major,
1494 current_version.major + 1,
1495 current_version.major,
1496 current_version.minor
1497 );
1498 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1499
1500 assert!(config.version_meets_requirement());
1501 }
1502
1503 #[nightly_only_test]
1504 #[test]
1505 fn test_required_version_wildcard_major() {
1506 let toml = "required_version=\"1.x\"";
1507 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1508
1509 assert!(config.version_meets_requirement());
1510 }
1511
1512 #[nightly_only_test]
1513 #[test]
1514 fn test_required_version_wildcard_any() {
1515 let toml = "required_version=\"*\"";
1516 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1517
1518 assert!(config.version_meets_requirement());
1519 }
1520
1521 #[nightly_only_test]
1522 #[test]
1523 fn test_required_version_major_version_zero() {
1524 let toml = "required_version=\"0.1.0\"";
1525 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1526
1527 assert!(!config.version_meets_requirement());
1528 }
1529
1530 #[nightly_only_test]
1531 #[test]
1532 fn test_required_version_future_major_version() {
1533 let toml = "required_version=\"3.0.0\"";
1534 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1535
1536 assert!(!config.version_meets_requirement());
1537 }
1538
1539 #[nightly_only_test]
1540 #[test]
1541 fn test_required_version_fail_different_operator() {
1542 let toml = "required_version=\"!=1.0.0\"";
1544 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1545
1546 assert!(!config.version_meets_requirement());
1547 }
1548 }
1549
1550 #[cfg(test)]
1551 mod check_semver_version {
1552 use super::*;
1553
1554 #[test]
1555 fn test_exact_version_match() {
1556 assert!(check_semver_version("1.0.0", "1.0.0"));
1557 assert!(!check_semver_version("1.0.0", "1.1.0"));
1558 assert!(!check_semver_version("1.0.0", "1.0.1"));
1559 assert!(!check_semver_version("1.0.0", "2.1.0"));
1560 assert!(!check_semver_version("1.0.0", "0.1.0"));
1561 assert!(!check_semver_version("1.0.0", "0.0.1"));
1562 }
1563
1564 #[test]
1565 fn test_version_mismatch() {
1566 assert!(!check_semver_version("2.0.0", "1.0.0"));
1567 }
1568
1569 #[test]
1570 fn test_patch_version_greater() {
1571 assert!(check_semver_version("^1.0.0", "1.0.1"));
1572 }
1573
1574 #[test]
1575 fn test_minor_version_greater() {
1576 assert!(check_semver_version("^1.0.0", "1.1.0"));
1577 }
1578
1579 #[test]
1580 fn test_major_version_less() {
1581 assert!(!check_semver_version("1.0.0", "0.9.0"));
1582 }
1583
1584 #[test]
1585 fn test_prerelease_less_than_release() {
1586 assert!(!check_semver_version("1.0.0", "1.0.0-alpha"));
1587 }
1588
1589 #[test]
1590 fn test_prerelease_version_specific_match() {
1591 assert!(check_semver_version("1.0.0-alpha", "1.0.0-alpha"));
1592 }
1593
1594 #[test]
1595 fn test_build_metadata_ignored() {
1596 assert!(check_semver_version("1.0.0", "1.0.0+build.1"));
1597 }
1598
1599 #[test]
1600 fn test_greater_than_requirement() {
1601 assert!(check_semver_version(">1.0.0", "1.1.0"));
1602 }
1603
1604 #[test]
1605 fn test_less_than_requirement_fails_when_greater() {
1606 assert!(!check_semver_version("<1.0.0", "1.1.0"));
1607 }
1608
1609 #[test]
1610 fn test_caret_requirement_matches_minor_update() {
1611 assert!(check_semver_version("^1.1.0", "1.2.0"));
1612 }
1613
1614 #[test]
1615 fn test_tilde_requirement_matches_patch_update() {
1616 assert!(check_semver_version("~1.0.0", "1.0.1"));
1617 }
1618
1619 #[test]
1620 fn test_range_requirement_inclusive() {
1621 assert!(check_semver_version(">=1.0.0, <2.0.0", "1.5.0"));
1622 }
1623
1624 #[test]
1625 fn test_pre_release_specific_match() {
1626 assert!(check_semver_version("1.0.0-alpha.1", "1.0.0-alpha.1"));
1627 }
1628
1629 #[test]
1630 fn test_pre_release_non_match_when_requiring_release() {
1631 assert!(!check_semver_version("1.0.0", "1.0.0-alpha.1"));
1632 }
1633
1634 #[test]
1637 fn test_invalid_or() {
1638 assert!(!check_semver_version("1.0.0 || 2.0.0", "1.0.0"));
1639 assert!(!check_semver_version("1.0.0 || 2.0.0", "2.0.0"));
1640 assert!(!check_semver_version("1.0.0 || 2.0.0", "3.0.0"));
1641 }
1642
1643 #[test]
1644 fn test_wildcard_match_minor() {
1645 assert!(check_semver_version("1.*", "1.1.0"));
1646 assert!(check_semver_version("1.*, <2.0.0", "1.1.0"));
1647 }
1648
1649 #[test]
1650 fn test_wildcard_mismatch() {
1651 assert!(!check_semver_version("1.*, <2.0.0", "2.1.0"));
1652 assert!(!check_semver_version("1.*, <2.0.0", "2.0.0"));
1653 assert!(!check_semver_version("1.*, <2.*", "2.1.0"));
1654 assert!(!check_semver_version("1.*, <2.*", "2.0.0"));
1655
1656 assert!(!check_semver_version("1.*, >2.0.0", "1.1.0"));
1657 assert!(!check_semver_version("1.*, >2.0.0", "1.0.0"));
1658 assert!(!check_semver_version("1.*, >2.*", "1.1.0"));
1659 assert!(!check_semver_version("1.*, >2.*", "1.0.0"));
1660
1661 assert!(!check_semver_version("<1.5.0, >1.10.*", "1.6.0"));
1662 }
1663
1664 #[test]
1665 fn test_wildcard_match_major() {
1666 assert!(check_semver_version("2.*", "2.0.0"));
1667 }
1668
1669 #[test]
1670 fn test_wildcard_match_patch() {
1671 assert!(check_semver_version("1.0.*", "1.0.1"));
1672 }
1673
1674 #[test]
1675 fn test_invalid_inputs() {
1676 assert!(!check_semver_version("not.a.requirement", "1.0.0"));
1677 assert!(!check_semver_version("1.0.0", "not.a.version"));
1678 }
1679
1680 #[test]
1681 fn test_version_with_pre_release_and_build() {
1682 assert!(check_semver_version("1.0.0-alpha", "1.0.0-alpha+001"));
1683 }
1684
1685 #[test]
1687 fn test_pre_release_numeric_vs_alphanumeric() {
1688 assert!(!check_semver_version("^1.0.0-alpha.beta", "1.0.0-alpha.1"));
1689 assert!(check_semver_version("^1.0.0-alpha.1", "1.0.0-alpha.beta"));
1690 }
1691
1692 #[test]
1694 fn test_wildcard_any() {
1695 assert!(check_semver_version("*", "1.0.0"));
1696 assert!(check_semver_version("*", "1.0.0+build"));
1697 }
1698
1699 #[test]
1701 fn test_pre_release_lexicographic_ordering() {
1702 assert!(check_semver_version(
1703 "^1.0.0-alpha.alpha",
1704 "1.0.0-alpha.beta",
1705 ));
1706 assert!(!check_semver_version(
1707 "^1.0.0-alpha.beta",
1708 "1.0.0-alpha.alpha",
1709 ));
1710 }
1711
1712 #[test]
1714 fn test_wildcard_any_with_range() {
1715 assert!(!check_semver_version("*, <2.0.0", "1.0.0"));
1716 assert!(!check_semver_version("*, 1.0.0", "1.5.0"));
1717 }
1718 }
1719}