2 use std::default::Default;
4 use std::io::{Error, ErrorKind, Read};
5 use std::path::{Path, PathBuf};
10 use crate::config::config_type::ConfigType;
11 #[allow(unreachable_pub)]
12 pub use crate::config::file_lines::{FileLines, FileName, Range};
13 #[allow(unreachable_pub)]
14 pub use crate::config::lists::*;
15 #[allow(unreachable_pub)]
16 pub use crate::config::options::*;
19 pub(crate) mod config_type;
21 pub(crate) mod options;
23 pub(crate) mod file_lines;
26 // This macro defines configuration options used in rustfmt. Each option
27 // is defined as follows:
29 // `name: value type, default value, is stable, description;`
32 max_width: usize, 100, true, "Maximum width of each line";
33 hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment";
34 tab_spaces: usize, 4, true, "Number of spaces per tab";
35 newline_style: NewlineStyle, NewlineStyle::Auto, true, "Unix or Windows line endings";
36 indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items";
39 use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different \
40 formatting for items and expressions if they satisfy a heuristic notion of 'small'";
41 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
42 "'small' heuristic values";
43 fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \
44 falling back to vertical formatting.";
45 attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \
46 attributes before falling back to vertical formatting.";
47 struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \
48 falling back to vertical formatting.";
49 struct_variant_width: usize, 35, true, "Maximum width in the body of a struct variant before \
50 falling back to vertical formatting.";
51 array_width: usize, 60, true, "Maximum width of an array literal before falling \
52 back to vertical formatting.";
53 chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line.";
54 single_line_if_else_max_width: usize, 50, true, "Maximum line length for single line if-else \
55 expressions. A value of zero means always break if-else expressions.";
57 // Comments. macros, and strings
58 wrap_comments: bool, false, false, "Break comments to fit on the line";
59 format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments.";
60 doc_comment_code_block_width: usize, 100, false, "Maximum width for code snippets in doc \
61 comments. No effect unless format_code_in_doc_comments = true";
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 format_strings: bool, false, false, "Format string literals where necessary";
67 format_macro_matchers: bool, false, false,
68 "Format the metavariable matching patterns in macros";
69 format_macro_bodies: bool, true, false, "Format the bodies of macros";
70 hex_literal_case: HexLiteralCase, HexLiteralCase::Preserve, false,
71 "Format hexadecimal integer literals";
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 short_array_element_width_threshold: usize, 10, true,
108 "Width threshold for an array element to be considered short";
109 overflow_delimited_expr: bool, false, false,
110 "Allow trailing bracket/brace delimited expressions to overflow";
111 struct_field_align_threshold: usize, 0, false,
112 "Align struct fields if their diffs fits within threshold";
113 enum_discrim_align_threshold: usize, 0, false,
114 "Align enum variants discrims, if their diffs fit within threshold";
115 match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
116 the same line with the pattern of arms";
117 match_arm_leading_pipes: MatchArmLeadingPipe, MatchArmLeadingPipe::Never, true,
118 "Determines whether leading pipes are emitted on match arms";
119 force_multiline_blocks: bool, false, false,
120 "Force multiline closure bodies and match arms to be wrapped in a block";
121 fn_args_layout: Density, Density::Tall, true,
122 "Control the layout of arguments in a function";
123 brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
124 control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
125 "Brace style for control flow constructs";
126 trailing_semicolon: bool, true, false,
127 "Add trailing semicolon after break, continue and return";
128 trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
129 "How to handle trailing commas for lists";
130 match_block_trailing_comma: bool, false, true,
131 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
132 blank_lines_upper_bound: usize, 1, false,
133 "Maximum number of blank lines which can be put between items";
134 blank_lines_lower_bound: usize, 0, false,
135 "Minimum number of blank lines which must be put between items";
136 edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)";
137 version: Version, Version::One, false, "Version of formatting rules";
138 inline_attribute_width: usize, 0, false,
139 "Write an item and its attribute on the same line \
140 if their combined width is below a threshold";
141 format_generated_files: bool, true, false, "Format generated files";
143 // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
144 merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
145 use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand";
146 use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible";
147 force_explicit_abi: bool, true, true, "Always print the abi for extern items";
148 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
151 // Control options (changes the operation of rustfmt, rather than the formatting)
152 color: Color, Color::Auto, false,
153 "What Color option to use when none is supplied: Always, Never, Auto";
154 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
155 "Require a specific version of rustfmt";
156 unstable_features: bool, false, false,
157 "Enables unstable features. Only available on nightly channel";
158 disable_all_formatting: bool, false, true, "Don't reformat anything";
159 skip_children: bool, false, false, "Don't reformat out of line modules";
160 hide_parse_errors: bool, false, false, "Hide errors from the parser";
161 error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
162 error_on_unformatted: bool, false, false,
163 "Error if unable to get comments or string literals within max_width, \
164 or they are left with trailing whitespaces";
165 ignore: IgnoreList, IgnoreList::default(), false,
166 "Skip formatting the specified files and directories";
169 verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user";
170 file_lines: FileLines, FileLines::all(), false,
171 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
172 via the --file-lines option";
173 emit_mode: EmitMode, EmitMode::Files, false,
174 "What emit Mode to use when none is supplied";
175 make_backup: bool, false, false, "Backup changed files";
176 print_misformatted_file_names: bool, false, true,
177 "Prints the names of mismatched files that were formatted. Prints the names of \
178 files that would be formated when used with `--check` mode. ";
181 #[derive(Error, Debug)]
182 #[error("Could not output config: {0}")]
183 pub struct ToTomlError(toml::ser::Error);
186 pub fn to_toml(&self) -> Result<String, ToTomlError> {
187 // Non-user-facing options can't be specified in TOML
188 let mut cloned = self.clone();
189 cloned.file_lines = None;
190 cloned.verbose = None;
191 cloned.width_heuristics = None;
192 cloned.print_misformatted_file_names = None;
193 cloned.merge_imports = None;
195 ::toml::to_string(&cloned).map_err(ToTomlError)
200 pub(crate) fn version_meets_requirement(&self) -> bool {
201 if self.was_set().required_version() {
202 let version = env!("CARGO_PKG_VERSION");
203 let required_version = self.required_version();
204 if version != required_version {
206 "Error: rustfmt version ({}) doesn't match the required version ({})",
207 version, required_version,
216 /// Constructs a `Config` from the toml file specified at `file_path`.
218 /// This method only looks at the provided path, for a method that
219 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
221 /// Returns a `Config` if the config could be read and parsed from
222 /// the file, otherwise errors.
223 pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
224 let mut file = File::open(&file_path)?;
225 let mut toml = String::new();
226 file.read_to_string(&mut toml)?;
227 Config::from_toml(&toml, file_path.parent().unwrap())
228 .map_err(|err| Error::new(ErrorKind::InvalidData, err))
231 /// Resolves the config for input in `dir`.
233 /// Searches for `rustfmt.toml` beginning with `dir`, and
234 /// recursively checking parents of `dir` if no config file is found.
235 /// If no config file exists in `dir` or in any parent, a
236 /// default `Config` will be returned (and the returned path will be empty).
238 /// Returns the `Config` to use, and the path of the project file if there was
240 pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
241 /// Try to find a project file in the given directory and its parents.
242 /// Returns the path of a the nearest project file if one exists,
243 /// or `None` if no project file was found.
244 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
245 let mut current = if dir.is_relative() {
246 env::current_dir()?.join(dir)
251 current = fs::canonicalize(current)?;
254 match get_toml_path(¤t) {
255 Ok(Some(path)) => return Ok(Some(path)),
256 Err(e) => return Err(e),
260 // If the current directory has no parent, we're done searching.
266 // If nothing was found, check in the home directory.
267 if let Some(home_dir) = dirs::home_dir() {
268 if let Some(path) = get_toml_path(&home_dir)? {
269 return Ok(Some(path));
273 // If none was found ther either, check in the user's configuration directory.
274 if let Some(mut config_dir) = dirs::config_dir() {
275 config_dir.push("rustfmt");
276 if let Some(path) = get_toml_path(&config_dir)? {
277 return Ok(Some(path));
284 match resolve_project_file(dir)? {
285 None => Ok((Config::default(), None)),
286 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
290 pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
291 let parsed: ::toml::Value = toml
293 .map_err(|e| format!("Could not parse TOML: {}", e))?;
294 let mut err = String::new();
297 .ok_or_else(|| String::from("Parsed config was not table"))?;
298 for key in table.keys() {
299 if !Config::is_valid_name(key) {
300 let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
304 match parsed.try_into() {
305 Ok(parsed_config) => {
309 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
312 err.push_str("Error: Decoding config file failed:\n");
313 err.push_str(format!("{}\n", e).as_str());
314 err.push_str("Please check your config file.");
321 /// Loads a config by checking the client-supplied options and if appropriate, the
322 /// file system (including searching the file system for overrides).
323 pub fn load_config<O: CliOptions>(
324 file_path: Option<&Path>,
326 ) -> Result<(Config, Option<PathBuf>), Error> {
327 let over_ride = match options {
328 Some(ref opts) => config_path(opts)?,
332 let result = if let Some(over_ride) = over_ride {
333 Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
334 } else if let Some(file_path) = file_path {
335 Config::from_resolved_toml_path(file_path)
337 Ok((Config::default(), None))
340 result.map(|(mut c, p)| {
341 if let Some(options) = options {
342 options.apply_to(&mut c);
348 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
350 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
351 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
352 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
353 for config_file_name in &CONFIG_FILE_NAMES {
354 let config_file = dir.join(config_file_name);
355 match fs::metadata(&config_file) {
356 // Only return if it's a file to handle the unlikely situation of a directory named
358 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
359 // Return the error if it's something other than `NotFound`; otherwise we didn't
360 // find the project file yet, and continue searching.
362 if e.kind() != ErrorKind::NotFound {
363 let ctx = format!("Failed to get metadata for config file {:?}", &config_file);
364 let err = anyhow::Error::new(e).context(ctx);
365 return Err(Error::new(ErrorKind::Other, err));
374 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
375 let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
379 "Error: unable to find a config file for the given path: `{}`",
385 // Read the config_path and convert to parent dir if a file is provided.
386 // If a config file cannot be found from the given path, return error.
387 match options.config_path() {
388 Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
389 Some(path) if path.is_dir() => {
390 let config_file_path = get_toml_path(path)?;
391 if config_file_path.is_some() {
394 config_path_not_found(path.to_str().unwrap())
397 path => Ok(path.map(ToOwned::to_owned)),
406 use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test};
413 // Options that are used by the generated functions
414 max_width: usize, 100, true, "Maximum width of each line";
415 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
416 "Require a specific version of rustfmt.";
417 ignore: IgnoreList, IgnoreList::default(), false,
418 "Skip formatting the specified files and directories.";
419 verbose: Verbosity, Verbosity::Normal, false,
420 "How much to information to emit to the user";
421 file_lines: FileLines, FileLines::all(), false,
422 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
423 via the --file-lines option";
425 // merge_imports deprecation
426 imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
428 merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
431 use_small_heuristics: Heuristics, Heuristics::Default, true,
432 "Whether to use different formatting for items and \
433 expressions if they satisfy a heuristic notion of 'small'.";
434 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
435 "'small' heuristic values";
437 fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \
438 falling back to vertical formatting.";
439 attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \
440 attributes before falling back to vertical formatting.";
441 struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \
442 falling back to vertical formatting.";
443 struct_variant_width: usize, 35, true, "Maximum width in the body of a struct \
444 variant before falling back to vertical formatting.";
445 array_width: usize, 60, true, "Maximum width of an array literal before falling \
446 back to vertical formatting.";
447 chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line.";
448 single_line_if_else_max_width: usize, 50, true, "Maximum line length for single \
449 line if-else expressions. A value of zero means always break if-else expressions.";
451 // Options that are used by the tests
452 stable_option: bool, false, true, "A stable option";
453 unstable_option: bool, false, false, "An unstable option";
458 fn test_config_set() {
459 let mut config = Config::default();
460 config.set().verbose(Verbosity::Quiet);
461 assert_eq!(config.verbose(), Verbosity::Quiet);
462 config.set().verbose(Verbosity::Normal);
463 assert_eq!(config.verbose(), Verbosity::Normal);
467 fn test_config_used_to_toml() {
468 let config = Config::default();
470 let merge_derives = config.merge_derives();
471 let skip_children = config.skip_children();
473 let used_options = config.used_options();
474 let toml = used_options.to_toml().unwrap();
478 "merge_derives = {}\nskip_children = {}\n",
479 merge_derives, skip_children,
486 let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
488 assert_eq!(config.was_set().hard_tabs(), true);
489 assert_eq!(config.was_set().verbose(), false);
493 fn test_print_docs_exclude_unstable() {
494 use self::mock::Config;
496 let mut output = Vec::new();
497 Config::print_docs(&mut output, false);
499 let s = str::from_utf8(&output).unwrap();
501 assert_eq!(s.contains("stable_option"), true);
502 assert_eq!(s.contains("unstable_option"), false);
503 assert_eq!(s.contains("(unstable)"), false);
507 fn test_print_docs_include_unstable() {
508 use self::mock::Config;
510 let mut output = Vec::new();
511 Config::print_docs(&mut output, true);
513 let s = str::from_utf8(&output).unwrap();
514 assert_eq!(s.contains("stable_option"), true);
515 assert_eq!(s.contains("unstable_option"), true);
516 assert_eq!(s.contains("(unstable)"), true);
520 fn test_dump_default_config() {
521 let default_config = format!(
525 newline_style = "Auto"
526 indent_style = "Block"
527 use_small_heuristics = "Default"
529 attr_fn_like_width = 70
530 struct_lit_width = 18
531 struct_variant_width = 35
534 single_line_if_else_max_width = 50
535 wrap_comments = false
536 format_code_in_doc_comments = false
537 doc_comment_code_block_width = 100
539 normalize_comments = false
540 normalize_doc_attributes = false
541 format_strings = false
542 format_macro_matchers = false
543 format_macro_bodies = true
544 hex_literal_case = "Preserve"
545 empty_item_single_line = true
546 struct_lit_single_line = true
547 fn_single_line = false
548 where_single_line = false
549 imports_indent = "Block"
550 imports_layout = "Mixed"
551 imports_granularity = "Preserve"
552 group_imports = "Preserve"
553 reorder_imports = true
554 reorder_modules = true
555 reorder_impl_items = false
556 type_punctuation_density = "Wide"
557 space_before_colon = false
558 space_after_colon = true
559 spaces_around_ranges = false
560 binop_separator = "Front"
561 remove_nested_parens = true
562 combine_control_expr = true
563 short_array_element_width_threshold = 10
564 overflow_delimited_expr = false
565 struct_field_align_threshold = 0
566 enum_discrim_align_threshold = 0
567 match_arm_blocks = true
568 match_arm_leading_pipes = "Never"
569 force_multiline_blocks = false
570 fn_args_layout = "Tall"
571 brace_style = "SameLineWhere"
572 control_brace_style = "AlwaysSameLine"
573 trailing_semicolon = true
574 trailing_comma = "Vertical"
575 match_block_trailing_comma = false
576 blank_lines_upper_bound = 1
577 blank_lines_lower_bound = 0
580 inline_attribute_width = 0
581 format_generated_files = true
583 use_try_shorthand = false
584 use_field_init_shorthand = false
585 force_explicit_abi = true
586 condense_wildcard_suffixes = false
588 required_version = "{}"
589 unstable_features = false
590 disable_all_formatting = false
591 skip_children = false
592 hide_parse_errors = false
593 error_on_line_overflow = false
594 error_on_unformatted = false
599 env!("CARGO_PKG_VERSION")
601 let toml = Config::default().all_options().to_toml().unwrap();
602 assert_eq!(&toml, &default_config);
607 fn test_as_not_nightly_channel() {
608 let mut config = Config::default();
609 assert_eq!(config.was_set().unstable_features(), false);
610 config.set().unstable_features(true);
611 assert_eq!(config.was_set().unstable_features(), false);
616 fn test_as_nightly_channel() {
617 let mut config = Config::default();
618 config.set().unstable_features(true);
619 // When we don't set the config from toml or command line options it
620 // doesn't get marked as set by the user.
621 assert_eq!(config.was_set().unstable_features(), false);
622 config.set().unstable_features(true);
623 assert_eq!(config.unstable_features(), true);
628 fn test_unstable_from_toml() {
629 let config = Config::from_toml("unstable_features = true", Path::new("")).unwrap();
630 assert_eq!(config.was_set().unstable_features(), true);
631 assert_eq!(config.unstable_features(), true);
635 mod deprecated_option_merge_imports {
640 fn test_old_option_set() {
642 unstable_features = true
645 let config = Config::from_toml(toml, Path::new("")).unwrap();
646 assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
653 unstable_features = true
655 imports_granularity = "Preserve"
657 let config = Config::from_toml(toml, Path::new("")).unwrap();
658 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
663 fn test_new_overridden() {
665 unstable_features = true
668 let mut config = Config::from_toml(toml, Path::new("")).unwrap();
669 config.override_value("imports_granularity", "Preserve");
670 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
675 fn test_old_overridden() {
677 unstable_features = true
678 imports_granularity = "Module"
680 let mut config = Config::from_toml(toml, Path::new("")).unwrap();
681 config.override_value("merge_imports", "true");
682 // no effect: the new option always takes precedence
683 assert_eq!(config.imports_granularity(), ImportGranularity::Module);
688 mod use_small_heuristics {
692 fn test_default_sets_correct_widths() {
694 use_small_heuristics = "Default"
697 let config = Config::from_toml(toml, Path::new("")).unwrap();
698 assert_eq!(config.array_width(), 120);
699 assert_eq!(config.attr_fn_like_width(), 140);
700 assert_eq!(config.chain_width(), 120);
701 assert_eq!(config.fn_call_width(), 120);
702 assert_eq!(config.single_line_if_else_max_width(), 100);
703 assert_eq!(config.struct_lit_width(), 36);
704 assert_eq!(config.struct_variant_width(), 70);
708 fn test_max_sets_correct_widths() {
710 use_small_heuristics = "Max"
713 let config = Config::from_toml(toml, Path::new("")).unwrap();
714 assert_eq!(config.array_width(), 120);
715 assert_eq!(config.attr_fn_like_width(), 120);
716 assert_eq!(config.chain_width(), 120);
717 assert_eq!(config.fn_call_width(), 120);
718 assert_eq!(config.single_line_if_else_max_width(), 120);
719 assert_eq!(config.struct_lit_width(), 120);
720 assert_eq!(config.struct_variant_width(), 120);
724 fn test_off_sets_correct_widths() {
726 use_small_heuristics = "Off"
729 let config = Config::from_toml(toml, Path::new("")).unwrap();
730 assert_eq!(config.array_width(), usize::max_value());
731 assert_eq!(config.attr_fn_like_width(), usize::max_value());
732 assert_eq!(config.chain_width(), usize::max_value());
733 assert_eq!(config.fn_call_width(), usize::max_value());
734 assert_eq!(config.single_line_if_else_max_width(), 0);
735 assert_eq!(config.struct_lit_width(), 0);
736 assert_eq!(config.struct_variant_width(), 0);
740 fn test_override_works_with_default() {
742 use_small_heuristics = "Default"
744 attr_fn_like_width = 40
747 single_line_if_else_max_width = 40
748 struct_lit_width = 30
749 struct_variant_width = 34
751 let config = Config::from_toml(toml, Path::new("")).unwrap();
752 assert_eq!(config.array_width(), 20);
753 assert_eq!(config.attr_fn_like_width(), 40);
754 assert_eq!(config.chain_width(), 20);
755 assert_eq!(config.fn_call_width(), 90);
756 assert_eq!(config.single_line_if_else_max_width(), 40);
757 assert_eq!(config.struct_lit_width(), 30);
758 assert_eq!(config.struct_variant_width(), 34);
762 fn test_override_with_max() {
764 use_small_heuristics = "Max"
766 attr_fn_like_width = 40
769 single_line_if_else_max_width = 40
770 struct_lit_width = 30
771 struct_variant_width = 34
773 let config = Config::from_toml(toml, Path::new("")).unwrap();
774 assert_eq!(config.array_width(), 20);
775 assert_eq!(config.attr_fn_like_width(), 40);
776 assert_eq!(config.chain_width(), 20);
777 assert_eq!(config.fn_call_width(), 90);
778 assert_eq!(config.single_line_if_else_max_width(), 40);
779 assert_eq!(config.struct_lit_width(), 30);
780 assert_eq!(config.struct_variant_width(), 34);
784 fn test_override_with_off() {
786 use_small_heuristics = "Off"
788 attr_fn_like_width = 40
791 single_line_if_else_max_width = 40
792 struct_lit_width = 30
793 struct_variant_width = 34
795 let config = Config::from_toml(toml, Path::new("")).unwrap();
796 assert_eq!(config.array_width(), 20);
797 assert_eq!(config.attr_fn_like_width(), 40);
798 assert_eq!(config.chain_width(), 20);
799 assert_eq!(config.fn_call_width(), 90);
800 assert_eq!(config.single_line_if_else_max_width(), 40);
801 assert_eq!(config.struct_lit_width(), 30);
802 assert_eq!(config.struct_variant_width(), 34);
806 fn test_fn_call_width_config_exceeds_max_width() {
811 let config = Config::from_toml(toml, Path::new("")).unwrap();
812 assert_eq!(config.fn_call_width(), 90);
816 fn test_attr_fn_like_width_config_exceeds_max_width() {
819 attr_fn_like_width = 90
821 let config = Config::from_toml(toml, Path::new("")).unwrap();
822 assert_eq!(config.attr_fn_like_width(), 80);
826 fn test_struct_lit_config_exceeds_max_width() {
829 struct_lit_width = 90
831 let config = Config::from_toml(toml, Path::new("")).unwrap();
832 assert_eq!(config.struct_lit_width(), 78);
836 fn test_struct_variant_width_config_exceeds_max_width() {
839 struct_variant_width = 90
841 let config = Config::from_toml(toml, Path::new("")).unwrap();
842 assert_eq!(config.struct_variant_width(), 80);
846 fn test_array_width_config_exceeds_max_width() {
851 let config = Config::from_toml(toml, Path::new("")).unwrap();
852 assert_eq!(config.array_width(), 60);
856 fn test_chain_width_config_exceeds_max_width() {
861 let config = Config::from_toml(toml, Path::new("")).unwrap();
862 assert_eq!(config.chain_width(), 80);
866 fn test_single_line_if_else_max_width_config_exceeds_max_width() {
869 single_line_if_else_max_width = 90
871 let config = Config::from_toml(toml, Path::new("")).unwrap();
872 assert_eq!(config.single_line_if_else_max_width(), 70);
876 fn test_override_fn_call_width_exceeds_max_width() {
877 let mut config = Config::default();
878 config.override_value("fn_call_width", "101");
879 assert_eq!(config.fn_call_width(), 100);
883 fn test_override_attr_fn_like_width_exceeds_max_width() {
884 let mut config = Config::default();
885 config.override_value("attr_fn_like_width", "101");
886 assert_eq!(config.attr_fn_like_width(), 100);
890 fn test_override_struct_lit_exceeds_max_width() {
891 let mut config = Config::default();
892 config.override_value("struct_lit_width", "101");
893 assert_eq!(config.struct_lit_width(), 100);
897 fn test_override_struct_variant_width_exceeds_max_width() {
898 let mut config = Config::default();
899 config.override_value("struct_variant_width", "101");
900 assert_eq!(config.struct_variant_width(), 100);
904 fn test_override_array_width_exceeds_max_width() {
905 let mut config = Config::default();
906 config.override_value("array_width", "101");
907 assert_eq!(config.array_width(), 100);
911 fn test_override_chain_width_exceeds_max_width() {
912 let mut config = Config::default();
913 config.override_value("chain_width", "101");
914 assert_eq!(config.chain_width(), 100);
918 fn test_override_single_line_if_else_max_width_exceeds_max_width() {
919 let mut config = Config::default();
920 config.override_value("single_line_if_else_max_width", "101");
921 assert_eq!(config.single_line_if_else_max_width(), 100);