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