]> git.lizzy.rs Git - rust.git/blob - src/config/mod.rs
Merge commit '5ff7b632a95bac6955611d85040859128902c580' into sync-rustfmt-subtree
[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 regex::Regex;
9 use thiserror::Error;
10
11 use crate::config::config_type::ConfigType;
12 #[allow(unreachable_pub)]
13 pub use crate::config::file_lines::{FileLines, FileName, Range};
14 #[allow(unreachable_pub)]
15 pub use crate::config::lists::*;
16 #[allow(unreachable_pub)]
17 pub use crate::config::options::*;
18
19 #[macro_use]
20 pub(crate) mod config_type;
21 #[macro_use]
22 pub(crate) mod options;
23
24 pub(crate) mod file_lines;
25 pub(crate) mod license;
26 pub(crate) mod lists;
27
28 // This macro defines configuration options used in rustfmt. Each option
29 // is defined as follows:
30 //
31 // `name: value type, default value, is stable, description;`
32 create_config! {
33     // Fundamental stuff
34     max_width: usize, 100, true, "Maximum width of each line";
35     hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment";
36     tab_spaces: usize, 4, true, "Number of spaces per tab";
37     newline_style: NewlineStyle, NewlineStyle::Auto, true, "Unix or Windows line endings";
38     indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items";
39
40     // Width Heuristics
41     use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different \
42         formatting for items and expressions if they satisfy a heuristic notion of 'small'";
43     width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
44         "'small' heuristic values";
45     fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \
46         falling back to vertical formatting.";
47     attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \
48         attributes before falling back to vertical formatting.";
49     struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \
50         falling back to vertical formatting.";
51     struct_variant_width: usize, 35, true, "Maximum width in the body of a struct variant before \
52         falling back to vertical formatting.";
53     array_width: usize, 60, true,  "Maximum width of an array literal before falling \
54         back to vertical formatting.";
55     chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line.";
56     single_line_if_else_max_width: usize, 50, true, "Maximum line length for single line if-else \
57         expressions. A value of zero means always break if-else expressions.";
58
59     // Comments. macros, and strings
60     wrap_comments: bool, false, false, "Break comments to fit on the line";
61     format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments.";
62     comment_width: usize, 80, false,
63         "Maximum length of comments. No effect unless wrap_comments = true";
64     normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
65     normalize_doc_attributes: bool, false, false, "Normalize doc attributes as doc comments";
66     license_template_path: String, String::default(), false,
67         "Beginning of file must match license template";
68     format_strings: bool, false, false, "Format string literals where necessary";
69     format_macro_matchers: bool, false, false,
70         "Format the metavariable matching patterns in macros";
71     format_macro_bodies: bool, true, false, "Format the bodies of macros";
72     hex_literal_case: HexLiteralCase, HexLiteralCase::Preserve, false,
73         "Format hexadecimal integer literals";
74
75     // Single line expressions and items
76     empty_item_single_line: bool, true, false,
77         "Put empty-body functions and impls on a single line";
78     struct_lit_single_line: bool, true, false,
79         "Put small struct literals on a single line";
80     fn_single_line: bool, false, false, "Put single-expression functions on a single line";
81     where_single_line: bool, false, false, "Force where-clauses to be on a single line";
82
83     // Imports
84     imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports";
85     imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
86     imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
87         "Merge or split imports to the provided granularity";
88     group_imports: GroupImportsTactic, GroupImportsTactic::Preserve, false,
89         "Controls the strategy for how imports are grouped together";
90     merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
91
92     // Ordering
93     reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically";
94     reorder_modules: bool, true, true, "Reorder module statements alphabetically in group";
95     reorder_impl_items: bool, false, false, "Reorder impl items";
96
97     // Spaces around punctuation
98     type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
99         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
100     space_before_colon: bool, false, false, "Leave a space before the colon";
101     space_after_colon: bool, true, false, "Leave a space after the colon";
102     spaces_around_ranges: bool, false, false, "Put spaces around the  .. and ..= range operators";
103     binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
104         "Where to put a binary operator when a binary expression goes multiline";
105
106     // Misc.
107     remove_nested_parens: bool, true, true, "Remove nested parens";
108     combine_control_expr: bool, true, false, "Combine control expressions with function calls";
109     short_array_element_width_threshold: usize, 10, true,
110         "Width threshold for an array element to be considered short";
111     overflow_delimited_expr: bool, false, false,
112         "Allow trailing bracket/brace delimited expressions to overflow";
113     struct_field_align_threshold: usize, 0, false,
114         "Align struct fields if their diffs fits within threshold";
115     enum_discrim_align_threshold: usize, 0, false,
116         "Align enum variants discrims, if their diffs fit within threshold";
117     match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
118         the same line with the pattern of arms";
119     match_arm_leading_pipes: MatchArmLeadingPipe, MatchArmLeadingPipe::Never, true,
120         "Determines whether leading pipes are emitted on match arms";
121     force_multiline_blocks: bool, false, false,
122         "Force multiline closure bodies and match arms to be wrapped in a block";
123     fn_args_layout: Density, Density::Tall, true,
124         "Control the layout of arguments in a function";
125     brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
126     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
127         "Brace style for control flow constructs";
128     trailing_semicolon: bool, true, false,
129         "Add trailing semicolon after break, continue and return";
130     trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
131         "How to handle trailing commas for lists";
132     match_block_trailing_comma: bool, false, true,
133         "Put a trailing comma after a block based match arm (non-block arms are not affected)";
134     blank_lines_upper_bound: usize, 1, false,
135         "Maximum number of blank lines which can be put between items";
136     blank_lines_lower_bound: usize, 0, false,
137         "Minimum number of blank lines which must be put between items";
138     edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)";
139     version: Version, Version::One, false, "Version of formatting rules";
140     inline_attribute_width: usize, 0, false,
141         "Write an item and its attribute on the same line \
142         if their combined width is below a threshold";
143     format_generated_files: bool, true, false, "Format generated files";
144
145     // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
146     merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
147     use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand";
148     use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible";
149     force_explicit_abi: bool, true, true, "Always print the abi for extern items";
150     condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
151                                                      in tuple patterns";
152
153     // Control options (changes the operation of rustfmt, rather than the formatting)
154     color: Color, Color::Auto, false,
155         "What Color option to use when none is supplied: Always, Never, Auto";
156     required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
157         "Require a specific version of rustfmt";
158     unstable_features: bool, false, false,
159             "Enables unstable features. Only available on nightly channel";
160     disable_all_formatting: bool, false, true, "Don't reformat anything";
161     skip_children: bool, false, false, "Don't reformat out of line modules";
162     hide_parse_errors: bool, false, false, "Hide errors from the parser";
163     error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
164     error_on_unformatted: bool, false, false,
165         "Error if unable to get comments or string literals within max_width, \
166          or they are left with trailing whitespaces";
167     report_todo: ReportTactic, ReportTactic::Never, false,
168         "Report all, none or unnumbered occurrences of TODO in source file comments";
169     report_fixme: ReportTactic, ReportTactic::Never, false,
170         "Report all, none or unnumbered occurrences of FIXME in source file comments";
171     ignore: IgnoreList, IgnoreList::default(), false,
172         "Skip formatting the specified files and directories";
173
174     // Not user-facing
175     verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user";
176     file_lines: FileLines, FileLines::all(), false,
177         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
178          via the --file-lines option";
179     emit_mode: EmitMode, EmitMode::Files, false,
180         "What emit Mode to use when none is supplied";
181     make_backup: bool, false, false, "Backup changed files";
182     print_misformatted_file_names: bool, false, true,
183         "Prints the names of mismatched files that were formatted. Prints the names of \
184          files that would be formated when used with `--check` mode. ";
185 }
186
187 #[derive(Error, Debug)]
188 #[error("Could not output config: {0}")]
189 pub struct ToTomlError(toml::ser::Error);
190
191 impl PartialConfig {
192     pub fn to_toml(&self) -> Result<String, ToTomlError> {
193         // Non-user-facing options can't be specified in TOML
194         let mut cloned = self.clone();
195         cloned.file_lines = None;
196         cloned.verbose = None;
197         cloned.width_heuristics = None;
198         cloned.print_misformatted_file_names = None;
199         cloned.merge_imports = None;
200
201         ::toml::to_string(&cloned).map_err(ToTomlError)
202     }
203 }
204
205 impl Config {
206     pub(crate) fn version_meets_requirement(&self) -> bool {
207         if self.was_set().required_version() {
208             let version = env!("CARGO_PKG_VERSION");
209             let required_version = self.required_version();
210             if version != required_version {
211                 println!(
212                     "Error: rustfmt version ({}) doesn't match the required version ({})",
213                     version, required_version,
214                 );
215                 return false;
216             }
217         }
218
219         true
220     }
221
222     /// Constructs a `Config` from the toml file specified at `file_path`.
223     ///
224     /// This method only looks at the provided path, for a method that
225     /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
226     ///
227     /// Returns a `Config` if the config could be read and parsed from
228     /// the file, otherwise errors.
229     pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
230         let mut file = File::open(&file_path)?;
231         let mut toml = String::new();
232         file.read_to_string(&mut toml)?;
233         Config::from_toml(&toml, file_path.parent().unwrap())
234             .map_err(|err| Error::new(ErrorKind::InvalidData, err))
235     }
236
237     /// Resolves the config for input in `dir`.
238     ///
239     /// Searches for `rustfmt.toml` beginning with `dir`, and
240     /// recursively checking parents of `dir` if no config file is found.
241     /// If no config file exists in `dir` or in any parent, a
242     /// default `Config` will be returned (and the returned path will be empty).
243     ///
244     /// Returns the `Config` to use, and the path of the project file if there was
245     /// one.
246     pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
247         /// Try to find a project file in the given directory and its parents.
248         /// Returns the path of a the nearest project file if one exists,
249         /// or `None` if no project file was found.
250         fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
251             let mut current = if dir.is_relative() {
252                 env::current_dir()?.join(dir)
253             } else {
254                 dir.to_path_buf()
255             };
256
257             current = fs::canonicalize(current)?;
258
259             loop {
260                 match get_toml_path(&current) {
261                     Ok(Some(path)) => return Ok(Some(path)),
262                     Err(e) => return Err(e),
263                     _ => (),
264                 }
265
266                 // If the current directory has no parent, we're done searching.
267                 if !current.pop() {
268                     break;
269                 }
270             }
271
272             // If nothing was found, check in the home directory.
273             if let Some(home_dir) = dirs::home_dir() {
274                 if let Some(path) = get_toml_path(&home_dir)? {
275                     return Ok(Some(path));
276                 }
277             }
278
279             // If none was found ther either, check in the user's configuration directory.
280             if let Some(mut config_dir) = dirs::config_dir() {
281                 config_dir.push("rustfmt");
282                 if let Some(path) = get_toml_path(&config_dir)? {
283                     return Ok(Some(path));
284                 }
285             }
286
287             Ok(None)
288         }
289
290         match resolve_project_file(dir)? {
291             None => Ok((Config::default(), None)),
292             Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
293         }
294     }
295
296     pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
297         let parsed: ::toml::Value = toml
298             .parse()
299             .map_err(|e| format!("Could not parse TOML: {}", e))?;
300         let mut err = String::new();
301         let table = parsed
302             .as_table()
303             .ok_or_else(|| String::from("Parsed config was not table"))?;
304         for key in table.keys() {
305             if !Config::is_valid_name(key) {
306                 let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
307                 err.push_str(msg)
308             }
309         }
310         match parsed.try_into() {
311             Ok(parsed_config) => {
312                 if !err.is_empty() {
313                     eprint!("{}", err);
314                 }
315                 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
316             }
317             Err(e) => {
318                 err.push_str("Error: Decoding config file failed:\n");
319                 err.push_str(format!("{}\n", e).as_str());
320                 err.push_str("Please check your config file.");
321                 Err(err)
322             }
323         }
324     }
325 }
326
327 /// Loads a config by checking the client-supplied options and if appropriate, the
328 /// file system (including searching the file system for overrides).
329 pub fn load_config<O: CliOptions>(
330     file_path: Option<&Path>,
331     options: Option<O>,
332 ) -> Result<(Config, Option<PathBuf>), Error> {
333     let over_ride = match options {
334         Some(ref opts) => config_path(opts)?,
335         None => None,
336     };
337
338     let result = if let Some(over_ride) = over_ride {
339         Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
340     } else if let Some(file_path) = file_path {
341         Config::from_resolved_toml_path(file_path)
342     } else {
343         Ok((Config::default(), None))
344     };
345
346     result.map(|(mut c, p)| {
347         if let Some(options) = options {
348             options.apply_to(&mut c);
349         }
350         (c, p)
351     })
352 }
353
354 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
355 //
356 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
357 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
358     const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
359     for config_file_name in &CONFIG_FILE_NAMES {
360         let config_file = dir.join(config_file_name);
361         match fs::metadata(&config_file) {
362             // Only return if it's a file to handle the unlikely situation of a directory named
363             // `rustfmt.toml`.
364             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
365             // Return the error if it's something other than `NotFound`; otherwise we didn't
366             // find the project file yet, and continue searching.
367             Err(e) => {
368                 if e.kind() != ErrorKind::NotFound {
369                     let ctx = format!("Failed to get metadata for config file {:?}", &config_file);
370                     let err = anyhow::Error::new(e).context(ctx);
371                     return Err(Error::new(ErrorKind::Other, err));
372                 }
373             }
374             _ => {}
375         }
376     }
377     Ok(None)
378 }
379
380 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
381     let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
382         Err(Error::new(
383             ErrorKind::NotFound,
384             format!(
385                 "Error: unable to find a config file for the given path: `{}`",
386                 path
387             ),
388         ))
389     };
390
391     // Read the config_path and convert to parent dir if a file is provided.
392     // If a config file cannot be found from the given path, return error.
393     match options.config_path() {
394         Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
395         Some(path) if path.is_dir() => {
396             let config_file_path = get_toml_path(path)?;
397             if config_file_path.is_some() {
398                 Ok(config_file_path)
399             } else {
400                 config_path_not_found(path.to_str().unwrap())
401             }
402         }
403         path => Ok(path.map(ToOwned::to_owned)),
404     }
405 }
406
407 #[cfg(test)]
408 mod test {
409     use super::*;
410     use std::str;
411
412     use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test};
413
414     #[allow(dead_code)]
415     mod mock {
416         use super::super::*;
417
418         create_config! {
419             // Options that are used by the generated functions
420             max_width: usize, 100, true, "Maximum width of each line";
421             license_template_path: String, String::default(), false,
422                 "Beginning of file must match license template";
423             required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
424                 "Require a specific version of rustfmt.";
425             ignore: IgnoreList, IgnoreList::default(), false,
426                 "Skip formatting the specified files and directories.";
427             verbose: Verbosity, Verbosity::Normal, false,
428                 "How much to information to emit to the user";
429             file_lines: FileLines, FileLines::all(), false,
430                 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
431                     via the --file-lines option";
432
433             // merge_imports deprecation
434             imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
435                 "Merge imports";
436             merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
437
438             // Width Heuristics
439             use_small_heuristics: Heuristics, Heuristics::Default, true,
440                 "Whether to use different formatting for items and \
441                  expressions if they satisfy a heuristic notion of 'small'.";
442             width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
443                 "'small' heuristic values";
444
445             fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \
446                 falling back to vertical formatting.";
447             attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \
448                 attributes before falling back to vertical formatting.";
449             struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \
450                 falling back to vertical formatting.";
451             struct_variant_width: usize, 35, true, "Maximum width in the body of a struct \
452                 variant before falling back to vertical formatting.";
453             array_width: usize, 60, true,  "Maximum width of an array literal before falling \
454                 back to vertical formatting.";
455             chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line.";
456             single_line_if_else_max_width: usize, 50, true, "Maximum line length for single \
457                 line if-else expressions. A value of zero means always break if-else expressions.";
458
459             // Options that are used by the tests
460             stable_option: bool, false, true, "A stable option";
461             unstable_option: bool, false, false, "An unstable option";
462         }
463     }
464
465     #[test]
466     fn test_config_set() {
467         let mut config = Config::default();
468         config.set().verbose(Verbosity::Quiet);
469         assert_eq!(config.verbose(), Verbosity::Quiet);
470         config.set().verbose(Verbosity::Normal);
471         assert_eq!(config.verbose(), Verbosity::Normal);
472     }
473
474     #[test]
475     fn test_config_used_to_toml() {
476         let config = Config::default();
477
478         let merge_derives = config.merge_derives();
479         let skip_children = config.skip_children();
480
481         let used_options = config.used_options();
482         let toml = used_options.to_toml().unwrap();
483         assert_eq!(
484             toml,
485             format!(
486                 "merge_derives = {}\nskip_children = {}\n",
487                 merge_derives, skip_children,
488             )
489         );
490     }
491
492     #[test]
493     fn test_was_set() {
494         let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
495
496         assert_eq!(config.was_set().hard_tabs(), true);
497         assert_eq!(config.was_set().verbose(), false);
498     }
499
500     #[test]
501     fn test_print_docs_exclude_unstable() {
502         use self::mock::Config;
503
504         let mut output = Vec::new();
505         Config::print_docs(&mut output, false);
506
507         let s = str::from_utf8(&output).unwrap();
508
509         assert_eq!(s.contains("stable_option"), true);
510         assert_eq!(s.contains("unstable_option"), false);
511         assert_eq!(s.contains("(unstable)"), false);
512     }
513
514     #[test]
515     fn test_print_docs_include_unstable() {
516         use self::mock::Config;
517
518         let mut output = Vec::new();
519         Config::print_docs(&mut output, true);
520
521         let s = str::from_utf8(&output).unwrap();
522         assert_eq!(s.contains("stable_option"), true);
523         assert_eq!(s.contains("unstable_option"), true);
524         assert_eq!(s.contains("(unstable)"), true);
525     }
526
527     #[test]
528     fn test_empty_string_license_template_path() {
529         let toml = r#"license_template_path = """#;
530         let config = Config::from_toml(toml, Path::new("")).unwrap();
531         assert!(config.license_template.is_none());
532     }
533
534     #[nightly_only_test]
535     #[test]
536     fn test_valid_license_template_path() {
537         let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
538         let config = Config::from_toml(toml, Path::new("")).unwrap();
539         assert!(config.license_template.is_some());
540     }
541
542     #[nightly_only_test]
543     #[test]
544     fn test_override_existing_license_with_no_license() {
545         let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
546         let mut config = Config::from_toml(toml, Path::new("")).unwrap();
547         assert!(config.license_template.is_some());
548         config.override_value("license_template_path", "");
549         assert!(config.license_template.is_none());
550     }
551
552     #[test]
553     fn test_dump_default_config() {
554         let default_config = format!(
555             r#"max_width = 100
556 hard_tabs = false
557 tab_spaces = 4
558 newline_style = "Auto"
559 indent_style = "Block"
560 use_small_heuristics = "Default"
561 fn_call_width = 60
562 attr_fn_like_width = 70
563 struct_lit_width = 18
564 struct_variant_width = 35
565 array_width = 60
566 chain_width = 60
567 single_line_if_else_max_width = 50
568 wrap_comments = false
569 format_code_in_doc_comments = false
570 comment_width = 80
571 normalize_comments = false
572 normalize_doc_attributes = false
573 license_template_path = ""
574 format_strings = false
575 format_macro_matchers = false
576 format_macro_bodies = true
577 hex_literal_case = "Preserve"
578 empty_item_single_line = true
579 struct_lit_single_line = true
580 fn_single_line = false
581 where_single_line = false
582 imports_indent = "Block"
583 imports_layout = "Mixed"
584 imports_granularity = "Preserve"
585 group_imports = "Preserve"
586 reorder_imports = true
587 reorder_modules = true
588 reorder_impl_items = false
589 type_punctuation_density = "Wide"
590 space_before_colon = false
591 space_after_colon = true
592 spaces_around_ranges = false
593 binop_separator = "Front"
594 remove_nested_parens = true
595 combine_control_expr = true
596 short_array_element_width_threshold = 10
597 overflow_delimited_expr = false
598 struct_field_align_threshold = 0
599 enum_discrim_align_threshold = 0
600 match_arm_blocks = true
601 match_arm_leading_pipes = "Never"
602 force_multiline_blocks = false
603 fn_args_layout = "Tall"
604 brace_style = "SameLineWhere"
605 control_brace_style = "AlwaysSameLine"
606 trailing_semicolon = true
607 trailing_comma = "Vertical"
608 match_block_trailing_comma = false
609 blank_lines_upper_bound = 1
610 blank_lines_lower_bound = 0
611 edition = "2015"
612 version = "One"
613 inline_attribute_width = 0
614 format_generated_files = true
615 merge_derives = true
616 use_try_shorthand = false
617 use_field_init_shorthand = false
618 force_explicit_abi = true
619 condense_wildcard_suffixes = false
620 color = "Auto"
621 required_version = "{}"
622 unstable_features = false
623 disable_all_formatting = false
624 skip_children = false
625 hide_parse_errors = false
626 error_on_line_overflow = false
627 error_on_unformatted = false
628 report_todo = "Never"
629 report_fixme = "Never"
630 ignore = []
631 emit_mode = "Files"
632 make_backup = false
633 "#,
634             env!("CARGO_PKG_VERSION")
635         );
636         let toml = Config::default().all_options().to_toml().unwrap();
637         assert_eq!(&toml, &default_config);
638     }
639
640     #[stable_only_test]
641     #[test]
642     fn test_as_not_nightly_channel() {
643         let mut config = Config::default();
644         assert_eq!(config.was_set().unstable_features(), false);
645         config.set().unstable_features(true);
646         assert_eq!(config.was_set().unstable_features(), false);
647     }
648
649     #[nightly_only_test]
650     #[test]
651     fn test_as_nightly_channel() {
652         let mut config = Config::default();
653         config.set().unstable_features(true);
654         // When we don't set the config from toml or command line options it
655         // doesn't get marked as set by the user.
656         assert_eq!(config.was_set().unstable_features(), false);
657         config.set().unstable_features(true);
658         assert_eq!(config.unstable_features(), true);
659     }
660
661     #[nightly_only_test]
662     #[test]
663     fn test_unstable_from_toml() {
664         let config = Config::from_toml("unstable_features = true", Path::new("")).unwrap();
665         assert_eq!(config.was_set().unstable_features(), true);
666         assert_eq!(config.unstable_features(), true);
667     }
668
669     #[cfg(test)]
670     mod deprecated_option_merge_imports {
671         use super::*;
672
673         #[nightly_only_test]
674         #[test]
675         fn test_old_option_set() {
676             let toml = r#"
677                 unstable_features = true
678                 merge_imports = true
679             "#;
680             let config = Config::from_toml(toml, Path::new("")).unwrap();
681             assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
682         }
683
684         #[nightly_only_test]
685         #[test]
686         fn test_both_set() {
687             let toml = r#"
688                 unstable_features = true
689                 merge_imports = true
690                 imports_granularity = "Preserve"
691             "#;
692             let config = Config::from_toml(toml, Path::new("")).unwrap();
693             assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
694         }
695
696         #[nightly_only_test]
697         #[test]
698         fn test_new_overridden() {
699             let toml = r#"
700                 unstable_features = true
701                 merge_imports = true
702             "#;
703             let mut config = Config::from_toml(toml, Path::new("")).unwrap();
704             config.override_value("imports_granularity", "Preserve");
705             assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
706         }
707
708         #[nightly_only_test]
709         #[test]
710         fn test_old_overridden() {
711             let toml = r#"
712                 unstable_features = true
713                 imports_granularity = "Module"
714             "#;
715             let mut config = Config::from_toml(toml, Path::new("")).unwrap();
716             config.override_value("merge_imports", "true");
717             // no effect: the new option always takes precedence
718             assert_eq!(config.imports_granularity(), ImportGranularity::Module);
719         }
720     }
721
722     #[cfg(test)]
723     mod use_small_heuristics {
724         use super::*;
725
726         #[test]
727         fn test_default_sets_correct_widths() {
728             let toml = r#"
729                 use_small_heuristics = "Default"
730                 max_width = 200
731             "#;
732             let config = Config::from_toml(toml, Path::new("")).unwrap();
733             assert_eq!(config.array_width(), 120);
734             assert_eq!(config.attr_fn_like_width(), 140);
735             assert_eq!(config.chain_width(), 120);
736             assert_eq!(config.fn_call_width(), 120);
737             assert_eq!(config.single_line_if_else_max_width(), 100);
738             assert_eq!(config.struct_lit_width(), 36);
739             assert_eq!(config.struct_variant_width(), 70);
740         }
741
742         #[test]
743         fn test_max_sets_correct_widths() {
744             let toml = r#"
745                 use_small_heuristics = "Max"
746                 max_width = 120
747             "#;
748             let config = Config::from_toml(toml, Path::new("")).unwrap();
749             assert_eq!(config.array_width(), 120);
750             assert_eq!(config.attr_fn_like_width(), 120);
751             assert_eq!(config.chain_width(), 120);
752             assert_eq!(config.fn_call_width(), 120);
753             assert_eq!(config.single_line_if_else_max_width(), 120);
754             assert_eq!(config.struct_lit_width(), 120);
755             assert_eq!(config.struct_variant_width(), 120);
756         }
757
758         #[test]
759         fn test_off_sets_correct_widths() {
760             let toml = r#"
761                 use_small_heuristics = "Off"
762                 max_width = 100
763             "#;
764             let config = Config::from_toml(toml, Path::new("")).unwrap();
765             assert_eq!(config.array_width(), usize::max_value());
766             assert_eq!(config.attr_fn_like_width(), usize::max_value());
767             assert_eq!(config.chain_width(), usize::max_value());
768             assert_eq!(config.fn_call_width(), usize::max_value());
769             assert_eq!(config.single_line_if_else_max_width(), 0);
770             assert_eq!(config.struct_lit_width(), 0);
771             assert_eq!(config.struct_variant_width(), 0);
772         }
773
774         #[test]
775         fn test_override_works_with_default() {
776             let toml = r#"
777                 use_small_heuristics = "Default"
778                 array_width = 20
779                 attr_fn_like_width = 40
780                 chain_width = 20
781                 fn_call_width = 90
782                 single_line_if_else_max_width = 40
783                 struct_lit_width = 30
784                 struct_variant_width = 34
785             "#;
786             let config = Config::from_toml(toml, Path::new("")).unwrap();
787             assert_eq!(config.array_width(), 20);
788             assert_eq!(config.attr_fn_like_width(), 40);
789             assert_eq!(config.chain_width(), 20);
790             assert_eq!(config.fn_call_width(), 90);
791             assert_eq!(config.single_line_if_else_max_width(), 40);
792             assert_eq!(config.struct_lit_width(), 30);
793             assert_eq!(config.struct_variant_width(), 34);
794         }
795
796         #[test]
797         fn test_override_with_max() {
798             let toml = r#"
799                 use_small_heuristics = "Max"
800                 array_width = 20
801                 attr_fn_like_width = 40
802                 chain_width = 20
803                 fn_call_width = 90
804                 single_line_if_else_max_width = 40
805                 struct_lit_width = 30
806                 struct_variant_width = 34
807             "#;
808             let config = Config::from_toml(toml, Path::new("")).unwrap();
809             assert_eq!(config.array_width(), 20);
810             assert_eq!(config.attr_fn_like_width(), 40);
811             assert_eq!(config.chain_width(), 20);
812             assert_eq!(config.fn_call_width(), 90);
813             assert_eq!(config.single_line_if_else_max_width(), 40);
814             assert_eq!(config.struct_lit_width(), 30);
815             assert_eq!(config.struct_variant_width(), 34);
816         }
817
818         #[test]
819         fn test_override_with_off() {
820             let toml = r#"
821                 use_small_heuristics = "Off"
822                 array_width = 20
823                 attr_fn_like_width = 40
824                 chain_width = 20
825                 fn_call_width = 90
826                 single_line_if_else_max_width = 40
827                 struct_lit_width = 30
828                 struct_variant_width = 34
829             "#;
830             let config = Config::from_toml(toml, Path::new("")).unwrap();
831             assert_eq!(config.array_width(), 20);
832             assert_eq!(config.attr_fn_like_width(), 40);
833             assert_eq!(config.chain_width(), 20);
834             assert_eq!(config.fn_call_width(), 90);
835             assert_eq!(config.single_line_if_else_max_width(), 40);
836             assert_eq!(config.struct_lit_width(), 30);
837             assert_eq!(config.struct_variant_width(), 34);
838         }
839
840         #[test]
841         fn test_fn_call_width_config_exceeds_max_width() {
842             let toml = r#"
843                 max_width = 90
844                 fn_call_width = 95
845             "#;
846             let config = Config::from_toml(toml, Path::new("")).unwrap();
847             assert_eq!(config.fn_call_width(), 90);
848         }
849
850         #[test]
851         fn test_attr_fn_like_width_config_exceeds_max_width() {
852             let toml = r#"
853                 max_width = 80
854                 attr_fn_like_width = 90
855             "#;
856             let config = Config::from_toml(toml, Path::new("")).unwrap();
857             assert_eq!(config.attr_fn_like_width(), 80);
858         }
859
860         #[test]
861         fn test_struct_lit_config_exceeds_max_width() {
862             let toml = r#"
863                 max_width = 78
864                 struct_lit_width = 90
865             "#;
866             let config = Config::from_toml(toml, Path::new("")).unwrap();
867             assert_eq!(config.struct_lit_width(), 78);
868         }
869
870         #[test]
871         fn test_struct_variant_width_config_exceeds_max_width() {
872             let toml = r#"
873                 max_width = 80
874                 struct_variant_width = 90
875             "#;
876             let config = Config::from_toml(toml, Path::new("")).unwrap();
877             assert_eq!(config.struct_variant_width(), 80);
878         }
879
880         #[test]
881         fn test_array_width_config_exceeds_max_width() {
882             let toml = r#"
883                 max_width = 60
884                 array_width = 80
885             "#;
886             let config = Config::from_toml(toml, Path::new("")).unwrap();
887             assert_eq!(config.array_width(), 60);
888         }
889
890         #[test]
891         fn test_chain_width_config_exceeds_max_width() {
892             let toml = r#"
893                 max_width = 80
894                 chain_width = 90
895             "#;
896             let config = Config::from_toml(toml, Path::new("")).unwrap();
897             assert_eq!(config.chain_width(), 80);
898         }
899
900         #[test]
901         fn test_single_line_if_else_max_width_config_exceeds_max_width() {
902             let toml = r#"
903                 max_width = 70
904                 single_line_if_else_max_width = 90
905             "#;
906             let config = Config::from_toml(toml, Path::new("")).unwrap();
907             assert_eq!(config.single_line_if_else_max_width(), 70);
908         }
909
910         #[test]
911         fn test_override_fn_call_width_exceeds_max_width() {
912             let mut config = Config::default();
913             config.override_value("fn_call_width", "101");
914             assert_eq!(config.fn_call_width(), 100);
915         }
916
917         #[test]
918         fn test_override_attr_fn_like_width_exceeds_max_width() {
919             let mut config = Config::default();
920             config.override_value("attr_fn_like_width", "101");
921             assert_eq!(config.attr_fn_like_width(), 100);
922         }
923
924         #[test]
925         fn test_override_struct_lit_exceeds_max_width() {
926             let mut config = Config::default();
927             config.override_value("struct_lit_width", "101");
928             assert_eq!(config.struct_lit_width(), 100);
929         }
930
931         #[test]
932         fn test_override_struct_variant_width_exceeds_max_width() {
933             let mut config = Config::default();
934             config.override_value("struct_variant_width", "101");
935             assert_eq!(config.struct_variant_width(), 100);
936         }
937
938         #[test]
939         fn test_override_array_width_exceeds_max_width() {
940             let mut config = Config::default();
941             config.override_value("array_width", "101");
942             assert_eq!(config.array_width(), 100);
943         }
944
945         #[test]
946         fn test_override_chain_width_exceeds_max_width() {
947             let mut config = Config::default();
948             config.override_value("chain_width", "101");
949             assert_eq!(config.chain_width(), 100);
950         }
951
952         #[test]
953         fn test_override_single_line_if_else_max_width_exceeds_max_width() {
954             let mut config = Config::default();
955             config.override_value("single_line_if_else_max_width", "101");
956             assert_eq!(config.single_line_if_else_max_width(), 100);
957         }
958     }
959 }