]> git.lizzy.rs Git - rust.git/blob - src/config/mod.rs
feat: remove license_template_path config option
[rust.git] / 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     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";
70
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";
78
79     // Imports
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)";
87
88     // Ordering
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";
92
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";
101
102     // Misc.
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";
140
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 .. \
147                                                      in tuple patterns";
148
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";
165
166     // Not user-facing
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. ";
177 }
178
179 #[derive(Error, Debug)]
180 #[error("Could not output config: {0}")]
181 pub struct ToTomlError(toml::ser::Error);
182
183 impl PartialConfig {
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;
192
193         ::toml::to_string(&cloned).map_err(ToTomlError)
194     }
195 }
196
197 impl Config {
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 {
203                 println!(
204                     "Error: rustfmt version ({}) doesn't match the required version ({})",
205                     version, required_version,
206                 );
207                 return false;
208             }
209         }
210
211         true
212     }
213
214     /// Constructs a `Config` from the toml file specified at `file_path`.
215     ///
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`.
218     ///
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))
227     }
228
229     /// Resolves the config for input in `dir`.
230     ///
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).
235     ///
236     /// Returns the `Config` to use, and the path of the project file if there was
237     /// one.
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)
245             } else {
246                 dir.to_path_buf()
247             };
248
249             current = fs::canonicalize(current)?;
250
251             loop {
252                 match get_toml_path(&current) {
253                     Ok(Some(path)) => return Ok(Some(path)),
254                     Err(e) => return Err(e),
255                     _ => (),
256                 }
257
258                 // If the current directory has no parent, we're done searching.
259                 if !current.pop() {
260                     break;
261                 }
262             }
263
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));
268                 }
269             }
270
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));
276                 }
277             }
278
279             Ok(None)
280         }
281
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))),
285         }
286     }
287
288     pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
289         let parsed: ::toml::Value = toml
290             .parse()
291             .map_err(|e| format!("Could not parse TOML: {}", e))?;
292         let mut err = String::new();
293         let table = parsed
294             .as_table()
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);
299                 err.push_str(msg)
300             }
301         }
302         match parsed.try_into() {
303             Ok(parsed_config) => {
304                 if !err.is_empty() {
305                     eprint!("{}", err);
306                 }
307                 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
308             }
309             Err(e) => {
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.");
313                 Err(err)
314             }
315         }
316     }
317 }
318
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>,
323     options: Option<O>,
324 ) -> Result<(Config, Option<PathBuf>), Error> {
325     let over_ride = match options {
326         Some(ref opts) => config_path(opts)?,
327         None => None,
328     };
329
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)
334     } else {
335         Ok((Config::default(), None))
336     };
337
338     result.map(|(mut c, p)| {
339         if let Some(options) = options {
340             options.apply_to(&mut c);
341         }
342         (c, p)
343     })
344 }
345
346 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
347 //
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
355             // `rustfmt.toml`.
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.
359             Err(e) => {
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));
364                 }
365             }
366             _ => {}
367         }
368     }
369     Ok(None)
370 }
371
372 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
373     let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
374         Err(Error::new(
375             ErrorKind::NotFound,
376             format!(
377                 "Error: unable to find a config file for the given path: `{}`",
378                 path
379             ),
380         ))
381     };
382
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() {
390                 Ok(config_file_path)
391             } else {
392                 config_path_not_found(path.to_str().unwrap())
393             }
394         }
395         path => Ok(path.map(ToOwned::to_owned)),
396     }
397 }
398
399 #[cfg(test)]
400 mod test {
401     use super::*;
402     use std::str;
403
404     use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test};
405
406     #[allow(dead_code)]
407     mod mock {
408         use super::super::*;
409
410         create_config! {
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";
422
423             // merge_imports deprecation
424             imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
425                 "Merge imports";
426             merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
427
428             // Width Heuristics
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";
434
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.";
448
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";
452         }
453     }
454
455     #[test]
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);
462     }
463
464     #[test]
465     fn test_config_used_to_toml() {
466         let config = Config::default();
467
468         let merge_derives = config.merge_derives();
469         let skip_children = config.skip_children();
470
471         let used_options = config.used_options();
472         let toml = used_options.to_toml().unwrap();
473         assert_eq!(
474             toml,
475             format!(
476                 "merge_derives = {}\nskip_children = {}\n",
477                 merge_derives, skip_children,
478             )
479         );
480     }
481
482     #[test]
483     fn test_was_set() {
484         let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
485
486         assert_eq!(config.was_set().hard_tabs(), true);
487         assert_eq!(config.was_set().verbose(), false);
488     }
489
490     #[test]
491     fn test_print_docs_exclude_unstable() {
492         use self::mock::Config;
493
494         let mut output = Vec::new();
495         Config::print_docs(&mut output, false);
496
497         let s = str::from_utf8(&output).unwrap();
498
499         assert_eq!(s.contains("stable_option"), true);
500         assert_eq!(s.contains("unstable_option"), false);
501         assert_eq!(s.contains("(unstable)"), false);
502     }
503
504     #[test]
505     fn test_print_docs_include_unstable() {
506         use self::mock::Config;
507
508         let mut output = Vec::new();
509         Config::print_docs(&mut output, true);
510
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);
515     }
516
517     #[test]
518     fn test_dump_default_config() {
519         let default_config = format!(
520             r#"max_width = 100
521 hard_tabs = false
522 tab_spaces = 4
523 newline_style = "Auto"
524 indent_style = "Block"
525 use_small_heuristics = "Default"
526 fn_call_width = 60
527 attr_fn_like_width = 70
528 struct_lit_width = 18
529 struct_variant_width = 35
530 array_width = 60
531 chain_width = 60
532 single_line_if_else_max_width = 50
533 wrap_comments = false
534 format_code_in_doc_comments = false
535 comment_width = 80
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
575 edition = "2015"
576 version = "One"
577 inline_attribute_width = 0
578 format_generated_files = true
579 merge_derives = true
580 use_try_shorthand = false
581 use_field_init_shorthand = false
582 force_explicit_abi = true
583 condense_wildcard_suffixes = false
584 color = "Auto"
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
592 ignore = []
593 emit_mode = "Files"
594 make_backup = false
595 "#,
596             env!("CARGO_PKG_VERSION")
597         );
598         let toml = Config::default().all_options().to_toml().unwrap();
599         assert_eq!(&toml, &default_config);
600     }
601
602     #[stable_only_test]
603     #[test]
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);
609     }
610
611     #[nightly_only_test]
612     #[test]
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);
621     }
622
623     #[nightly_only_test]
624     #[test]
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);
629     }
630
631     #[cfg(test)]
632     mod deprecated_option_merge_imports {
633         use super::*;
634
635         #[nightly_only_test]
636         #[test]
637         fn test_old_option_set() {
638             let toml = r#"
639                 unstable_features = true
640                 merge_imports = true
641             "#;
642             let config = Config::from_toml(toml, Path::new("")).unwrap();
643             assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
644         }
645
646         #[nightly_only_test]
647         #[test]
648         fn test_both_set() {
649             let toml = r#"
650                 unstable_features = true
651                 merge_imports = true
652                 imports_granularity = "Preserve"
653             "#;
654             let config = Config::from_toml(toml, Path::new("")).unwrap();
655             assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
656         }
657
658         #[nightly_only_test]
659         #[test]
660         fn test_new_overridden() {
661             let toml = r#"
662                 unstable_features = true
663                 merge_imports = true
664             "#;
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);
668         }
669
670         #[nightly_only_test]
671         #[test]
672         fn test_old_overridden() {
673             let toml = r#"
674                 unstable_features = true
675                 imports_granularity = "Module"
676             "#;
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);
681         }
682     }
683
684     #[cfg(test)]
685     mod use_small_heuristics {
686         use super::*;
687
688         #[test]
689         fn test_default_sets_correct_widths() {
690             let toml = r#"
691                 use_small_heuristics = "Default"
692                 max_width = 200
693             "#;
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);
702         }
703
704         #[test]
705         fn test_max_sets_correct_widths() {
706             let toml = r#"
707                 use_small_heuristics = "Max"
708                 max_width = 120
709             "#;
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);
718         }
719
720         #[test]
721         fn test_off_sets_correct_widths() {
722             let toml = r#"
723                 use_small_heuristics = "Off"
724                 max_width = 100
725             "#;
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);
734         }
735
736         #[test]
737         fn test_override_works_with_default() {
738             let toml = r#"
739                 use_small_heuristics = "Default"
740                 array_width = 20
741                 attr_fn_like_width = 40
742                 chain_width = 20
743                 fn_call_width = 90
744                 single_line_if_else_max_width = 40
745                 struct_lit_width = 30
746                 struct_variant_width = 34
747             "#;
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);
756         }
757
758         #[test]
759         fn test_override_with_max() {
760             let toml = r#"
761                 use_small_heuristics = "Max"
762                 array_width = 20
763                 attr_fn_like_width = 40
764                 chain_width = 20
765                 fn_call_width = 90
766                 single_line_if_else_max_width = 40
767                 struct_lit_width = 30
768                 struct_variant_width = 34
769             "#;
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);
778         }
779
780         #[test]
781         fn test_override_with_off() {
782             let toml = r#"
783                 use_small_heuristics = "Off"
784                 array_width = 20
785                 attr_fn_like_width = 40
786                 chain_width = 20
787                 fn_call_width = 90
788                 single_line_if_else_max_width = 40
789                 struct_lit_width = 30
790                 struct_variant_width = 34
791             "#;
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);
800         }
801
802         #[test]
803         fn test_fn_call_width_config_exceeds_max_width() {
804             let toml = r#"
805                 max_width = 90
806                 fn_call_width = 95
807             "#;
808             let config = Config::from_toml(toml, Path::new("")).unwrap();
809             assert_eq!(config.fn_call_width(), 90);
810         }
811
812         #[test]
813         fn test_attr_fn_like_width_config_exceeds_max_width() {
814             let toml = r#"
815                 max_width = 80
816                 attr_fn_like_width = 90
817             "#;
818             let config = Config::from_toml(toml, Path::new("")).unwrap();
819             assert_eq!(config.attr_fn_like_width(), 80);
820         }
821
822         #[test]
823         fn test_struct_lit_config_exceeds_max_width() {
824             let toml = r#"
825                 max_width = 78
826                 struct_lit_width = 90
827             "#;
828             let config = Config::from_toml(toml, Path::new("")).unwrap();
829             assert_eq!(config.struct_lit_width(), 78);
830         }
831
832         #[test]
833         fn test_struct_variant_width_config_exceeds_max_width() {
834             let toml = r#"
835                 max_width = 80
836                 struct_variant_width = 90
837             "#;
838             let config = Config::from_toml(toml, Path::new("")).unwrap();
839             assert_eq!(config.struct_variant_width(), 80);
840         }
841
842         #[test]
843         fn test_array_width_config_exceeds_max_width() {
844             let toml = r#"
845                 max_width = 60
846                 array_width = 80
847             "#;
848             let config = Config::from_toml(toml, Path::new("")).unwrap();
849             assert_eq!(config.array_width(), 60);
850         }
851
852         #[test]
853         fn test_chain_width_config_exceeds_max_width() {
854             let toml = r#"
855                 max_width = 80
856                 chain_width = 90
857             "#;
858             let config = Config::from_toml(toml, Path::new("")).unwrap();
859             assert_eq!(config.chain_width(), 80);
860         }
861
862         #[test]
863         fn test_single_line_if_else_max_width_config_exceeds_max_width() {
864             let toml = r#"
865                 max_width = 70
866                 single_line_if_else_max_width = 90
867             "#;
868             let config = Config::from_toml(toml, Path::new("")).unwrap();
869             assert_eq!(config.single_line_if_else_max_width(), 70);
870         }
871
872         #[test]
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);
877         }
878
879         #[test]
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);
884         }
885
886         #[test]
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);
891         }
892
893         #[test]
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);
898         }
899
900         #[test]
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);
905         }
906
907         #[test]
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);
912         }
913
914         #[test]
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);
919         }
920     }
921 }