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