2 use std::default::Default;
4 use std::io::{Error, ErrorKind, Read};
5 use std::path::{Path, PathBuf};
11 use crate::config::config_type::ConfigType;
12 #[allow(unreachable_pub)]
13 pub use crate::config::file_lines::{FileLines, FileName, Range};
14 #[allow(unreachable_pub)]
15 pub use crate::config::lists::*;
16 #[allow(unreachable_pub)]
17 pub use crate::config::options::*;
20 pub(crate) mod config_type;
22 pub(crate) mod options;
24 pub(crate) mod file_lines;
25 pub(crate) mod license;
28 // This macro defines configuration options used in rustfmt. Each option
29 // is defined as follows:
31 // `name: value type, default value, is stable, description;`
34 max_width: usize, 100, true, "Maximum width of each line";
35 hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment";
36 tab_spaces: usize, 4, true, "Number of spaces per tab";
37 newline_style: NewlineStyle, NewlineStyle::Auto, true, "Unix or Windows line endings";
38 indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items";
41 use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different \
42 formatting for items and expressions if they satisfy a heuristic notion of 'small'";
43 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
44 "'small' heuristic values";
45 fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \
46 falling back to vertical formatting.";
47 attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \
48 attributes before falling back to vertical formatting.";
49 struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \
50 falling back to vertical formatting.";
51 struct_variant_width: usize, 35, true, "Maximum width in the body of a struct variant before \
52 falling back to vertical formatting.";
53 array_width: usize, 60, true, "Maximum width of an array literal before falling \
54 back to vertical formatting.";
55 chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line.";
56 single_line_if_else_max_width: usize, 50, true, "Maximum line length for single line if-else \
57 expressions. A value of zero means always break if-else expressions.";
59 // Comments. macros, and strings
60 wrap_comments: bool, false, false, "Break comments to fit on the line";
61 format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments.";
62 comment_width: usize, 80, false,
63 "Maximum length of comments. No effect unless wrap_comments = true";
64 normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
65 normalize_doc_attributes: bool, false, false, "Normalize doc attributes as doc comments";
66 license_template_path: String, String::default(), false,
67 "Beginning of file must match license template";
68 format_strings: bool, false, false, "Format string literals where necessary";
69 format_macro_matchers: bool, false, false,
70 "Format the metavariable matching patterns in macros";
71 format_macro_bodies: bool, true, false, "Format the bodies of macros";
73 // Single line expressions and items
74 empty_item_single_line: bool, true, false,
75 "Put empty-body functions and impls on a single line";
76 struct_lit_single_line: bool, true, false,
77 "Put small struct literals on a single line";
78 fn_single_line: bool, false, false, "Put single-expression functions on a single line";
79 where_single_line: bool, false, false, "Force where-clauses to be on a single line";
82 imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports";
83 imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
84 imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
85 "Merge or split imports to the provided granularity";
86 group_imports: GroupImportsTactic, GroupImportsTactic::Preserve, false,
87 "Controls the strategy for how imports are grouped together";
88 merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
91 reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically";
92 reorder_modules: bool, true, true, "Reorder module statements alphabetically in group";
93 reorder_impl_items: bool, false, false, "Reorder impl items";
95 // Spaces around punctuation
96 type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
97 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
98 space_before_colon: bool, false, false, "Leave a space before the colon";
99 space_after_colon: bool, true, false, "Leave a space after the colon";
100 spaces_around_ranges: bool, false, false, "Put spaces around the .. and ..= range operators";
101 binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
102 "Where to put a binary operator when a binary expression goes multiline";
105 remove_nested_parens: bool, true, true, "Remove nested parens";
106 combine_control_expr: bool, true, false, "Combine control expressions with function calls";
107 overflow_delimited_expr: bool, false, false,
108 "Allow trailing bracket/brace delimited expressions to overflow";
109 struct_field_align_threshold: usize, 0, false,
110 "Align struct fields if their diffs fits within threshold";
111 enum_discrim_align_threshold: usize, 0, false,
112 "Align enum variants discrims, if their diffs fit within threshold";
113 match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
114 the same line with the pattern of arms";
115 match_arm_leading_pipes: MatchArmLeadingPipe, MatchArmLeadingPipe::Never, true,
116 "Determines whether leading pipes are emitted on match arms";
117 force_multiline_blocks: bool, false, false,
118 "Force multiline closure bodies and match arms to be wrapped in a block";
119 fn_args_layout: Density, Density::Tall, true,
120 "Control the layout of arguments in a function";
121 brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
122 control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
123 "Brace style for control flow constructs";
124 trailing_semicolon: bool, true, false,
125 "Add trailing semicolon after break, continue and return";
126 trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
127 "How to handle trailing commas for lists";
128 match_block_trailing_comma: bool, false, false,
129 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
130 blank_lines_upper_bound: usize, 1, false,
131 "Maximum number of blank lines which can be put between items";
132 blank_lines_lower_bound: usize, 0, false,
133 "Minimum number of blank lines which must be put between items";
134 edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)";
135 version: Version, Version::One, false, "Version of formatting rules";
136 inline_attribute_width: usize, 0, false,
137 "Write an item and its attribute on the same line \
138 if their combined width is below a threshold";
140 // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
141 merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
142 use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand";
143 use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible";
144 force_explicit_abi: bool, true, true, "Always print the abi for extern items";
145 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
148 // Control options (changes the operation of rustfmt, rather than the formatting)
149 color: Color, Color::Auto, false,
150 "What Color option to use when none is supplied: Always, Never, Auto";
151 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
152 "Require a specific version of rustfmt";
153 unstable_features: bool, false, false,
154 "Enables unstable features. Only available on nightly channel";
155 disable_all_formatting: bool, false, false, "Don't reformat anything";
156 skip_children: bool, false, false, "Don't reformat out of line modules";
157 hide_parse_errors: bool, false, false, "Hide errors from the parser";
158 error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
159 error_on_unformatted: bool, false, false,
160 "Error if unable to get comments or string literals within max_width, \
161 or they are left with trailing whitespaces";
162 report_todo: ReportTactic, ReportTactic::Never, false,
163 "Report all, none or unnumbered occurrences of TODO in source file comments";
164 report_fixme: ReportTactic, ReportTactic::Never, false,
165 "Report all, none or unnumbered occurrences of FIXME in source file comments";
166 ignore: IgnoreList, IgnoreList::default(), false,
167 "Skip formatting the specified files and directories";
170 verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user";
171 file_lines: FileLines, FileLines::all(), false,
172 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
173 via the --file-lines option";
174 emit_mode: EmitMode, EmitMode::Files, false,
175 "What emit Mode to use when none is supplied";
176 make_backup: bool, false, false, "Backup changed files";
177 print_misformatted_file_names: bool, false, true,
178 "Prints the names of mismatched files that were formatted. Prints the names of \
179 files that would be formated when used with `--check` mode. ";
182 #[derive(Error, Debug)]
183 #[error("Could not output config: {0}")]
184 pub struct ToTomlError(toml::ser::Error);
187 pub fn to_toml(&self) -> Result<String, ToTomlError> {
188 // Non-user-facing options can't be specified in TOML
189 let mut cloned = self.clone();
190 cloned.file_lines = None;
191 cloned.verbose = None;
192 cloned.width_heuristics = None;
193 cloned.print_misformatted_file_names = None;
194 cloned.merge_imports = None;
196 ::toml::to_string(&cloned).map_err(ToTomlError)
201 pub(crate) fn version_meets_requirement(&self) -> bool {
202 if self.was_set().required_version() {
203 let version = env!("CARGO_PKG_VERSION");
204 let required_version = self.required_version();
205 if version != required_version {
207 "Error: rustfmt version ({}) doesn't match the required version ({})",
208 version, required_version,
217 /// Constructs a `Config` from the toml file specified at `file_path`.
219 /// This method only looks at the provided path, for a method that
220 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
222 /// Returns a `Config` if the config could be read and parsed from
223 /// the file, otherwise errors.
224 pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
225 let mut file = File::open(&file_path)?;
226 let mut toml = String::new();
227 file.read_to_string(&mut toml)?;
228 Config::from_toml(&toml, file_path.parent().unwrap())
229 .map_err(|err| Error::new(ErrorKind::InvalidData, err))
232 /// Resolves the config for input in `dir`.
234 /// Searches for `rustfmt.toml` beginning with `dir`, and
235 /// recursively checking parents of `dir` if no config file is found.
236 /// If no config file exists in `dir` or in any parent, a
237 /// default `Config` will be returned (and the returned path will be empty).
239 /// Returns the `Config` to use, and the path of the project file if there was
241 pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
242 /// Try to find a project file in the given directory and its parents.
243 /// Returns the path of a the nearest project file if one exists,
244 /// or `None` if no project file was found.
245 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
246 let mut current = if dir.is_relative() {
247 env::current_dir()?.join(dir)
252 current = fs::canonicalize(current)?;
255 match get_toml_path(¤t) {
256 Ok(Some(path)) => return Ok(Some(path)),
257 Err(e) => return Err(e),
261 // If the current directory has no parent, we're done searching.
267 // If nothing was found, check in the home directory.
268 if let Some(home_dir) = dirs::home_dir() {
269 if let Some(path) = get_toml_path(&home_dir)? {
270 return Ok(Some(path));
274 // If none was found ther either, check in the user's configuration directory.
275 if let Some(mut config_dir) = dirs::config_dir() {
276 config_dir.push("rustfmt");
277 if let Some(path) = get_toml_path(&config_dir)? {
278 return Ok(Some(path));
285 match resolve_project_file(dir)? {
286 None => Ok((Config::default(), None)),
287 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
291 pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
292 let parsed: ::toml::Value = toml
294 .map_err(|e| format!("Could not parse TOML: {}", e))?;
295 let mut err = String::new();
298 .ok_or_else(|| String::from("Parsed config was not table"))?;
299 for key in table.keys() {
300 if !Config::is_valid_name(key) {
301 let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
305 match parsed.try_into() {
306 Ok(parsed_config) => {
310 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
313 err.push_str("Error: Decoding config file failed:\n");
314 err.push_str(format!("{}\n", e).as_str());
315 err.push_str("Please check your config file.");
322 /// Loads a config by checking the client-supplied options and if appropriate, the
323 /// file system (including searching the file system for overrides).
324 pub fn load_config<O: CliOptions>(
325 file_path: Option<&Path>,
327 ) -> Result<(Config, Option<PathBuf>), Error> {
328 let over_ride = match options {
329 Some(ref opts) => config_path(opts)?,
333 let result = if let Some(over_ride) = over_ride {
334 Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
335 } else if let Some(file_path) = file_path {
336 Config::from_resolved_toml_path(file_path)
338 Ok((Config::default(), None))
341 result.map(|(mut c, p)| {
342 if let Some(options) = options {
343 options.apply_to(&mut c);
349 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
351 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
352 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
353 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
354 for config_file_name in &CONFIG_FILE_NAMES {
355 let config_file = dir.join(config_file_name);
356 match fs::metadata(&config_file) {
357 // Only return if it's a file to handle the unlikely situation of a directory named
359 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
360 // Return the error if it's something other than `NotFound`; otherwise we didn't
361 // find the project file yet, and continue searching.
363 if e.kind() != ErrorKind::NotFound {
373 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
374 let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
378 "Error: unable to find a config file for the given path: `{}`",
384 // Read the config_path and convert to parent dir if a file is provided.
385 // If a config file cannot be found from the given path, return error.
386 match options.config_path() {
387 Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
388 Some(path) if path.is_dir() => {
389 let config_file_path = get_toml_path(path)?;
390 if config_file_path.is_some() {
393 config_path_not_found(path.to_str().unwrap())
396 path => Ok(path.map(ToOwned::to_owned)),
410 // Options that are used by the generated functions
411 max_width: usize, 100, true, "Maximum width of each line";
412 license_template_path: String, String::default(), false,
413 "Beginning of file must match license template";
414 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
415 "Require a specific version of rustfmt.";
416 ignore: IgnoreList, IgnoreList::default(), false,
417 "Skip formatting the specified files and directories.";
418 verbose: Verbosity, Verbosity::Normal, false,
419 "How much to information to emit to the user";
420 file_lines: FileLines, FileLines::all(), false,
421 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
422 via the --file-lines option";
424 // merge_imports deprecation
425 imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
427 merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
430 use_small_heuristics: Heuristics, Heuristics::Default, true,
431 "Whether to use different formatting for items and \
432 expressions if they satisfy a heuristic notion of 'small'.";
433 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
434 "'small' heuristic values";
436 fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \
437 falling back to vertical formatting.";
438 attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \
439 attributes before falling back to vertical formatting.";
440 struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \
441 falling back to vertical formatting.";
442 struct_variant_width: usize, 35, true, "Maximum width in the body of a struct \
443 variant before falling back to vertical formatting.";
444 array_width: usize, 60, true, "Maximum width of an array literal before falling \
445 back to vertical formatting.";
446 chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line.";
447 single_line_if_else_max_width: usize, 50, true, "Maximum line length for single \
448 line if-else expressions. A value of zero means always break if-else expressions.";
450 // Options that are used by the tests
451 stable_option: bool, false, true, "A stable option";
452 unstable_option: bool, false, false, "An unstable option";
457 fn test_config_set() {
458 let mut config = Config::default();
459 config.set().verbose(Verbosity::Quiet);
460 assert_eq!(config.verbose(), Verbosity::Quiet);
461 config.set().verbose(Verbosity::Normal);
462 assert_eq!(config.verbose(), Verbosity::Normal);
466 fn test_config_used_to_toml() {
467 let config = Config::default();
469 let merge_derives = config.merge_derives();
470 let skip_children = config.skip_children();
472 let used_options = config.used_options();
473 let toml = used_options.to_toml().unwrap();
477 "merge_derives = {}\nskip_children = {}\n",
478 merge_derives, skip_children,
485 let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
487 assert_eq!(config.was_set().hard_tabs(), true);
488 assert_eq!(config.was_set().verbose(), false);
492 fn test_print_docs_exclude_unstable() {
493 use self::mock::Config;
495 let mut output = Vec::new();
496 Config::print_docs(&mut output, false);
498 let s = str::from_utf8(&output).unwrap();
500 assert_eq!(s.contains("stable_option"), true);
501 assert_eq!(s.contains("unstable_option"), false);
502 assert_eq!(s.contains("(unstable)"), false);
506 fn test_print_docs_include_unstable() {
507 use self::mock::Config;
509 let mut output = Vec::new();
510 Config::print_docs(&mut output, true);
512 let s = str::from_utf8(&output).unwrap();
513 assert_eq!(s.contains("stable_option"), true);
514 assert_eq!(s.contains("unstable_option"), true);
515 assert_eq!(s.contains("(unstable)"), true);
519 fn test_empty_string_license_template_path() {
520 let toml = r#"license_template_path = """#;
521 let config = Config::from_toml(toml, Path::new("")).unwrap();
522 assert!(config.license_template.is_none());
526 fn test_valid_license_template_path() {
527 if !crate::is_nightly_channel!() {
530 let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
531 let config = Config::from_toml(toml, Path::new("")).unwrap();
532 assert!(config.license_template.is_some());
536 fn test_override_existing_license_with_no_license() {
537 if !crate::is_nightly_channel!() {
540 let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
541 let mut config = Config::from_toml(toml, Path::new("")).unwrap();
542 assert!(config.license_template.is_some());
543 config.override_value("license_template_path", "");
544 assert!(config.license_template.is_none());
548 fn test_dump_default_config() {
549 let default_config = format!(
553 newline_style = "Auto"
554 indent_style = "Block"
555 use_small_heuristics = "Default"
557 attr_fn_like_width = 70
558 struct_lit_width = 18
559 struct_variant_width = 35
562 single_line_if_else_max_width = 50
563 wrap_comments = false
564 format_code_in_doc_comments = false
566 normalize_comments = false
567 normalize_doc_attributes = false
568 license_template_path = ""
569 format_strings = false
570 format_macro_matchers = false
571 format_macro_bodies = true
572 empty_item_single_line = true
573 struct_lit_single_line = true
574 fn_single_line = false
575 where_single_line = false
576 imports_indent = "Block"
577 imports_layout = "Mixed"
578 imports_granularity = "Preserve"
579 group_imports = "Preserve"
580 reorder_imports = true
581 reorder_modules = true
582 reorder_impl_items = false
583 type_punctuation_density = "Wide"
584 space_before_colon = false
585 space_after_colon = true
586 spaces_around_ranges = false
587 binop_separator = "Front"
588 remove_nested_parens = true
589 combine_control_expr = true
590 overflow_delimited_expr = false
591 struct_field_align_threshold = 0
592 enum_discrim_align_threshold = 0
593 match_arm_blocks = true
594 match_arm_leading_pipes = "Never"
595 force_multiline_blocks = false
596 fn_args_layout = "Tall"
597 brace_style = "SameLineWhere"
598 control_brace_style = "AlwaysSameLine"
599 trailing_semicolon = true
600 trailing_comma = "Vertical"
601 match_block_trailing_comma = false
602 blank_lines_upper_bound = 1
603 blank_lines_lower_bound = 0
606 inline_attribute_width = 0
608 use_try_shorthand = false
609 use_field_init_shorthand = false
610 force_explicit_abi = true
611 condense_wildcard_suffixes = false
613 required_version = "{}"
614 unstable_features = false
615 disable_all_formatting = false
616 skip_children = false
617 hide_parse_errors = false
618 error_on_line_overflow = false
619 error_on_unformatted = false
620 report_todo = "Never"
621 report_fixme = "Never"
626 env!("CARGO_PKG_VERSION")
628 let toml = Config::default().all_options().to_toml().unwrap();
629 assert_eq!(&toml, &default_config);
632 // FIXME(#2183): these tests cannot be run in parallel because they use env vars.
634 // fn test_as_not_nightly_channel() {
635 // let mut config = Config::default();
636 // assert_eq!(config.was_set().unstable_features(), false);
637 // config.set().unstable_features(true);
638 // assert_eq!(config.was_set().unstable_features(), false);
642 // fn test_as_nightly_channel() {
643 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
644 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
645 // let mut config = Config::default();
646 // config.set().unstable_features(true);
647 // assert_eq!(config.was_set().unstable_features(), false);
648 // config.set().unstable_features(true);
649 // assert_eq!(config.unstable_features(), true);
650 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
654 // fn test_unstable_from_toml() {
655 // let mut config = Config::from_toml("unstable_features = true").unwrap();
656 // assert_eq!(config.was_set().unstable_features(), false);
657 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
658 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
659 // config = Config::from_toml("unstable_features = true").unwrap();
660 // assert_eq!(config.was_set().unstable_features(), true);
661 // assert_eq!(config.unstable_features(), true);
662 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
666 mod deprecated_option_merge_imports {
670 fn test_old_option_set() {
671 if !crate::is_nightly_channel!() {
675 unstable_features = true
678 let config = Config::from_toml(toml, Path::new("")).unwrap();
679 assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
684 if !crate::is_nightly_channel!() {
688 unstable_features = true
690 imports_granularity = "Preserve"
692 let config = Config::from_toml(toml, Path::new("")).unwrap();
693 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
697 fn test_new_overridden() {
698 if !crate::is_nightly_channel!() {
702 unstable_features = true
705 let mut config = Config::from_toml(toml, Path::new("")).unwrap();
706 config.override_value("imports_granularity", "Preserve");
707 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
711 fn test_old_overridden() {
712 if !crate::is_nightly_channel!() {
716 unstable_features = true
717 imports_granularity = "Module"
719 let mut config = Config::from_toml(toml, Path::new("")).unwrap();
720 config.override_value("merge_imports", "true");
721 // no effect: the new option always takes precedence
722 assert_eq!(config.imports_granularity(), ImportGranularity::Module);
727 mod use_small_heuristics {
731 fn test_default_sets_correct_widths() {
733 use_small_heuristics = "Default"
736 let config = Config::from_toml(toml, Path::new("")).unwrap();
737 assert_eq!(config.array_width(), 120);
738 assert_eq!(config.attr_fn_like_width(), 140);
739 assert_eq!(config.chain_width(), 120);
740 assert_eq!(config.fn_call_width(), 120);
741 assert_eq!(config.single_line_if_else_max_width(), 100);
742 assert_eq!(config.struct_lit_width(), 36);
743 assert_eq!(config.struct_variant_width(), 70);
747 fn test_max_sets_correct_widths() {
749 use_small_heuristics = "Max"
752 let config = Config::from_toml(toml, Path::new("")).unwrap();
753 assert_eq!(config.array_width(), 120);
754 assert_eq!(config.attr_fn_like_width(), 120);
755 assert_eq!(config.chain_width(), 120);
756 assert_eq!(config.fn_call_width(), 120);
757 assert_eq!(config.single_line_if_else_max_width(), 120);
758 assert_eq!(config.struct_lit_width(), 120);
759 assert_eq!(config.struct_variant_width(), 120);
763 fn test_off_sets_correct_widths() {
765 use_small_heuristics = "Off"
768 let config = Config::from_toml(toml, Path::new("")).unwrap();
769 assert_eq!(config.array_width(), usize::max_value());
770 assert_eq!(config.attr_fn_like_width(), usize::max_value());
771 assert_eq!(config.chain_width(), usize::max_value());
772 assert_eq!(config.fn_call_width(), usize::max_value());
773 assert_eq!(config.single_line_if_else_max_width(), 0);
774 assert_eq!(config.struct_lit_width(), 0);
775 assert_eq!(config.struct_variant_width(), 0);
779 fn test_override_works_with_default() {
781 use_small_heuristics = "Default"
783 attr_fn_like_width = 40
786 single_line_if_else_max_width = 40
787 struct_lit_width = 30
788 struct_variant_width = 34
790 let config = Config::from_toml(toml, Path::new("")).unwrap();
791 assert_eq!(config.array_width(), 20);
792 assert_eq!(config.attr_fn_like_width(), 40);
793 assert_eq!(config.chain_width(), 20);
794 assert_eq!(config.fn_call_width(), 90);
795 assert_eq!(config.single_line_if_else_max_width(), 40);
796 assert_eq!(config.struct_lit_width(), 30);
797 assert_eq!(config.struct_variant_width(), 34);
801 fn test_override_with_max() {
803 use_small_heuristics = "Max"
805 attr_fn_like_width = 40
808 single_line_if_else_max_width = 40
809 struct_lit_width = 30
810 struct_variant_width = 34
812 let config = Config::from_toml(toml, Path::new("")).unwrap();
813 assert_eq!(config.array_width(), 20);
814 assert_eq!(config.attr_fn_like_width(), 40);
815 assert_eq!(config.chain_width(), 20);
816 assert_eq!(config.fn_call_width(), 90);
817 assert_eq!(config.single_line_if_else_max_width(), 40);
818 assert_eq!(config.struct_lit_width(), 30);
819 assert_eq!(config.struct_variant_width(), 34);
823 fn test_override_with_off() {
825 use_small_heuristics = "Off"
827 attr_fn_like_width = 40
830 single_line_if_else_max_width = 40
831 struct_lit_width = 30
832 struct_variant_width = 34
834 let config = Config::from_toml(toml, Path::new("")).unwrap();
835 assert_eq!(config.array_width(), 20);
836 assert_eq!(config.attr_fn_like_width(), 40);
837 assert_eq!(config.chain_width(), 20);
838 assert_eq!(config.fn_call_width(), 90);
839 assert_eq!(config.single_line_if_else_max_width(), 40);
840 assert_eq!(config.struct_lit_width(), 30);
841 assert_eq!(config.struct_variant_width(), 34);
845 #[should_panic(expected = "`fn_call_width` cannot have a value that exceeds `max_width")]
846 fn test_panics_when_fn_call_width_config_exceeds_max_width() {
851 Config::from_toml(toml, Path::new("")).unwrap();
856 expected = "`attr_fn_like_width` cannot have a value that exceeds `max_width"
858 fn test_panics_when_attr_fn_like_width_config_exceeds_max_width() {
861 attr_fn_like_width = 90
863 Config::from_toml(toml, Path::new("")).unwrap();
867 #[should_panic(expected = "`struct_lit_width` cannot have a value that exceeds `max_width")]
868 fn test_panics_when_struct_lit_config_exceeds_max_width() {
871 struct_lit_width = 90
873 Config::from_toml(toml, Path::new("")).unwrap();
878 expected = "`struct_variant_width` cannot have a value that exceeds `max_width"
880 fn test_panics_when_struct_variant_width_config_exceeds_max_width() {
883 struct_variant_width = 90
885 Config::from_toml(toml, Path::new("")).unwrap();
889 #[should_panic(expected = "`array_width` cannot have a value that exceeds `max_width")]
890 fn test_panics_when_array_width_config_exceeds_max_width() {
895 Config::from_toml(toml, Path::new("")).unwrap();
899 #[should_panic(expected = "`chain_width` cannot have a value that exceeds `max_width")]
900 fn test_panics_when_chain_width_config_exceeds_max_width() {
905 Config::from_toml(toml, Path::new("")).unwrap();
910 expected = "`single_line_if_else_max_width` cannot have a value that exceeds `max_width"
912 fn test_panics_when_single_line_if_else_max_width_config_exceeds_max_width() {
915 single_line_if_else_max_width = 90
917 Config::from_toml(toml, Path::new("")).unwrap();
921 #[should_panic(expected = "`fn_call_width` cannot have a value that exceeds `max_width")]
922 fn test_panics_when_fn_call_width_override_exceeds_max_width() {
923 let mut config = Config::default();
924 config.override_value("fn_call_width", "101");
929 expected = "`attr_fn_like_width` cannot have a value that exceeds `max_width"
931 fn test_panics_when_attr_fn_like_width_override_exceeds_max_width() {
932 let mut config = Config::default();
933 config.override_value("attr_fn_like_width", "101");
937 #[should_panic(expected = "`struct_lit_width` cannot have a value that exceeds `max_width")]
938 fn test_panics_when_struct_lit_override_exceeds_max_width() {
939 let mut config = Config::default();
940 config.override_value("struct_lit_width", "101");
945 expected = "`struct_variant_width` cannot have a value that exceeds `max_width"
947 fn test_panics_when_struct_variant_width_override_exceeds_max_width() {
948 let mut config = Config::default();
949 config.override_value("struct_variant_width", "101");
953 #[should_panic(expected = "`array_width` cannot have a value that exceeds `max_width")]
954 fn test_panics_when_array_width_override_exceeds_max_width() {
955 let mut config = Config::default();
956 config.override_value("array_width", "101");
960 #[should_panic(expected = "`chain_width` cannot have a value that exceeds `max_width")]
961 fn test_panics_when_chain_width_override_exceeds_max_width() {
962 let mut config = Config::default();
963 config.override_value("chain_width", "101");
968 expected = "`single_line_if_else_max_width` cannot have a value that exceeds `max_width"
970 fn test_panics_when_single_line_if_else_max_width_override_exceeds_max_width() {
971 let mut config = Config::default();
972 config.override_value("single_line_if_else_max_width", "101");