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