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 comment_width: usize, 80, false,
61 "Maximum length of comments. No effect unless wrap_comments = true";
62 normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
63 normalize_doc_attributes: bool, false, false, "Normalize doc attributes as doc comments";
64 format_strings: bool, false, false, "Format string literals where necessary";
65 format_macro_matchers: bool, false, false,
66 "Format the metavariable matching patterns in macros";
67 format_macro_bodies: bool, true, false, "Format the bodies of macros";
68 hex_literal_case: HexLiteralCase, HexLiteralCase::Preserve, false,
69 "Format hexadecimal integer literals";
71 // Single line expressions and items
72 empty_item_single_line: bool, true, false,
73 "Put empty-body functions and impls on a single line";
74 struct_lit_single_line: bool, true, false,
75 "Put small struct literals on a single line";
76 fn_single_line: bool, false, false, "Put single-expression functions on a single line";
77 where_single_line: bool, false, false, "Force where-clauses to be on a single line";
80 imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports";
81 imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
82 imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
83 "Merge or split imports to the provided granularity";
84 group_imports: GroupImportsTactic, GroupImportsTactic::Preserve, false,
85 "Controls the strategy for how imports are grouped together";
86 merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
89 reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically";
90 reorder_modules: bool, true, true, "Reorder module statements alphabetically in group";
91 reorder_impl_items: bool, false, false, "Reorder impl items";
93 // Spaces around punctuation
94 type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
95 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
96 space_before_colon: bool, false, false, "Leave a space before the colon";
97 space_after_colon: bool, true, false, "Leave a space after the colon";
98 spaces_around_ranges: bool, false, false, "Put spaces around the .. and ..= range operators";
99 binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
100 "Where to put a binary operator when a binary expression goes multiline";
103 remove_nested_parens: bool, true, true, "Remove nested parens";
104 combine_control_expr: bool, true, false, "Combine control expressions with function calls";
105 short_array_element_width_threshold: usize, 10, true,
106 "Width threshold for an array element to be considered short";
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, true,
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";
139 format_generated_files: bool, true, false, "Format generated files";
141 // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
142 merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
143 use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand";
144 use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible";
145 force_explicit_abi: bool, true, true, "Always print the abi for extern items";
146 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
149 // Control options (changes the operation of rustfmt, rather than the formatting)
150 color: Color, Color::Auto, false,
151 "What Color option to use when none is supplied: Always, Never, Auto";
152 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
153 "Require a specific version of rustfmt";
154 unstable_features: bool, false, false,
155 "Enables unstable features. Only available on nightly channel";
156 disable_all_formatting: bool, false, true, "Don't reformat anything";
157 skip_children: bool, false, false, "Don't reformat out of line modules";
158 hide_parse_errors: bool, false, false, "Hide errors from the parser";
159 error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
160 error_on_unformatted: bool, false, false,
161 "Error if unable to get comments or string literals within max_width, \
162 or they are left with trailing whitespaces";
163 ignore: IgnoreList, IgnoreList::default(), false,
164 "Skip formatting the specified files and directories";
167 verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user";
168 file_lines: FileLines, FileLines::all(), false,
169 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
170 via the --file-lines option";
171 emit_mode: EmitMode, EmitMode::Files, false,
172 "What emit Mode to use when none is supplied";
173 make_backup: bool, false, false, "Backup changed files";
174 print_misformatted_file_names: bool, false, true,
175 "Prints the names of mismatched files that were formatted. Prints the names of \
176 files that would be formated when used with `--check` mode. ";
179 #[derive(Error, Debug)]
180 #[error("Could not output config: {0}")]
181 pub struct ToTomlError(toml::ser::Error);
184 pub fn to_toml(&self) -> Result<String, ToTomlError> {
185 // Non-user-facing options can't be specified in TOML
186 let mut cloned = self.clone();
187 cloned.file_lines = None;
188 cloned.verbose = None;
189 cloned.width_heuristics = None;
190 cloned.print_misformatted_file_names = None;
191 cloned.merge_imports = None;
193 ::toml::to_string(&cloned).map_err(ToTomlError)
198 pub(crate) fn version_meets_requirement(&self) -> bool {
199 if self.was_set().required_version() {
200 let version = env!("CARGO_PKG_VERSION");
201 let required_version = self.required_version();
202 if version != required_version {
204 "Error: rustfmt version ({}) doesn't match the required version ({})",
205 version, required_version,
214 /// Constructs a `Config` from the toml file specified at `file_path`.
216 /// This method only looks at the provided path, for a method that
217 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
219 /// Returns a `Config` if the config could be read and parsed from
220 /// the file, otherwise errors.
221 pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
222 let mut file = File::open(&file_path)?;
223 let mut toml = String::new();
224 file.read_to_string(&mut toml)?;
225 Config::from_toml(&toml, file_path.parent().unwrap())
226 .map_err(|err| Error::new(ErrorKind::InvalidData, err))
229 /// Resolves the config for input in `dir`.
231 /// Searches for `rustfmt.toml` beginning with `dir`, and
232 /// recursively checking parents of `dir` if no config file is found.
233 /// If no config file exists in `dir` or in any parent, a
234 /// default `Config` will be returned (and the returned path will be empty).
236 /// Returns the `Config` to use, and the path of the project file if there was
238 pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
239 /// Try to find a project file in the given directory and its parents.
240 /// Returns the path of a the nearest project file if one exists,
241 /// or `None` if no project file was found.
242 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
243 let mut current = if dir.is_relative() {
244 env::current_dir()?.join(dir)
249 current = fs::canonicalize(current)?;
252 match get_toml_path(¤t) {
253 Ok(Some(path)) => return Ok(Some(path)),
254 Err(e) => return Err(e),
258 // If the current directory has no parent, we're done searching.
264 // If nothing was found, check in the home directory.
265 if let Some(home_dir) = dirs::home_dir() {
266 if let Some(path) = get_toml_path(&home_dir)? {
267 return Ok(Some(path));
271 // If none was found ther either, check in the user's configuration directory.
272 if let Some(mut config_dir) = dirs::config_dir() {
273 config_dir.push("rustfmt");
274 if let Some(path) = get_toml_path(&config_dir)? {
275 return Ok(Some(path));
282 match resolve_project_file(dir)? {
283 None => Ok((Config::default(), None)),
284 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
288 pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
289 let parsed: ::toml::Value = toml
291 .map_err(|e| format!("Could not parse TOML: {}", e))?;
292 let mut err = String::new();
295 .ok_or_else(|| String::from("Parsed config was not table"))?;
296 for key in table.keys() {
297 if !Config::is_valid_name(key) {
298 let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
302 match parsed.try_into() {
303 Ok(parsed_config) => {
307 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
310 err.push_str("Error: Decoding config file failed:\n");
311 err.push_str(format!("{}\n", e).as_str());
312 err.push_str("Please check your config file.");
319 /// Loads a config by checking the client-supplied options and if appropriate, the
320 /// file system (including searching the file system for overrides).
321 pub fn load_config<O: CliOptions>(
322 file_path: Option<&Path>,
324 ) -> Result<(Config, Option<PathBuf>), Error> {
325 let over_ride = match options {
326 Some(ref opts) => config_path(opts)?,
330 let result = if let Some(over_ride) = over_ride {
331 Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
332 } else if let Some(file_path) = file_path {
333 Config::from_resolved_toml_path(file_path)
335 Ok((Config::default(), None))
338 result.map(|(mut c, p)| {
339 if let Some(options) = options {
340 options.apply_to(&mut c);
346 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
348 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
349 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
350 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
351 for config_file_name in &CONFIG_FILE_NAMES {
352 let config_file = dir.join(config_file_name);
353 match fs::metadata(&config_file) {
354 // Only return if it's a file to handle the unlikely situation of a directory named
356 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
357 // Return the error if it's something other than `NotFound`; otherwise we didn't
358 // find the project file yet, and continue searching.
360 if e.kind() != ErrorKind::NotFound {
361 let ctx = format!("Failed to get metadata for config file {:?}", &config_file);
362 let err = anyhow::Error::new(e).context(ctx);
363 return Err(Error::new(ErrorKind::Other, err));
372 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
373 let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
377 "Error: unable to find a config file for the given path: `{}`",
383 // Read the config_path and convert to parent dir if a file is provided.
384 // If a config file cannot be found from the given path, return error.
385 match options.config_path() {
386 Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
387 Some(path) if path.is_dir() => {
388 let config_file_path = get_toml_path(path)?;
389 if config_file_path.is_some() {
392 config_path_not_found(path.to_str().unwrap())
395 path => Ok(path.map(ToOwned::to_owned)),
404 use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test};
411 // Options that are used by the generated functions
412 max_width: usize, 100, true, "Maximum width of each line";
413 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
414 "Require a specific version of rustfmt.";
415 ignore: IgnoreList, IgnoreList::default(), false,
416 "Skip formatting the specified files and directories.";
417 verbose: Verbosity, Verbosity::Normal, false,
418 "How much to information to emit to the user";
419 file_lines: FileLines, FileLines::all(), false,
420 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
421 via the --file-lines option";
423 // merge_imports deprecation
424 imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
426 merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
429 use_small_heuristics: Heuristics, Heuristics::Default, true,
430 "Whether to use different formatting for items and \
431 expressions if they satisfy a heuristic notion of 'small'.";
432 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
433 "'small' heuristic values";
435 fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \
436 falling back to vertical formatting.";
437 attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \
438 attributes before falling back to vertical formatting.";
439 struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \
440 falling back to vertical formatting.";
441 struct_variant_width: usize, 35, true, "Maximum width in the body of a struct \
442 variant before falling back to vertical formatting.";
443 array_width: usize, 60, true, "Maximum width of an array literal before falling \
444 back to vertical formatting.";
445 chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line.";
446 single_line_if_else_max_width: usize, 50, true, "Maximum line length for single \
447 line if-else expressions. A value of zero means always break if-else expressions.";
449 // Options that are used by the tests
450 stable_option: bool, false, true, "A stable option";
451 unstable_option: bool, false, false, "An unstable option";
456 fn test_config_set() {
457 let mut config = Config::default();
458 config.set().verbose(Verbosity::Quiet);
459 assert_eq!(config.verbose(), Verbosity::Quiet);
460 config.set().verbose(Verbosity::Normal);
461 assert_eq!(config.verbose(), Verbosity::Normal);
465 fn test_config_used_to_toml() {
466 let config = Config::default();
468 let merge_derives = config.merge_derives();
469 let skip_children = config.skip_children();
471 let used_options = config.used_options();
472 let toml = used_options.to_toml().unwrap();
476 "merge_derives = {}\nskip_children = {}\n",
477 merge_derives, skip_children,
484 let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
486 assert_eq!(config.was_set().hard_tabs(), true);
487 assert_eq!(config.was_set().verbose(), false);
491 fn test_print_docs_exclude_unstable() {
492 use self::mock::Config;
494 let mut output = Vec::new();
495 Config::print_docs(&mut output, false);
497 let s = str::from_utf8(&output).unwrap();
499 assert_eq!(s.contains("stable_option"), true);
500 assert_eq!(s.contains("unstable_option"), false);
501 assert_eq!(s.contains("(unstable)"), false);
505 fn test_print_docs_include_unstable() {
506 use self::mock::Config;
508 let mut output = Vec::new();
509 Config::print_docs(&mut output, true);
511 let s = str::from_utf8(&output).unwrap();
512 assert_eq!(s.contains("stable_option"), true);
513 assert_eq!(s.contains("unstable_option"), true);
514 assert_eq!(s.contains("(unstable)"), true);
518 fn test_dump_default_config() {
519 let default_config = format!(
523 newline_style = "Auto"
524 indent_style = "Block"
525 use_small_heuristics = "Default"
527 attr_fn_like_width = 70
528 struct_lit_width = 18
529 struct_variant_width = 35
532 single_line_if_else_max_width = 50
533 wrap_comments = false
534 format_code_in_doc_comments = false
536 normalize_comments = false
537 normalize_doc_attributes = false
538 format_strings = false
539 format_macro_matchers = false
540 format_macro_bodies = true
541 hex_literal_case = "Preserve"
542 empty_item_single_line = true
543 struct_lit_single_line = true
544 fn_single_line = false
545 where_single_line = false
546 imports_indent = "Block"
547 imports_layout = "Mixed"
548 imports_granularity = "Preserve"
549 group_imports = "Preserve"
550 reorder_imports = true
551 reorder_modules = true
552 reorder_impl_items = false
553 type_punctuation_density = "Wide"
554 space_before_colon = false
555 space_after_colon = true
556 spaces_around_ranges = false
557 binop_separator = "Front"
558 remove_nested_parens = true
559 combine_control_expr = true
560 short_array_element_width_threshold = 10
561 overflow_delimited_expr = false
562 struct_field_align_threshold = 0
563 enum_discrim_align_threshold = 0
564 match_arm_blocks = true
565 match_arm_leading_pipes = "Never"
566 force_multiline_blocks = false
567 fn_args_layout = "Tall"
568 brace_style = "SameLineWhere"
569 control_brace_style = "AlwaysSameLine"
570 trailing_semicolon = true
571 trailing_comma = "Vertical"
572 match_block_trailing_comma = false
573 blank_lines_upper_bound = 1
574 blank_lines_lower_bound = 0
577 inline_attribute_width = 0
578 format_generated_files = true
580 use_try_shorthand = false
581 use_field_init_shorthand = false
582 force_explicit_abi = true
583 condense_wildcard_suffixes = false
585 required_version = "{}"
586 unstable_features = false
587 disable_all_formatting = false
588 skip_children = false
589 hide_parse_errors = false
590 error_on_line_overflow = false
591 error_on_unformatted = false
596 env!("CARGO_PKG_VERSION")
598 let toml = Config::default().all_options().to_toml().unwrap();
599 assert_eq!(&toml, &default_config);
604 fn test_as_not_nightly_channel() {
605 let mut config = Config::default();
606 assert_eq!(config.was_set().unstable_features(), false);
607 config.set().unstable_features(true);
608 assert_eq!(config.was_set().unstable_features(), false);
613 fn test_as_nightly_channel() {
614 let mut config = Config::default();
615 config.set().unstable_features(true);
616 // When we don't set the config from toml or command line options it
617 // doesn't get marked as set by the user.
618 assert_eq!(config.was_set().unstable_features(), false);
619 config.set().unstable_features(true);
620 assert_eq!(config.unstable_features(), true);
625 fn test_unstable_from_toml() {
626 let config = Config::from_toml("unstable_features = true", Path::new("")).unwrap();
627 assert_eq!(config.was_set().unstable_features(), true);
628 assert_eq!(config.unstable_features(), true);
632 mod deprecated_option_merge_imports {
637 fn test_old_option_set() {
639 unstable_features = true
642 let config = Config::from_toml(toml, Path::new("")).unwrap();
643 assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
650 unstable_features = true
652 imports_granularity = "Preserve"
654 let config = Config::from_toml(toml, Path::new("")).unwrap();
655 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
660 fn test_new_overridden() {
662 unstable_features = true
665 let mut config = Config::from_toml(toml, Path::new("")).unwrap();
666 config.override_value("imports_granularity", "Preserve");
667 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
672 fn test_old_overridden() {
674 unstable_features = true
675 imports_granularity = "Module"
677 let mut config = Config::from_toml(toml, Path::new("")).unwrap();
678 config.override_value("merge_imports", "true");
679 // no effect: the new option always takes precedence
680 assert_eq!(config.imports_granularity(), ImportGranularity::Module);
685 mod use_small_heuristics {
689 fn test_default_sets_correct_widths() {
691 use_small_heuristics = "Default"
694 let config = Config::from_toml(toml, Path::new("")).unwrap();
695 assert_eq!(config.array_width(), 120);
696 assert_eq!(config.attr_fn_like_width(), 140);
697 assert_eq!(config.chain_width(), 120);
698 assert_eq!(config.fn_call_width(), 120);
699 assert_eq!(config.single_line_if_else_max_width(), 100);
700 assert_eq!(config.struct_lit_width(), 36);
701 assert_eq!(config.struct_variant_width(), 70);
705 fn test_max_sets_correct_widths() {
707 use_small_heuristics = "Max"
710 let config = Config::from_toml(toml, Path::new("")).unwrap();
711 assert_eq!(config.array_width(), 120);
712 assert_eq!(config.attr_fn_like_width(), 120);
713 assert_eq!(config.chain_width(), 120);
714 assert_eq!(config.fn_call_width(), 120);
715 assert_eq!(config.single_line_if_else_max_width(), 120);
716 assert_eq!(config.struct_lit_width(), 120);
717 assert_eq!(config.struct_variant_width(), 120);
721 fn test_off_sets_correct_widths() {
723 use_small_heuristics = "Off"
726 let config = Config::from_toml(toml, Path::new("")).unwrap();
727 assert_eq!(config.array_width(), usize::max_value());
728 assert_eq!(config.attr_fn_like_width(), usize::max_value());
729 assert_eq!(config.chain_width(), usize::max_value());
730 assert_eq!(config.fn_call_width(), usize::max_value());
731 assert_eq!(config.single_line_if_else_max_width(), 0);
732 assert_eq!(config.struct_lit_width(), 0);
733 assert_eq!(config.struct_variant_width(), 0);
737 fn test_override_works_with_default() {
739 use_small_heuristics = "Default"
741 attr_fn_like_width = 40
744 single_line_if_else_max_width = 40
745 struct_lit_width = 30
746 struct_variant_width = 34
748 let config = Config::from_toml(toml, Path::new("")).unwrap();
749 assert_eq!(config.array_width(), 20);
750 assert_eq!(config.attr_fn_like_width(), 40);
751 assert_eq!(config.chain_width(), 20);
752 assert_eq!(config.fn_call_width(), 90);
753 assert_eq!(config.single_line_if_else_max_width(), 40);
754 assert_eq!(config.struct_lit_width(), 30);
755 assert_eq!(config.struct_variant_width(), 34);
759 fn test_override_with_max() {
761 use_small_heuristics = "Max"
763 attr_fn_like_width = 40
766 single_line_if_else_max_width = 40
767 struct_lit_width = 30
768 struct_variant_width = 34
770 let config = Config::from_toml(toml, Path::new("")).unwrap();
771 assert_eq!(config.array_width(), 20);
772 assert_eq!(config.attr_fn_like_width(), 40);
773 assert_eq!(config.chain_width(), 20);
774 assert_eq!(config.fn_call_width(), 90);
775 assert_eq!(config.single_line_if_else_max_width(), 40);
776 assert_eq!(config.struct_lit_width(), 30);
777 assert_eq!(config.struct_variant_width(), 34);
781 fn test_override_with_off() {
783 use_small_heuristics = "Off"
785 attr_fn_like_width = 40
788 single_line_if_else_max_width = 40
789 struct_lit_width = 30
790 struct_variant_width = 34
792 let config = Config::from_toml(toml, Path::new("")).unwrap();
793 assert_eq!(config.array_width(), 20);
794 assert_eq!(config.attr_fn_like_width(), 40);
795 assert_eq!(config.chain_width(), 20);
796 assert_eq!(config.fn_call_width(), 90);
797 assert_eq!(config.single_line_if_else_max_width(), 40);
798 assert_eq!(config.struct_lit_width(), 30);
799 assert_eq!(config.struct_variant_width(), 34);
803 fn test_fn_call_width_config_exceeds_max_width() {
808 let config = Config::from_toml(toml, Path::new("")).unwrap();
809 assert_eq!(config.fn_call_width(), 90);
813 fn test_attr_fn_like_width_config_exceeds_max_width() {
816 attr_fn_like_width = 90
818 let config = Config::from_toml(toml, Path::new("")).unwrap();
819 assert_eq!(config.attr_fn_like_width(), 80);
823 fn test_struct_lit_config_exceeds_max_width() {
826 struct_lit_width = 90
828 let config = Config::from_toml(toml, Path::new("")).unwrap();
829 assert_eq!(config.struct_lit_width(), 78);
833 fn test_struct_variant_width_config_exceeds_max_width() {
836 struct_variant_width = 90
838 let config = Config::from_toml(toml, Path::new("")).unwrap();
839 assert_eq!(config.struct_variant_width(), 80);
843 fn test_array_width_config_exceeds_max_width() {
848 let config = Config::from_toml(toml, Path::new("")).unwrap();
849 assert_eq!(config.array_width(), 60);
853 fn test_chain_width_config_exceeds_max_width() {
858 let config = Config::from_toml(toml, Path::new("")).unwrap();
859 assert_eq!(config.chain_width(), 80);
863 fn test_single_line_if_else_max_width_config_exceeds_max_width() {
866 single_line_if_else_max_width = 90
868 let config = Config::from_toml(toml, Path::new("")).unwrap();
869 assert_eq!(config.single_line_if_else_max_width(), 70);
873 fn test_override_fn_call_width_exceeds_max_width() {
874 let mut config = Config::default();
875 config.override_value("fn_call_width", "101");
876 assert_eq!(config.fn_call_width(), 100);
880 fn test_override_attr_fn_like_width_exceeds_max_width() {
881 let mut config = Config::default();
882 config.override_value("attr_fn_like_width", "101");
883 assert_eq!(config.attr_fn_like_width(), 100);
887 fn test_override_struct_lit_exceeds_max_width() {
888 let mut config = Config::default();
889 config.override_value("struct_lit_width", "101");
890 assert_eq!(config.struct_lit_width(), 100);
894 fn test_override_struct_variant_width_exceeds_max_width() {
895 let mut config = Config::default();
896 config.override_value("struct_variant_width", "101");
897 assert_eq!(config.struct_variant_width(), 100);
901 fn test_override_array_width_exceeds_max_width() {
902 let mut config = Config::default();
903 config.override_value("array_width", "101");
904 assert_eq!(config.array_width(), 100);
908 fn test_override_chain_width_exceeds_max_width() {
909 let mut config = Config::default();
910 config.override_value("chain_width", "101");
911 assert_eq!(config.chain_width(), 100);
915 fn test_override_single_line_if_else_max_width_exceeds_max_width() {
916 let mut config = Config::default();
917 config.override_value("single_line_if_else_max_width", "101");
918 assert_eq!(config.single_line_if_else_max_width(), 100);