]> git.lizzy.rs Git - rust.git/blob - src/config/mod.rs
deps: apply upstream rustc-* changes
[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
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 license;
25 pub(crate) mod lists;
26
27 // This macro defines configuration options used in rustfmt. Each option
28 // is defined as follows:
29 //
30 // `name: value type, default value, is stable, description;`
31 create_config! {
32     // Fundamental stuff
33     max_width: usize, 100, true, "Maximum width of each line";
34     hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment";
35     tab_spaces: usize, 4, true, "Number of spaces per tab";
36     newline_style: NewlineStyle, NewlineStyle::Auto, true, "Unix or Windows line endings";
37     use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different \
38         formatting for items and expressions if they satisfy a heuristic notion of 'small'";
39     indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items";
40
41     // Comments. macros, and strings
42     wrap_comments: bool, false, false, "Break comments to fit on the line";
43     format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments.";
44     comment_width: usize, 80, false,
45         "Maximum length of comments. No effect unless wrap_comments = true";
46     normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
47     normalize_doc_attributes: bool, false, false, "Normalize doc attributes as doc comments";
48     license_template_path: String, String::default(), false,
49         "Beginning of file must match license template";
50     format_strings: bool, false, false, "Format string literals where necessary";
51     format_macro_matchers: bool, false, false,
52         "Format the metavariable matching patterns in macros";
53     format_macro_bodies: bool, true, false, "Format the bodies of macros";
54
55     // Single line expressions and items
56     empty_item_single_line: bool, true, false,
57         "Put empty-body functions and impls on a single line";
58     struct_lit_single_line: bool, true, false,
59         "Put small struct literals on a single line";
60     fn_single_line: bool, false, false, "Put single-expression functions on a single line";
61     where_single_line: bool, false, false, "Force where-clauses to be on a single line";
62
63     // Imports
64     imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports";
65     imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
66     merge_imports: bool, false, false, "Merge imports";
67
68     // Ordering
69     reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically";
70     reorder_modules: bool, true, true, "Reorder module statements alphabetically in group";
71     reorder_impl_items: bool, false, false, "Reorder impl items";
72
73     // Spaces around punctuation
74     type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
75         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
76     space_before_colon: bool, false, false, "Leave a space before the colon";
77     space_after_colon: bool, true, false, "Leave a space after the colon";
78     spaces_around_ranges: bool, false, false, "Put spaces around the  .. and ..= range operators";
79     binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
80         "Where to put a binary operator when a binary expression goes multiline";
81
82     // Misc.
83     remove_nested_parens: bool, true, true, "Remove nested parens";
84     combine_control_expr: bool, true, false, "Combine control expressions with function calls";
85     overflow_delimited_expr: bool, false, false,
86         "Allow trailing bracket/brace delimited expressions to overflow";
87     struct_field_align_threshold: usize, 0, false,
88         "Align struct fields if their diffs fits within threshold";
89     enum_discrim_align_threshold: usize, 0, false,
90         "Align enum variants discrims, if their diffs fit within threshold";
91     match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
92         the same line with the pattern of arms";
93     force_multiline_blocks: bool, false, false,
94         "Force multiline closure bodies and match arms to be wrapped in a block";
95     fn_args_layout: Density, Density::Tall, true,
96         "Control the layout of arguments in a function";
97     brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
98     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
99         "Brace style for control flow constructs";
100     trailing_semicolon: bool, true, false,
101         "Add trailing semicolon after break, continue and return";
102     trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
103         "How to handle trailing commas for lists";
104     match_block_trailing_comma: bool, false, false,
105         "Put a trailing comma after a block based match arm (non-block arms are not affected)";
106     blank_lines_upper_bound: usize, 1, false,
107         "Maximum number of blank lines which can be put between items";
108     blank_lines_lower_bound: usize, 0, false,
109         "Minimum number of blank lines which must be put between items";
110     edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)";
111     version: Version, Version::One, false, "Version of formatting rules";
112     inline_attribute_width: usize, 0, false,
113         "Write an item and its attribute on the same line \
114         if their combined width is below a threshold";
115
116     // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
117     merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
118     use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand";
119     use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible";
120     force_explicit_abi: bool, true, true, "Always print the abi for extern items";
121     condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
122                                                      in tuple patterns";
123
124     // Control options (changes the operation of rustfmt, rather than the formatting)
125     color: Color, Color::Auto, false,
126         "What Color option to use when none is supplied: Always, Never, Auto";
127     required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
128         "Require a specific version of rustfmt";
129     unstable_features: bool, false, false,
130             "Enables unstable features. Only available on nightly channel";
131     disable_all_formatting: bool, false, false, "Don't reformat anything";
132     skip_children: bool, false, false, "Don't reformat out of line modules";
133     hide_parse_errors: bool, false, false, "Hide errors from the parser";
134     error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
135     error_on_unformatted: bool, false, false,
136         "Error if unable to get comments or string literals within max_width, \
137          or they are left with trailing whitespaces";
138     report_todo: ReportTactic, ReportTactic::Never, false,
139         "Report all, none or unnumbered occurrences of TODO in source file comments";
140     report_fixme: ReportTactic, ReportTactic::Never, false,
141         "Report all, none or unnumbered occurrences of FIXME in source file comments";
142     ignore: IgnoreList, IgnoreList::default(), false,
143         "Skip formatting the specified files and directories";
144
145     // Not user-facing
146     verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user";
147     file_lines: FileLines, FileLines::all(), false,
148         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
149          via the --file-lines option";
150     width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
151         "'small' heuristic values";
152     emit_mode: EmitMode, EmitMode::Files, false,
153         "What emit Mode to use when none is supplied";
154     make_backup: bool, false, false, "Backup changed files";
155     print_misformatted_file_names: bool, false, true,
156         "Prints the names of mismatched files that were formatted. Prints the names of \
157          files that would be formated when used with `--check` mode. ";
158 }
159
160 impl PartialConfig {
161     pub fn to_toml(&self) -> Result<String, String> {
162         // Non-user-facing options can't be specified in TOML
163         let mut cloned = self.clone();
164         cloned.file_lines = None;
165         cloned.verbose = None;
166         cloned.width_heuristics = None;
167         cloned.print_misformatted_file_names = None;
168
169         ::toml::to_string(&cloned).map_err(|e| format!("Could not output config: {}", e))
170     }
171 }
172
173 impl Config {
174     pub(crate) fn version_meets_requirement(&self) -> bool {
175         if self.was_set().required_version() {
176             let version = env!("CARGO_PKG_VERSION");
177             let required_version = self.required_version();
178             if version != required_version {
179                 println!(
180                     "Error: rustfmt version ({}) doesn't match the required version ({})",
181                     version, required_version,
182                 );
183                 return false;
184             }
185         }
186
187         true
188     }
189
190     /// Constructs a `Config` from the toml file specified at `file_path`.
191     ///
192     /// This method only looks at the provided path, for a method that
193     /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
194     ///
195     /// Returns a `Config` if the config could be read and parsed from
196     /// the file, otherwise errors.
197     pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
198         let mut file = File::open(&file_path)?;
199         let mut toml = String::new();
200         file.read_to_string(&mut toml)?;
201         Config::from_toml(&toml, file_path.parent().unwrap())
202             .map_err(|err| Error::new(ErrorKind::InvalidData, err))
203     }
204
205     /// Resolves the config for input in `dir`.
206     ///
207     /// Searches for `rustfmt.toml` beginning with `dir`, and
208     /// recursively checking parents of `dir` if no config file is found.
209     /// If no config file exists in `dir` or in any parent, a
210     /// default `Config` will be returned (and the returned path will be empty).
211     ///
212     /// Returns the `Config` to use, and the path of the project file if there was
213     /// one.
214     pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
215         /// Try to find a project file in the given directory and its parents.
216         /// Returns the path of a the nearest project file if one exists,
217         /// or `None` if no project file was found.
218         fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
219             let mut current = if dir.is_relative() {
220                 env::current_dir()?.join(dir)
221             } else {
222                 dir.to_path_buf()
223             };
224
225             current = fs::canonicalize(current)?;
226
227             loop {
228                 match get_toml_path(&current) {
229                     Ok(Some(path)) => return Ok(Some(path)),
230                     Err(e) => return Err(e),
231                     _ => (),
232                 }
233
234                 // If the current directory has no parent, we're done searching.
235                 if !current.pop() {
236                     break;
237                 }
238             }
239
240             // If nothing was found, check in the home directory.
241             if let Some(home_dir) = dirs::home_dir() {
242                 if let Some(path) = get_toml_path(&home_dir)? {
243                     return Ok(Some(path));
244                 }
245             }
246
247             // If none was found ther either, check in the user's configuration directory.
248             if let Some(mut config_dir) = dirs::config_dir() {
249                 config_dir.push("rustfmt");
250                 if let Some(path) = get_toml_path(&config_dir)? {
251                     return Ok(Some(path));
252                 }
253             }
254
255             Ok(None)
256         }
257
258         match resolve_project_file(dir)? {
259             None => Ok((Config::default(), None)),
260             Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
261         }
262     }
263
264     pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
265         let parsed: ::toml::Value = toml
266             .parse()
267             .map_err(|e| format!("Could not parse TOML: {}", e))?;
268         let mut err = String::new();
269         let table = parsed
270             .as_table()
271             .ok_or_else(|| String::from("Parsed config was not table"))?;
272         for key in table.keys() {
273             if !Config::is_valid_name(key) {
274                 let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
275                 err.push_str(msg)
276             }
277         }
278         match parsed.try_into() {
279             Ok(parsed_config) => {
280                 if !err.is_empty() {
281                     eprint!("{}", err);
282                 }
283                 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
284             }
285             Err(e) => {
286                 err.push_str("Error: Decoding config file failed:\n");
287                 err.push_str(format!("{}\n", e).as_str());
288                 err.push_str("Please check your config file.");
289                 Err(err)
290             }
291         }
292     }
293 }
294
295 /// Loads a config by checking the client-supplied options and if appropriate, the
296 /// file system (including searching the file system for overrides).
297 pub fn load_config<O: CliOptions>(
298     file_path: Option<&Path>,
299     options: Option<O>,
300 ) -> Result<(Config, Option<PathBuf>), Error> {
301     let over_ride = match options {
302         Some(ref opts) => config_path(opts)?,
303         None => None,
304     };
305
306     let result = if let Some(over_ride) = over_ride {
307         Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
308     } else if let Some(file_path) = file_path {
309         Config::from_resolved_toml_path(file_path)
310     } else {
311         Ok((Config::default(), None))
312     };
313
314     result.map(|(mut c, p)| {
315         if let Some(options) = options {
316             options.apply_to(&mut c);
317         }
318         (c, p)
319     })
320 }
321
322 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
323 //
324 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
325 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
326     const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
327     for config_file_name in &CONFIG_FILE_NAMES {
328         let config_file = dir.join(config_file_name);
329         match fs::metadata(&config_file) {
330             // Only return if it's a file to handle the unlikely situation of a directory named
331             // `rustfmt.toml`.
332             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
333             // Return the error if it's something other than `NotFound`; otherwise we didn't
334             // find the project file yet, and continue searching.
335             Err(e) => {
336                 if e.kind() != ErrorKind::NotFound {
337                     return Err(e);
338                 }
339             }
340             _ => {}
341         }
342     }
343     Ok(None)
344 }
345
346 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
347     let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
348         Err(Error::new(
349             ErrorKind::NotFound,
350             format!(
351                 "Error: unable to find a config file for the given path: `{}`",
352                 path
353             ),
354         ))
355     };
356
357     // Read the config_path and convert to parent dir if a file is provided.
358     // If a config file cannot be found from the given path, return error.
359     match options.config_path() {
360         Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
361         Some(path) if path.is_dir() => {
362             let config_file_path = get_toml_path(path)?;
363             if config_file_path.is_some() {
364                 Ok(config_file_path)
365             } else {
366                 config_path_not_found(path.to_str().unwrap())
367             }
368         }
369         path => Ok(path.map(ToOwned::to_owned)),
370     }
371 }
372
373 #[cfg(test)]
374 mod test {
375     use super::*;
376     use std::str;
377
378     #[allow(dead_code)]
379     mod mock {
380         use super::super::*;
381
382         create_config! {
383             // Options that are used by the generated functions
384             max_width: usize, 100, true, "Maximum width of each line";
385             use_small_heuristics: Heuristics, Heuristics::Default, true,
386                 "Whether to use different formatting for items and \
387                  expressions if they satisfy a heuristic notion of 'small'.";
388             license_template_path: String, String::default(), false,
389                 "Beginning of file must match license template";
390             required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
391                 "Require a specific version of rustfmt.";
392             ignore: IgnoreList, IgnoreList::default(), false,
393                 "Skip formatting the specified files and directories.";
394             verbose: Verbosity, Verbosity::Normal, false,
395                 "How much to information to emit to the user";
396             file_lines: FileLines, FileLines::all(), false,
397                 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
398                     via the --file-lines option";
399             width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
400                 "'small' heuristic values";
401
402             // Options that are used by the tests
403             stable_option: bool, false, true, "A stable option";
404             unstable_option: bool, false, false, "An unstable option";
405         }
406     }
407
408     #[test]
409     fn test_config_set() {
410         let mut config = Config::default();
411         config.set().verbose(Verbosity::Quiet);
412         assert_eq!(config.verbose(), Verbosity::Quiet);
413         config.set().verbose(Verbosity::Normal);
414         assert_eq!(config.verbose(), Verbosity::Normal);
415     }
416
417     #[test]
418     fn test_config_used_to_toml() {
419         let config = Config::default();
420
421         let merge_derives = config.merge_derives();
422         let skip_children = config.skip_children();
423
424         let used_options = config.used_options();
425         let toml = used_options.to_toml().unwrap();
426         assert_eq!(
427             toml,
428             format!(
429                 "merge_derives = {}\nskip_children = {}\n",
430                 merge_derives, skip_children,
431             )
432         );
433     }
434
435     #[test]
436     fn test_was_set() {
437         let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
438
439         assert_eq!(config.was_set().hard_tabs(), true);
440         assert_eq!(config.was_set().verbose(), false);
441     }
442
443     #[test]
444     fn test_print_docs_exclude_unstable() {
445         use self::mock::Config;
446
447         let mut output = Vec::new();
448         Config::print_docs(&mut output, false);
449
450         let s = str::from_utf8(&output).unwrap();
451
452         assert_eq!(s.contains("stable_option"), true);
453         assert_eq!(s.contains("unstable_option"), false);
454         assert_eq!(s.contains("(unstable)"), false);
455     }
456
457     #[test]
458     fn test_print_docs_include_unstable() {
459         use self::mock::Config;
460
461         let mut output = Vec::new();
462         Config::print_docs(&mut output, true);
463
464         let s = str::from_utf8(&output).unwrap();
465         assert_eq!(s.contains("stable_option"), true);
466         assert_eq!(s.contains("unstable_option"), true);
467         assert_eq!(s.contains("(unstable)"), true);
468     }
469
470     #[test]
471     fn test_empty_string_license_template_path() {
472         let toml = r#"license_template_path = """#;
473         let config = Config::from_toml(toml, Path::new("")).unwrap();
474         assert!(config.license_template.is_none());
475     }
476
477     #[test]
478     fn test_valid_license_template_path() {
479         let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
480         let config = Config::from_toml(toml, Path::new("")).unwrap();
481         assert!(config.license_template.is_some());
482     }
483
484     #[test]
485     fn test_dump_default_config() {
486         let default_config = format!(
487             r#"max_width = 100
488 hard_tabs = false
489 tab_spaces = 4
490 newline_style = "Auto"
491 use_small_heuristics = "Default"
492 indent_style = "Block"
493 wrap_comments = false
494 format_code_in_doc_comments = false
495 comment_width = 80
496 normalize_comments = false
497 normalize_doc_attributes = false
498 license_template_path = ""
499 format_strings = false
500 format_macro_matchers = false
501 format_macro_bodies = true
502 empty_item_single_line = true
503 struct_lit_single_line = true
504 fn_single_line = false
505 where_single_line = false
506 imports_indent = "Block"
507 imports_layout = "Mixed"
508 merge_imports = false
509 reorder_imports = true
510 reorder_modules = true
511 reorder_impl_items = false
512 type_punctuation_density = "Wide"
513 space_before_colon = false
514 space_after_colon = true
515 spaces_around_ranges = false
516 binop_separator = "Front"
517 remove_nested_parens = true
518 combine_control_expr = true
519 overflow_delimited_expr = false
520 struct_field_align_threshold = 0
521 enum_discrim_align_threshold = 0
522 match_arm_blocks = true
523 force_multiline_blocks = false
524 fn_args_layout = "Tall"
525 brace_style = "SameLineWhere"
526 control_brace_style = "AlwaysSameLine"
527 trailing_semicolon = true
528 trailing_comma = "Vertical"
529 match_block_trailing_comma = false
530 blank_lines_upper_bound = 1
531 blank_lines_lower_bound = 0
532 edition = "2015"
533 version = "One"
534 inline_attribute_width = 0
535 merge_derives = true
536 use_try_shorthand = false
537 use_field_init_shorthand = false
538 force_explicit_abi = true
539 condense_wildcard_suffixes = false
540 color = "Auto"
541 required_version = "{}"
542 unstable_features = false
543 disable_all_formatting = false
544 skip_children = false
545 hide_parse_errors = false
546 error_on_line_overflow = false
547 error_on_unformatted = false
548 report_todo = "Never"
549 report_fixme = "Never"
550 ignore = []
551 emit_mode = "Files"
552 make_backup = false
553 "#,
554             env!("CARGO_PKG_VERSION")
555         );
556         let toml = Config::default().all_options().to_toml().unwrap();
557         assert_eq!(&toml, &default_config);
558     }
559
560     // FIXME(#2183): these tests cannot be run in parallel because they use env vars.
561     // #[test]
562     // fn test_as_not_nightly_channel() {
563     //     let mut config = Config::default();
564     //     assert_eq!(config.was_set().unstable_features(), false);
565     //     config.set().unstable_features(true);
566     //     assert_eq!(config.was_set().unstable_features(), false);
567     // }
568
569     // #[test]
570     // fn test_as_nightly_channel() {
571     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
572     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
573     //     let mut config = Config::default();
574     //     config.set().unstable_features(true);
575     //     assert_eq!(config.was_set().unstable_features(), false);
576     //     config.set().unstable_features(true);
577     //     assert_eq!(config.unstable_features(), true);
578     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
579     // }
580
581     // #[test]
582     // fn test_unstable_from_toml() {
583     //     let mut config = Config::from_toml("unstable_features = true").unwrap();
584     //     assert_eq!(config.was_set().unstable_features(), false);
585     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
586     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
587     //     config = Config::from_toml("unstable_features = true").unwrap();
588     //     assert_eq!(config.was_set().unstable_features(), true);
589     //     assert_eq!(config.unstable_features(), true);
590     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
591     // }
592 }