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