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_adjust_max_width() {
706 let mut config = Config::default();
711 config.reduce_max_width(usize::MAX);
712 assert_eq!(config.max_width(), 0);
713
714 let mut config = Config::default();
716 config.set().max_width(usize::MAX - 1);
717 config.increase_max_width(2);
718 assert_eq!(config.max_width(), usize::MAX);
719 }
720
721 #[test]
722 fn test_config_used_to_toml() {
723 let config = Config::default();
724
725 let merge_derives = config.merge_derives();
726 let skip_children = config.skip_children();
727
728 let used_options = config.used_options();
729 let toml = used_options.to_toml().unwrap();
730 assert_eq!(
731 toml,
732 format!("merge_derives = {merge_derives}\nskip_children = {skip_children}\n",)
733 );
734 }
735
736 #[test]
737 fn test_was_set() {
738 let config = Config::from_toml("hard_tabs = true", Path::new("./rustfmt.toml")).unwrap();
739
740 assert_eq!(config.was_set().hard_tabs(), true);
741 assert_eq!(config.was_set().verbose(), false);
742 }
743
744 const PRINT_DOCS_STABLE_OPTION: &str = "stable_option <boolean> Default: false";
745 const PRINT_DOCS_UNSTABLE_OPTION: &str = "unstable_option <boolean> Default: false (unstable)";
746 const PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION: &str =
747 "partially_unstable_option [V1|V2|V3 (unstable)] Default: V1";
748
749 #[test]
750 fn test_print_docs_exclude_unstable() {
751 use self::mock::Config;
752
753 let mut output = Vec::new();
754 Config::print_docs(&mut output, false);
755
756 let s = str::from_utf8(&output).unwrap();
757 assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true);
758 assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), false);
759 assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true);
760 }
761
762 #[test]
763 fn test_print_docs_include_unstable() {
764 use self::mock::Config;
765
766 let mut output = Vec::new();
767 Config::print_docs(&mut output, true);
768
769 let s = str::from_utf8(&output).unwrap();
770 assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true);
771 assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), true);
772 assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true);
773 }
774
775 #[test]
776 fn test_dump_default_config() {
777 let default_config = format!(
778 r#"max_width = 100
779hard_tabs = false
780tab_spaces = 4
781newline_style = "Auto"
782indent_style = "Block"
783use_small_heuristics = "Default"
784fn_call_width = 60
785attr_fn_like_width = 70
786struct_lit_width = 18
787struct_variant_width = 35
788array_width = 60
789chain_width = 60
790single_line_if_else_max_width = 50
791single_line_let_else_max_width = 50
792wrap_comments = false
793format_code_in_doc_comments = false
794doc_comment_code_block_width = 100
795doc_comment_code_block_small_heuristics = "Inherit"
796comment_width = 80
797normalize_comments = false
798normalize_doc_attributes = false
799format_strings = false
800format_macro_matchers = false
801format_macro_bodies = true
802skip_macro_invocations = []
803hex_literal_case = "Preserve"
804float_literal_trailing_zero = "Preserve"
805empty_item_single_line = true
806struct_lit_single_line = true
807fn_single_line = false
808where_single_line = false
809imports_indent = "Block"
810imports_layout = "Mixed"
811imports_granularity = "Preserve"
812group_imports = "Preserve"
813reorder_imports = true
814reorder_modules = true
815reorder_impl_items = false
816type_punctuation_density = "Wide"
817space_before_colon = false
818space_after_colon = true
819spaces_around_ranges = false
820binop_separator = "Front"
821remove_nested_parens = true
822combine_control_expr = true
823short_array_element_width_threshold = 10
824overflow_delimited_expr = false
825struct_field_align_threshold = 0
826enum_discrim_align_threshold = 0
827match_arm_blocks = true
828match_arm_leading_pipes = "Never"
829match_arm_indent = true
830force_multiline_blocks = false
831fn_params_layout = "Tall"
832brace_style = "SameLineWhere"
833control_brace_style = "AlwaysSameLine"
834trailing_semicolon = true
835trailing_comma = "Vertical"
836match_block_trailing_comma = false
837blank_lines_upper_bound = 1
838blank_lines_lower_bound = 0
839edition = "2015"
840style_edition = "2015"
841version = "One"
842inline_attribute_width = 0
843format_generated_files = true
844generated_marker_line_search_limit = 5
845merge_derives = true
846use_try_shorthand = false
847use_field_init_shorthand = false
848force_explicit_abi = true
849condense_wildcard_suffixes = false
850color = "Auto"
851required_version = "{}"
852unstable_features = false
853disable_all_formatting = false
854skip_children = false
855show_parse_errors = true
856error_on_line_overflow = false
857error_on_unformatted = false
858ignore = []
859emit_mode = "Files"
860make_backup = false
861"#,
862 env!("CARGO_PKG_VERSION")
863 );
864 let toml = Config::default().all_options().to_toml().unwrap();
865 assert_eq!(&toml, &default_config);
866 }
867
868 #[test]
869 fn test_dump_style_edition_2024_config() {
870 let edition_2024_config = format!(
871 r#"max_width = 100
872hard_tabs = false
873tab_spaces = 4
874newline_style = "Auto"
875indent_style = "Block"
876use_small_heuristics = "Default"
877fn_call_width = 60
878attr_fn_like_width = 70
879struct_lit_width = 18
880struct_variant_width = 35
881array_width = 60
882chain_width = 60
883single_line_if_else_max_width = 50
884single_line_let_else_max_width = 50
885wrap_comments = false
886format_code_in_doc_comments = false
887doc_comment_code_block_width = 100
888doc_comment_code_block_small_heuristics = "Inherit"
889comment_width = 80
890normalize_comments = false
891normalize_doc_attributes = false
892format_strings = false
893format_macro_matchers = false
894format_macro_bodies = true
895skip_macro_invocations = []
896hex_literal_case = "Preserve"
897float_literal_trailing_zero = "Preserve"
898empty_item_single_line = true
899struct_lit_single_line = true
900fn_single_line = false
901where_single_line = false
902imports_indent = "Block"
903imports_layout = "Mixed"
904imports_granularity = "Preserve"
905group_imports = "Preserve"
906reorder_imports = true
907reorder_modules = true
908reorder_impl_items = false
909type_punctuation_density = "Wide"
910space_before_colon = false
911space_after_colon = true
912spaces_around_ranges = false
913binop_separator = "Front"
914remove_nested_parens = true
915combine_control_expr = true
916short_array_element_width_threshold = 10
917overflow_delimited_expr = false
918struct_field_align_threshold = 0
919enum_discrim_align_threshold = 0
920match_arm_blocks = true
921match_arm_leading_pipes = "Never"
922match_arm_indent = true
923force_multiline_blocks = false
924fn_params_layout = "Tall"
925brace_style = "SameLineWhere"
926control_brace_style = "AlwaysSameLine"
927trailing_semicolon = true
928trailing_comma = "Vertical"
929match_block_trailing_comma = false
930blank_lines_upper_bound = 1
931blank_lines_lower_bound = 0
932edition = "2015"
933style_edition = "2024"
934version = "Two"
935inline_attribute_width = 0
936format_generated_files = true
937generated_marker_line_search_limit = 5
938merge_derives = true
939use_try_shorthand = false
940use_field_init_shorthand = false
941force_explicit_abi = true
942condense_wildcard_suffixes = false
943color = "Auto"
944required_version = "{}"
945unstable_features = false
946disable_all_formatting = false
947skip_children = false
948show_parse_errors = true
949error_on_line_overflow = false
950error_on_unformatted = false
951ignore = []
952emit_mode = "Files"
953make_backup = false
954"#,
955 env!("CARGO_PKG_VERSION")
956 );
957 let toml = Config::default_with_style_edition(StyleEdition::Edition2024)
958 .all_options()
959 .to_toml()
960 .unwrap();
961 assert_eq!(&toml, &edition_2024_config);
962 }
963
964 #[test]
965 fn test_editions_2015_2018_2021_identical() {
966 let get_edition_toml = |style_edition: StyleEdition| {
967 Config::default_with_style_edition(style_edition)
968 .all_options()
969 .to_toml()
970 .unwrap()
971 };
972 let edition2015 = get_edition_toml(StyleEdition::Edition2015);
973 let edition2018 = get_edition_toml(StyleEdition::Edition2018);
974 let edition2021 = get_edition_toml(StyleEdition::Edition2021);
975 assert_eq!(edition2015, edition2018);
976 assert_eq!(edition2018, edition2021);
977 }
978
979 #[stable_only_test]
980 #[test]
981 fn test_as_not_nightly_channel() {
982 let mut config = Config::default();
983 assert_eq!(config.was_set().unstable_features(), false);
984 config.set().unstable_features(true);
985 assert_eq!(config.was_set().unstable_features(), false);
986 }
987
988 #[nightly_only_test]
989 #[test]
990 fn test_as_nightly_channel() {
991 let mut config = Config::default();
992 config.set().unstable_features(true);
993 assert_eq!(config.was_set().unstable_features(), false);
996 config.set().unstable_features(true);
997 assert_eq!(config.unstable_features(), true);
998 }
999
1000 #[nightly_only_test]
1001 #[test]
1002 fn test_unstable_from_toml() {
1003 let config =
1004 Config::from_toml("unstable_features = true", Path::new("./rustfmt.toml")).unwrap();
1005 assert_eq!(config.was_set().unstable_features(), true);
1006 assert_eq!(config.unstable_features(), true);
1007 }
1008
1009 #[test]
1010 fn test_set_cli() {
1011 let mut config = Config::default();
1012 assert_eq!(config.was_set().edition(), false);
1013 assert_eq!(config.was_set_cli().edition(), false);
1014 config.set().edition(Edition::Edition2021);
1015 assert_eq!(config.was_set().edition(), false);
1016 assert_eq!(config.was_set_cli().edition(), false);
1017 config.set_cli().edition(Edition::Edition2021);
1018 assert_eq!(config.was_set().edition(), false);
1019 assert_eq!(config.was_set_cli().edition(), true);
1020 assert_eq!(config.was_set_cli().emit_mode(), false);
1021 }
1022
1023 #[cfg(test)]
1024 mod deprecated_option_merge_imports {
1025 use super::*;
1026
1027 #[nightly_only_test]
1028 #[test]
1029 fn test_old_option_set() {
1030 let toml = r#"
1031 unstable_features = true
1032 merge_imports = true
1033 "#;
1034 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1035 assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
1036 }
1037
1038 #[nightly_only_test]
1039 #[test]
1040 fn test_both_set() {
1041 let toml = r#"
1042 unstable_features = true
1043 merge_imports = true
1044 imports_granularity = "Preserve"
1045 "#;
1046 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1047 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
1048 }
1049
1050 #[nightly_only_test]
1051 #[test]
1052 fn test_new_overridden() {
1053 let toml = r#"
1054 unstable_features = true
1055 merge_imports = true
1056 "#;
1057 let mut config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1058 config.override_value("imports_granularity", "Preserve");
1059 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
1060 }
1061
1062 #[nightly_only_test]
1063 #[test]
1064 fn test_old_overridden() {
1065 let toml = r#"
1066 unstable_features = true
1067 imports_granularity = "Module"
1068 "#;
1069 let mut config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1070 config.override_value("merge_imports", "true");
1071 assert_eq!(config.imports_granularity(), ImportGranularity::Module);
1073 }
1074 }
1075
1076 #[cfg(test)]
1077 mod use_small_heuristics {
1078 use super::*;
1079
1080 #[test]
1081 fn test_default_sets_correct_widths() {
1082 let toml = r#"
1083 use_small_heuristics = "Default"
1084 max_width = 200
1085 "#;
1086 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1087 assert_eq!(config.array_width(), 120);
1088 assert_eq!(config.attr_fn_like_width(), 140);
1089 assert_eq!(config.chain_width(), 120);
1090 assert_eq!(config.fn_call_width(), 120);
1091 assert_eq!(config.single_line_if_else_max_width(), 100);
1092 assert_eq!(config.struct_lit_width(), 36);
1093 assert_eq!(config.struct_variant_width(), 70);
1094 }
1095
1096 #[test]
1097 fn test_max_sets_correct_widths() {
1098 let toml = r#"
1099 use_small_heuristics = "Max"
1100 max_width = 120
1101 "#;
1102 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1103 assert_eq!(config.array_width(), 120);
1104 assert_eq!(config.attr_fn_like_width(), 120);
1105 assert_eq!(config.chain_width(), 120);
1106 assert_eq!(config.fn_call_width(), 120);
1107 assert_eq!(config.single_line_if_else_max_width(), 120);
1108 assert_eq!(config.struct_lit_width(), 120);
1109 assert_eq!(config.struct_variant_width(), 120);
1110 }
1111
1112 #[test]
1113 fn test_off_sets_correct_widths() {
1114 let toml = r#"
1115 use_small_heuristics = "Off"
1116 max_width = 100
1117 "#;
1118 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1119 assert_eq!(config.array_width(), usize::MAX);
1120 assert_eq!(config.attr_fn_like_width(), usize::MAX);
1121 assert_eq!(config.chain_width(), usize::MAX);
1122 assert_eq!(config.fn_call_width(), usize::MAX);
1123 assert_eq!(config.single_line_if_else_max_width(), 0);
1124 assert_eq!(config.struct_lit_width(), 0);
1125 assert_eq!(config.struct_variant_width(), 0);
1126 }
1127
1128 #[test]
1129 fn test_override_works_with_default() {
1130 let toml = r#"
1131 use_small_heuristics = "Default"
1132 array_width = 20
1133 attr_fn_like_width = 40
1134 chain_width = 20
1135 fn_call_width = 90
1136 single_line_if_else_max_width = 40
1137 struct_lit_width = 30
1138 struct_variant_width = 34
1139 "#;
1140 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1141 assert_eq!(config.array_width(), 20);
1142 assert_eq!(config.attr_fn_like_width(), 40);
1143 assert_eq!(config.chain_width(), 20);
1144 assert_eq!(config.fn_call_width(), 90);
1145 assert_eq!(config.single_line_if_else_max_width(), 40);
1146 assert_eq!(config.struct_lit_width(), 30);
1147 assert_eq!(config.struct_variant_width(), 34);
1148 }
1149
1150 #[test]
1151 fn test_override_with_max() {
1152 let toml = r#"
1153 use_small_heuristics = "Max"
1154 array_width = 20
1155 attr_fn_like_width = 40
1156 chain_width = 20
1157 fn_call_width = 90
1158 single_line_if_else_max_width = 40
1159 struct_lit_width = 30
1160 struct_variant_width = 34
1161 "#;
1162 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1163 assert_eq!(config.array_width(), 20);
1164 assert_eq!(config.attr_fn_like_width(), 40);
1165 assert_eq!(config.chain_width(), 20);
1166 assert_eq!(config.fn_call_width(), 90);
1167 assert_eq!(config.single_line_if_else_max_width(), 40);
1168 assert_eq!(config.struct_lit_width(), 30);
1169 assert_eq!(config.struct_variant_width(), 34);
1170 }
1171
1172 #[test]
1173 fn test_override_with_off() {
1174 let toml = r#"
1175 use_small_heuristics = "Off"
1176 array_width = 20
1177 attr_fn_like_width = 40
1178 chain_width = 20
1179 fn_call_width = 90
1180 single_line_if_else_max_width = 40
1181 struct_lit_width = 30
1182 struct_variant_width = 34
1183 "#;
1184 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1185 assert_eq!(config.array_width(), 20);
1186 assert_eq!(config.attr_fn_like_width(), 40);
1187 assert_eq!(config.chain_width(), 20);
1188 assert_eq!(config.fn_call_width(), 90);
1189 assert_eq!(config.single_line_if_else_max_width(), 40);
1190 assert_eq!(config.struct_lit_width(), 30);
1191 assert_eq!(config.struct_variant_width(), 34);
1192 }
1193
1194 #[test]
1195 fn test_fn_call_width_config_exceeds_max_width() {
1196 let toml = r#"
1197 max_width = 90
1198 fn_call_width = 95
1199 "#;
1200 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1201 assert_eq!(config.fn_call_width(), 90);
1202 }
1203
1204 #[test]
1205 fn test_attr_fn_like_width_config_exceeds_max_width() {
1206 let toml = r#"
1207 max_width = 80
1208 attr_fn_like_width = 90
1209 "#;
1210 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1211 assert_eq!(config.attr_fn_like_width(), 80);
1212 }
1213
1214 #[test]
1215 fn test_struct_lit_config_exceeds_max_width() {
1216 let toml = r#"
1217 max_width = 78
1218 struct_lit_width = 90
1219 "#;
1220 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1221 assert_eq!(config.struct_lit_width(), 78);
1222 }
1223
1224 #[test]
1225 fn test_struct_variant_width_config_exceeds_max_width() {
1226 let toml = r#"
1227 max_width = 80
1228 struct_variant_width = 90
1229 "#;
1230 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1231 assert_eq!(config.struct_variant_width(), 80);
1232 }
1233
1234 #[test]
1235 fn test_array_width_config_exceeds_max_width() {
1236 let toml = r#"
1237 max_width = 60
1238 array_width = 80
1239 "#;
1240 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1241 assert_eq!(config.array_width(), 60);
1242 }
1243
1244 #[test]
1245 fn test_chain_width_config_exceeds_max_width() {
1246 let toml = r#"
1247 max_width = 80
1248 chain_width = 90
1249 "#;
1250 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1251 assert_eq!(config.chain_width(), 80);
1252 }
1253
1254 #[test]
1255 fn test_single_line_if_else_max_width_config_exceeds_max_width() {
1256 let toml = r#"
1257 max_width = 70
1258 single_line_if_else_max_width = 90
1259 "#;
1260 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1261 assert_eq!(config.single_line_if_else_max_width(), 70);
1262 }
1263
1264 #[test]
1265 fn test_override_fn_call_width_exceeds_max_width() {
1266 let mut config = Config::default();
1267 config.override_value("fn_call_width", "101");
1268 assert_eq!(config.fn_call_width(), 100);
1269 }
1270
1271 #[test]
1272 fn test_override_attr_fn_like_width_exceeds_max_width() {
1273 let mut config = Config::default();
1274 config.override_value("attr_fn_like_width", "101");
1275 assert_eq!(config.attr_fn_like_width(), 100);
1276 }
1277
1278 #[test]
1279 fn test_override_struct_lit_exceeds_max_width() {
1280 let mut config = Config::default();
1281 config.override_value("struct_lit_width", "101");
1282 assert_eq!(config.struct_lit_width(), 100);
1283 }
1284
1285 #[test]
1286 fn test_override_struct_variant_width_exceeds_max_width() {
1287 let mut config = Config::default();
1288 config.override_value("struct_variant_width", "101");
1289 assert_eq!(config.struct_variant_width(), 100);
1290 }
1291
1292 #[test]
1293 fn test_override_array_width_exceeds_max_width() {
1294 let mut config = Config::default();
1295 config.override_value("array_width", "101");
1296 assert_eq!(config.array_width(), 100);
1297 }
1298
1299 #[test]
1300 fn test_override_chain_width_exceeds_max_width() {
1301 let mut config = Config::default();
1302 config.override_value("chain_width", "101");
1303 assert_eq!(config.chain_width(), 100);
1304 }
1305
1306 #[test]
1307 fn test_override_single_line_if_else_max_width_exceeds_max_width() {
1308 let mut config = Config::default();
1309 config.override_value("single_line_if_else_max_width", "101");
1310 assert_eq!(config.single_line_if_else_max_width(), 100);
1311 }
1312 }
1313
1314 #[cfg(test)]
1315 mod partially_unstable_option {
1316 use super::mock::{Config, PartiallyUnstableOption};
1317
1318 #[test]
1320 fn test_override_stable_value() {
1321 let mut config = Config::default();
1322 config.override_value("partially_unstable_option", "V2");
1323 assert_eq!(
1324 config.partially_unstable_option(),
1325 PartiallyUnstableOption::V2
1326 );
1327 }
1328
1329 #[test]
1331 fn test_override_unstable_value() {
1332 let mut config = Config::default();
1333 config.override_value("partially_unstable_option", "V3");
1334 assert_eq!(
1335 config.partially_unstable_option(),
1336 PartiallyUnstableOption::V3
1337 );
1338 }
1339 }
1340
1341 #[test]
1342 fn test_override_skip_macro_invocations() {
1343 let mut config = Config::default();
1344 config.override_value("skip_macro_invocations", r#"["*", "println"]"#);
1345 assert_eq!(
1346 config.skip_macro_invocations(),
1347 MacroSelectors(vec![
1348 MacroSelector::All,
1349 MacroSelector::Name(MacroName::new("println".to_owned()))
1350 ])
1351 );
1352 }
1353
1354 #[cfg(test)]
1355 mod required_version {
1356 use super::*;
1357
1358 #[allow(dead_code)] fn get_current_version() -> semver::Version {
1360 semver::Version::parse(env!("CARGO_PKG_VERSION")).unwrap()
1361 }
1362
1363 #[nightly_only_test]
1364 #[test]
1365 fn test_required_version_default() {
1366 let config = Config::default();
1367 assert!(config.version_meets_requirement());
1368 }
1369
1370 #[nightly_only_test]
1371 #[test]
1372 fn test_current_required_version() {
1373 let toml = format!("required_version=\"{}\"", env!("CARGO_PKG_VERSION"));
1374 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1375
1376 assert!(config.version_meets_requirement());
1377 }
1378
1379 #[nightly_only_test]
1380 #[test]
1381 fn test_required_version_above() {
1382 let toml = "required_version=\"1000.0.0\"";
1383 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1384
1385 assert!(!config.version_meets_requirement());
1386 }
1387
1388 #[nightly_only_test]
1389 #[test]
1390 fn test_required_version_below() {
1391 let versions = vec!["0.0.0", "0.0.1", "0.1.0"];
1392
1393 for version in versions {
1394 let toml = format!("required_version=\"{}\"", version.to_string());
1395 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1396
1397 assert!(!config.version_meets_requirement());
1398 }
1399 }
1400
1401 #[nightly_only_test]
1402 #[test]
1403 fn test_required_version_tilde() {
1404 let toml = format!("required_version=\"~{}\"", env!("CARGO_PKG_VERSION"));
1405 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1406
1407 assert!(config.version_meets_requirement());
1408 }
1409
1410 #[nightly_only_test]
1411 #[test]
1412 fn test_required_version_caret() {
1413 let current_version = get_current_version();
1414
1415 for minor in current_version.minor..0 {
1416 let toml = format!(
1417 "required_version=\"^{}.{}.0\"",
1418 current_version.major.to_string(),
1419 minor.to_string()
1420 );
1421 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1422
1423 assert!(!config.version_meets_requirement());
1424 }
1425 }
1426
1427 #[nightly_only_test]
1428 #[test]
1429 fn test_required_version_greater_than() {
1430 let toml = "required_version=\">1.0.0\"";
1431 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1432
1433 assert!(config.version_meets_requirement());
1434 }
1435
1436 #[nightly_only_test]
1437 #[test]
1438 fn test_required_version_less_than() {
1439 let toml = "required_version=\"<1.0.0\"";
1440 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1441
1442 assert!(!config.version_meets_requirement());
1443 }
1444
1445 #[nightly_only_test]
1446 #[test]
1447 fn test_required_version_range() {
1448 let current_version = get_current_version();
1449
1450 let toml = format!(
1451 "required_version=\">={}.0.0, <{}.0.0\"",
1452 current_version.major,
1453 current_version.major + 1
1454 );
1455 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1456
1457 assert!(config.version_meets_requirement());
1458 }
1459
1460 #[nightly_only_test]
1461 #[test]
1462 fn test_required_version_exact_boundary() {
1463 let toml = format!("required_version=\"{}\"", get_current_version().to_string());
1464 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1465
1466 assert!(config.version_meets_requirement());
1467 }
1468
1469 #[nightly_only_test]
1470 #[test]
1471 fn test_required_version_pre_release() {
1472 let toml = format!(
1473 "required_version=\"^{}-alpha\"",
1474 get_current_version().to_string()
1475 );
1476 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1477
1478 assert!(config.version_meets_requirement());
1479 }
1480
1481 #[nightly_only_test]
1482 #[test]
1483 fn test_required_version_with_build_metadata() {
1484 let toml = format!(
1485 "required_version=\"{}+build.1\"",
1486 get_current_version().to_string()
1487 );
1488
1489 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1490
1491 assert!(config.version_meets_requirement());
1492 }
1493
1494 #[nightly_only_test]
1495 #[test]
1496 fn test_required_version_invalid_specification() {
1497 let toml = "required_version=\"not.a.version\"";
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_complex_range() {
1506 let current_version = get_current_version();
1507
1508 let toml = format!(
1509 "required_version=\">={}.0.0, <{}.0.0, ~{}.{}.0\"",
1510 current_version.major,
1511 current_version.major + 1,
1512 current_version.major,
1513 current_version.minor
1514 );
1515 let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap();
1516
1517 assert!(config.version_meets_requirement());
1518 }
1519
1520 #[nightly_only_test]
1521 #[test]
1522 fn test_required_version_wildcard_major() {
1523 let toml = "required_version=\"1.x\"";
1524 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1525
1526 assert!(config.version_meets_requirement());
1527 }
1528
1529 #[nightly_only_test]
1530 #[test]
1531 fn test_required_version_wildcard_any() {
1532 let toml = "required_version=\"*\"";
1533 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1534
1535 assert!(config.version_meets_requirement());
1536 }
1537
1538 #[nightly_only_test]
1539 #[test]
1540 fn test_required_version_major_version_zero() {
1541 let toml = "required_version=\"0.1.0\"";
1542 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1543
1544 assert!(!config.version_meets_requirement());
1545 }
1546
1547 #[nightly_only_test]
1548 #[test]
1549 fn test_required_version_future_major_version() {
1550 let toml = "required_version=\"3.0.0\"";
1551 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1552
1553 assert!(!config.version_meets_requirement());
1554 }
1555
1556 #[nightly_only_test]
1557 #[test]
1558 fn test_required_version_fail_different_operator() {
1559 let toml = "required_version=\"!=1.0.0\"";
1561 let config = Config::from_toml(toml, Path::new("./rustfmt.toml")).unwrap();
1562
1563 assert!(!config.version_meets_requirement());
1564 }
1565 }
1566
1567 #[cfg(test)]
1568 mod check_semver_version {
1569 use super::*;
1570
1571 #[test]
1572 fn test_exact_version_match() {
1573 assert!(check_semver_version("1.0.0", "1.0.0"));
1574 assert!(!check_semver_version("1.0.0", "1.1.0"));
1575 assert!(!check_semver_version("1.0.0", "1.0.1"));
1576 assert!(!check_semver_version("1.0.0", "2.1.0"));
1577 assert!(!check_semver_version("1.0.0", "0.1.0"));
1578 assert!(!check_semver_version("1.0.0", "0.0.1"));
1579 }
1580
1581 #[test]
1582 fn test_version_mismatch() {
1583 assert!(!check_semver_version("2.0.0", "1.0.0"));
1584 }
1585
1586 #[test]
1587 fn test_patch_version_greater() {
1588 assert!(check_semver_version("^1.0.0", "1.0.1"));
1589 }
1590
1591 #[test]
1592 fn test_minor_version_greater() {
1593 assert!(check_semver_version("^1.0.0", "1.1.0"));
1594 }
1595
1596 #[test]
1597 fn test_major_version_less() {
1598 assert!(!check_semver_version("1.0.0", "0.9.0"));
1599 }
1600
1601 #[test]
1602 fn test_prerelease_less_than_release() {
1603 assert!(!check_semver_version("1.0.0", "1.0.0-alpha"));
1604 }
1605
1606 #[test]
1607 fn test_prerelease_version_specific_match() {
1608 assert!(check_semver_version("1.0.0-alpha", "1.0.0-alpha"));
1609 }
1610
1611 #[test]
1612 fn test_build_metadata_ignored() {
1613 assert!(check_semver_version("1.0.0", "1.0.0+build.1"));
1614 }
1615
1616 #[test]
1617 fn test_greater_than_requirement() {
1618 assert!(check_semver_version(">1.0.0", "1.1.0"));
1619 }
1620
1621 #[test]
1622 fn test_less_than_requirement_fails_when_greater() {
1623 assert!(!check_semver_version("<1.0.0", "1.1.0"));
1624 }
1625
1626 #[test]
1627 fn test_caret_requirement_matches_minor_update() {
1628 assert!(check_semver_version("^1.1.0", "1.2.0"));
1629 }
1630
1631 #[test]
1632 fn test_tilde_requirement_matches_patch_update() {
1633 assert!(check_semver_version("~1.0.0", "1.0.1"));
1634 }
1635
1636 #[test]
1637 fn test_range_requirement_inclusive() {
1638 assert!(check_semver_version(">=1.0.0, <2.0.0", "1.5.0"));
1639 }
1640
1641 #[test]
1642 fn test_pre_release_specific_match() {
1643 assert!(check_semver_version("1.0.0-alpha.1", "1.0.0-alpha.1"));
1644 }
1645
1646 #[test]
1647 fn test_pre_release_non_match_when_requiring_release() {
1648 assert!(!check_semver_version("1.0.0", "1.0.0-alpha.1"));
1649 }
1650
1651 #[test]
1654 fn test_invalid_or() {
1655 assert!(!check_semver_version("1.0.0 || 2.0.0", "1.0.0"));
1656 assert!(!check_semver_version("1.0.0 || 2.0.0", "2.0.0"));
1657 assert!(!check_semver_version("1.0.0 || 2.0.0", "3.0.0"));
1658 }
1659
1660 #[test]
1661 fn test_wildcard_match_minor() {
1662 assert!(check_semver_version("1.*", "1.1.0"));
1663 assert!(check_semver_version("1.*, <2.0.0", "1.1.0"));
1664 }
1665
1666 #[test]
1667 fn test_wildcard_mismatch() {
1668 assert!(!check_semver_version("1.*, <2.0.0", "2.1.0"));
1669 assert!(!check_semver_version("1.*, <2.0.0", "2.0.0"));
1670 assert!(!check_semver_version("1.*, <2.*", "2.1.0"));
1671 assert!(!check_semver_version("1.*, <2.*", "2.0.0"));
1672
1673 assert!(!check_semver_version("1.*, >2.0.0", "1.1.0"));
1674 assert!(!check_semver_version("1.*, >2.0.0", "1.0.0"));
1675 assert!(!check_semver_version("1.*, >2.*", "1.1.0"));
1676 assert!(!check_semver_version("1.*, >2.*", "1.0.0"));
1677
1678 assert!(!check_semver_version("<1.5.0, >1.10.*", "1.6.0"));
1679 }
1680
1681 #[test]
1682 fn test_wildcard_match_major() {
1683 assert!(check_semver_version("2.*", "2.0.0"));
1684 }
1685
1686 #[test]
1687 fn test_wildcard_match_patch() {
1688 assert!(check_semver_version("1.0.*", "1.0.1"));
1689 }
1690
1691 #[test]
1692 fn test_invalid_inputs() {
1693 assert!(!check_semver_version("not.a.requirement", "1.0.0"));
1694 assert!(!check_semver_version("1.0.0", "not.a.version"));
1695 }
1696
1697 #[test]
1698 fn test_version_with_pre_release_and_build() {
1699 assert!(check_semver_version("1.0.0-alpha", "1.0.0-alpha+001"));
1700 }
1701
1702 #[test]
1704 fn test_pre_release_numeric_vs_alphanumeric() {
1705 assert!(!check_semver_version("^1.0.0-alpha.beta", "1.0.0-alpha.1"));
1706 assert!(check_semver_version("^1.0.0-alpha.1", "1.0.0-alpha.beta"));
1707 }
1708
1709 #[test]
1711 fn test_wildcard_any() {
1712 assert!(check_semver_version("*", "1.0.0"));
1713 assert!(check_semver_version("*", "1.0.0+build"));
1714 }
1715
1716 #[test]
1718 fn test_pre_release_lexicographic_ordering() {
1719 assert!(check_semver_version(
1720 "^1.0.0-alpha.alpha",
1721 "1.0.0-alpha.beta",
1722 ));
1723 assert!(!check_semver_version(
1724 "^1.0.0-alpha.beta",
1725 "1.0.0-alpha.alpha",
1726 ));
1727 }
1728
1729 #[test]
1731 fn test_wildcard_any_with_range() {
1732 assert!(!check_semver_version("*, <2.0.0", "1.0.0"));
1733 assert!(!check_semver_version("*, 1.0.0", "1.5.0"));
1734 }
1735 }
1736}