]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/config/mod.rs
Merge commit '3c7e7dbc1583a0b06df5bd7623dd354a4debd23d' into clippyup
[rust.git] / src / tools / rustfmt / src / config / mod.rs
1 use std::cell::Cell;
2 use std::default::Default;
3 use std::fs::File;
4 use std::io::{Error, ErrorKind, Read};
5 use std::path::{Path, PathBuf};
6 use std::{env, fs};
7
8 use thiserror::Error;
9
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::*;
17
18 #[macro_use]
19 pub(crate) mod config_type;
20 #[macro_use]
21 pub(crate) mod options;
22
23 pub(crate) mod file_lines;
24 pub(crate) mod lists;
25
26 // This macro defines configuration options used in rustfmt. Each option
27 // is defined as follows:
28 //
29 // `name: value type, default value, is stable, description;`
30 create_config! {
31     // Fundamental stuff
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";
37
38     // Width Heuristics
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.";
56
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";
72
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";
80
81     // Imports
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)";
89
90     // Ordering
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";
94
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";
103
104     // Misc.
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";
142
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 .. \
149                                                      in tuple patterns";
150
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";
167
168     // Not user-facing
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. ";
179 }
180
181 #[derive(Error, Debug)]
182 #[error("Could not output config: {0}")]
183 pub struct ToTomlError(toml::ser::Error);
184
185 impl PartialConfig {
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;
194
195         ::toml::to_string(&cloned).map_err(ToTomlError)
196     }
197 }
198
199 impl Config {
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 {
205                 println!(
206                     "Error: rustfmt version ({}) doesn't match the required version ({})",
207                     version, required_version,
208                 );
209                 return false;
210             }
211         }
212
213         true
214     }
215
216     /// Constructs a `Config` from the toml file specified at `file_path`.
217     ///
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`.
220     ///
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))
229     }
230
231     /// Resolves the config for input in `dir`.
232     ///
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).
237     ///
238     /// Returns the `Config` to use, and the path of the project file if there was
239     /// one.
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)
247             } else {
248                 dir.to_path_buf()
249             };
250
251             current = fs::canonicalize(current)?;
252
253             loop {
254                 match get_toml_path(&current) {
255                     Ok(Some(path)) => return Ok(Some(path)),
256                     Err(e) => return Err(e),
257                     _ => (),
258                 }
259
260                 // If the current directory has no parent, we're done searching.
261                 if !current.pop() {
262                     break;
263                 }
264             }
265
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));
270                 }
271             }
272
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));
278                 }
279             }
280
281             Ok(None)
282         }
283
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))),
287         }
288     }
289
290     pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
291         let parsed: ::toml::Value = toml
292             .parse()
293             .map_err(|e| format!("Could not parse TOML: {}", e))?;
294         let mut err = String::new();
295         let table = parsed
296             .as_table()
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);
301                 err.push_str(msg)
302             }
303         }
304         match parsed.try_into() {
305             Ok(parsed_config) => {
306                 if !err.is_empty() {
307                     eprint!("{}", err);
308                 }
309                 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
310             }
311             Err(e) => {
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.");
315                 Err(err)
316             }
317         }
318     }
319 }
320
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>,
325     options: Option<O>,
326 ) -> Result<(Config, Option<PathBuf>), Error> {
327     let over_ride = match options {
328         Some(ref opts) => config_path(opts)?,
329         None => None,
330     };
331
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)
336     } else {
337         Ok((Config::default(), None))
338     };
339
340     result.map(|(mut c, p)| {
341         if let Some(options) = options {
342             options.apply_to(&mut c);
343         }
344         (c, p)
345     })
346 }
347
348 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
349 //
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
357             // `rustfmt.toml`.
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.
361             Err(e) => {
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));
366                 }
367             }
368             _ => {}
369         }
370     }
371     Ok(None)
372 }
373
374 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
375     let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
376         Err(Error::new(
377             ErrorKind::NotFound,
378             format!(
379                 "Error: unable to find a config file for the given path: `{}`",
380                 path
381             ),
382         ))
383     };
384
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() {
392                 Ok(config_file_path)
393             } else {
394                 config_path_not_found(path.to_str().unwrap())
395             }
396         }
397         path => Ok(path.map(ToOwned::to_owned)),
398     }
399 }
400
401 #[cfg(test)]
402 mod test {
403     use super::*;
404     use std::str;
405
406     use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test};
407
408     #[allow(dead_code)]
409     mod mock {
410         use super::super::*;
411
412         create_config! {
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";
424
425             // merge_imports deprecation
426             imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
427                 "Merge imports";
428             merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
429
430             // Width Heuristics
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";
436
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.";
450
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";
454         }
455     }
456
457     #[test]
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);
464     }
465
466     #[test]
467     fn test_config_used_to_toml() {
468         let config = Config::default();
469
470         let merge_derives = config.merge_derives();
471         let skip_children = config.skip_children();
472
473         let used_options = config.used_options();
474         let toml = used_options.to_toml().unwrap();
475         assert_eq!(
476             toml,
477             format!(
478                 "merge_derives = {}\nskip_children = {}\n",
479                 merge_derives, skip_children,
480             )
481         );
482     }
483
484     #[test]
485     fn test_was_set() {
486         let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
487
488         assert_eq!(config.was_set().hard_tabs(), true);
489         assert_eq!(config.was_set().verbose(), false);
490     }
491
492     #[test]
493     fn test_print_docs_exclude_unstable() {
494         use self::mock::Config;
495
496         let mut output = Vec::new();
497         Config::print_docs(&mut output, false);
498
499         let s = str::from_utf8(&output).unwrap();
500
501         assert_eq!(s.contains("stable_option"), true);
502         assert_eq!(s.contains("unstable_option"), false);
503         assert_eq!(s.contains("(unstable)"), false);
504     }
505
506     #[test]
507     fn test_print_docs_include_unstable() {
508         use self::mock::Config;
509
510         let mut output = Vec::new();
511         Config::print_docs(&mut output, true);
512
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);
517     }
518
519     #[test]
520     fn test_dump_default_config() {
521         let default_config = format!(
522             r#"max_width = 100
523 hard_tabs = false
524 tab_spaces = 4
525 newline_style = "Auto"
526 indent_style = "Block"
527 use_small_heuristics = "Default"
528 fn_call_width = 60
529 attr_fn_like_width = 70
530 struct_lit_width = 18
531 struct_variant_width = 35
532 array_width = 60
533 chain_width = 60
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
538 comment_width = 80
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
578 edition = "2015"
579 version = "One"
580 inline_attribute_width = 0
581 format_generated_files = true
582 merge_derives = true
583 use_try_shorthand = false
584 use_field_init_shorthand = false
585 force_explicit_abi = true
586 condense_wildcard_suffixes = false
587 color = "Auto"
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
595 ignore = []
596 emit_mode = "Files"
597 make_backup = false
598 "#,
599             env!("CARGO_PKG_VERSION")
600         );
601         let toml = Config::default().all_options().to_toml().unwrap();
602         assert_eq!(&toml, &default_config);
603     }
604
605     #[stable_only_test]
606     #[test]
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);
612     }
613
614     #[nightly_only_test]
615     #[test]
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);
624     }
625
626     #[nightly_only_test]
627     #[test]
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);
632     }
633
634     #[cfg(test)]
635     mod deprecated_option_merge_imports {
636         use super::*;
637
638         #[nightly_only_test]
639         #[test]
640         fn test_old_option_set() {
641             let toml = r#"
642                 unstable_features = true
643                 merge_imports = true
644             "#;
645             let config = Config::from_toml(toml, Path::new("")).unwrap();
646             assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
647         }
648
649         #[nightly_only_test]
650         #[test]
651         fn test_both_set() {
652             let toml = r#"
653                 unstable_features = true
654                 merge_imports = true
655                 imports_granularity = "Preserve"
656             "#;
657             let config = Config::from_toml(toml, Path::new("")).unwrap();
658             assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
659         }
660
661         #[nightly_only_test]
662         #[test]
663         fn test_new_overridden() {
664             let toml = r#"
665                 unstable_features = true
666                 merge_imports = true
667             "#;
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);
671         }
672
673         #[nightly_only_test]
674         #[test]
675         fn test_old_overridden() {
676             let toml = r#"
677                 unstable_features = true
678                 imports_granularity = "Module"
679             "#;
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);
684         }
685     }
686
687     #[cfg(test)]
688     mod use_small_heuristics {
689         use super::*;
690
691         #[test]
692         fn test_default_sets_correct_widths() {
693             let toml = r#"
694                 use_small_heuristics = "Default"
695                 max_width = 200
696             "#;
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);
705         }
706
707         #[test]
708         fn test_max_sets_correct_widths() {
709             let toml = r#"
710                 use_small_heuristics = "Max"
711                 max_width = 120
712             "#;
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);
721         }
722
723         #[test]
724         fn test_off_sets_correct_widths() {
725             let toml = r#"
726                 use_small_heuristics = "Off"
727                 max_width = 100
728             "#;
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);
737         }
738
739         #[test]
740         fn test_override_works_with_default() {
741             let toml = r#"
742                 use_small_heuristics = "Default"
743                 array_width = 20
744                 attr_fn_like_width = 40
745                 chain_width = 20
746                 fn_call_width = 90
747                 single_line_if_else_max_width = 40
748                 struct_lit_width = 30
749                 struct_variant_width = 34
750             "#;
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);
759         }
760
761         #[test]
762         fn test_override_with_max() {
763             let toml = r#"
764                 use_small_heuristics = "Max"
765                 array_width = 20
766                 attr_fn_like_width = 40
767                 chain_width = 20
768                 fn_call_width = 90
769                 single_line_if_else_max_width = 40
770                 struct_lit_width = 30
771                 struct_variant_width = 34
772             "#;
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);
781         }
782
783         #[test]
784         fn test_override_with_off() {
785             let toml = r#"
786                 use_small_heuristics = "Off"
787                 array_width = 20
788                 attr_fn_like_width = 40
789                 chain_width = 20
790                 fn_call_width = 90
791                 single_line_if_else_max_width = 40
792                 struct_lit_width = 30
793                 struct_variant_width = 34
794             "#;
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);
803         }
804
805         #[test]
806         fn test_fn_call_width_config_exceeds_max_width() {
807             let toml = r#"
808                 max_width = 90
809                 fn_call_width = 95
810             "#;
811             let config = Config::from_toml(toml, Path::new("")).unwrap();
812             assert_eq!(config.fn_call_width(), 90);
813         }
814
815         #[test]
816         fn test_attr_fn_like_width_config_exceeds_max_width() {
817             let toml = r#"
818                 max_width = 80
819                 attr_fn_like_width = 90
820             "#;
821             let config = Config::from_toml(toml, Path::new("")).unwrap();
822             assert_eq!(config.attr_fn_like_width(), 80);
823         }
824
825         #[test]
826         fn test_struct_lit_config_exceeds_max_width() {
827             let toml = r#"
828                 max_width = 78
829                 struct_lit_width = 90
830             "#;
831             let config = Config::from_toml(toml, Path::new("")).unwrap();
832             assert_eq!(config.struct_lit_width(), 78);
833         }
834
835         #[test]
836         fn test_struct_variant_width_config_exceeds_max_width() {
837             let toml = r#"
838                 max_width = 80
839                 struct_variant_width = 90
840             "#;
841             let config = Config::from_toml(toml, Path::new("")).unwrap();
842             assert_eq!(config.struct_variant_width(), 80);
843         }
844
845         #[test]
846         fn test_array_width_config_exceeds_max_width() {
847             let toml = r#"
848                 max_width = 60
849                 array_width = 80
850             "#;
851             let config = Config::from_toml(toml, Path::new("")).unwrap();
852             assert_eq!(config.array_width(), 60);
853         }
854
855         #[test]
856         fn test_chain_width_config_exceeds_max_width() {
857             let toml = r#"
858                 max_width = 80
859                 chain_width = 90
860             "#;
861             let config = Config::from_toml(toml, Path::new("")).unwrap();
862             assert_eq!(config.chain_width(), 80);
863         }
864
865         #[test]
866         fn test_single_line_if_else_max_width_config_exceeds_max_width() {
867             let toml = r#"
868                 max_width = 70
869                 single_line_if_else_max_width = 90
870             "#;
871             let config = Config::from_toml(toml, Path::new("")).unwrap();
872             assert_eq!(config.single_line_if_else_max_width(), 70);
873         }
874
875         #[test]
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);
880         }
881
882         #[test]
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);
887         }
888
889         #[test]
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);
894         }
895
896         #[test]
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);
901         }
902
903         #[test]
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);
908         }
909
910         #[test]
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);
915         }
916
917         #[test]
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);
922         }
923     }
924 }