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