]> git.lizzy.rs Git - rust.git/blob - src/config/mod.rs
Merge pull request #2836 from topecongiro/async-closure
[rust.git] / src / config / mod.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use regex::Regex;
12 use std::cell::Cell;
13 use std::default::Default;
14 use std::fs::File;
15 use std::io::{Error, ErrorKind, Read};
16 use std::path::{Path, PathBuf};
17 use std::{env, fs};
18
19 use config::config_type::ConfigType;
20 pub use config::file_lines::{FileLines, FileName, Range};
21 pub use config::lists::*;
22 pub use config::options::*;
23
24 #[macro_use]
25 pub mod config_type;
26 #[macro_use]
27 pub mod options;
28
29 pub mod file_lines;
30 pub mod license;
31 pub mod lists;
32 pub mod summary;
33
34 /// This macro defines configuration options used in rustfmt. Each option
35 /// is defined as follows:
36 ///
37 /// `name: value type, default value, is stable, description;`
38 create_config! {
39     // Fundamental stuff
40     max_width: usize, 100, true, "Maximum width of each line";
41     hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment";
42     tab_spaces: usize, 4, true, "Number of spaces per tab";
43     newline_style: NewlineStyle, NewlineStyle::Unix, true, "Unix or Windows line endings";
44     use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different \
45         formatting for items and expressions if they satisfy a heuristic notion of 'small'.";
46     indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items.";
47
48     // Comments and strings
49     wrap_comments: bool, false, false, "Break comments to fit on the line";
50     comment_width: usize, 80, false,
51         "Maximum length of comments. No effect unless wrap_comments = true";
52     normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
53     license_template_path: String, String::default(), false,
54         "Beginning of file must match license template";
55     format_strings: bool, false, false, "Format string literals where necessary";
56
57     // Single line expressions and items
58     empty_item_single_line: bool, true, false,
59         "Put empty-body functions and impls on a single line";
60     struct_lit_single_line: bool, true, false,
61         "Put small struct literals on a single line";
62     fn_single_line: bool, false, false, "Put single-expression functions on a single line";
63     where_single_line: bool, false, false, "Force where clauses to be on a single line";
64
65     // Imports
66     imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports";
67     imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
68     merge_imports: bool, false, false, "Merge imports";
69
70     // Ordering
71     reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically";
72     reorder_modules: bool, true, true, "Reorder module statements alphabetically in group";
73     reorder_impl_items: bool, false, false, "Reorder impl items";
74
75     // Spaces around punctuation
76     type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
77         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
78     space_before_colon: bool, false, false, "Leave a space before the colon";
79     space_after_colon: bool, true, false, "Leave a space after the colon";
80     spaces_around_ranges: bool, false, false, "Put spaces around the  .. and ..= range operators";
81     binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
82         "Where to put a binary operator when a binary expression goes multiline.";
83
84     // Misc.
85     remove_nested_parens: bool, true, true, "Remove nested parens.";
86     combine_control_expr: bool, true, false, "Combine control expressions with function calls.";
87     struct_field_align_threshold: usize, 0, false, "Align struct fields if their diffs fits within \
88                                              threshold.";
89     match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
90         the same line with the pattern of arms";
91     force_multiline_blocks: bool, false, false,
92         "Force multiline closure bodies and match arms to be wrapped in a block";
93     fn_args_density: Density, Density::Tall, false, "Argument density in functions";
94     brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
95     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
96         "Brace style for control flow constructs";
97     trailing_semicolon: bool, true, false,
98         "Add trailing semicolon after break, continue and return";
99     trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
100         "How to handle trailing commas for lists";
101     match_block_trailing_comma: bool, false, false,
102         "Put a trailing comma after a block based match arm (non-block arms are not affected)";
103     blank_lines_upper_bound: usize, 1, false,
104         "Maximum number of blank lines which can be put between items.";
105     blank_lines_lower_bound: usize, 0, false,
106         "Minimum number of blank lines which must be put between items.";
107     edition: Edition, Edition::Edition2015, false, "The edition of the parser. (RFC 2052)";
108
109     // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
110     merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
111     use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand";
112     use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible";
113     force_explicit_abi: bool, true, true, "Always print the abi for extern items";
114     condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
115                                                      in tuple patterns";
116
117     // Control options (changes the operation of rustfmt, rather than the formatting)
118     color: Color, Color::Auto, false,
119         "What Color option to use when none is supplied: Always, Never, Auto";
120     required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
121         "Require a specific version of rustfmt.";
122     unstable_features: bool, false, false,
123             "Enables unstable features. Only available on nightly channel";
124     disable_all_formatting: bool, false, false, "Don't reformat anything";
125     skip_children: bool, false, false, "Don't reformat out of line modules";
126     hide_parse_errors: bool, false, false, "Hide errors from the parser";
127     error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
128     error_on_unformatted: bool, false, false,
129         "Error if unable to get comments or string literals within max_width, \
130          or they are left with trailing whitespaces";
131     report_todo: ReportTactic, ReportTactic::Never, false,
132         "Report all, none or unnumbered occurrences of TODO in source file comments";
133     report_fixme: ReportTactic, ReportTactic::Never, false,
134         "Report all, none or unnumbered occurrences of FIXME in source file comments";
135     ignore: IgnoreList, IgnoreList::default(), false,
136         "Skip formatting the specified files and directories.";
137
138     // Not user-facing
139     verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user";
140     file_lines: FileLines, FileLines::all(), false,
141         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
142          via the --file-lines option";
143     width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
144         "'small' heuristic values";
145     emit_mode: EmitMode, EmitMode::Files, false,
146         "What emit Mode to use when none is supplied";
147     make_backup: bool, false, false, "Backup changed files";
148 }
149
150 /// Load a config by checking the client-supplied options and if appropriate, the
151 /// file system (including searching the file system for overrides).
152 pub fn load_config<O: CliOptions>(
153     file_path: Option<&Path>,
154     options: Option<O>,
155 ) -> Result<(Config, Option<PathBuf>), Error> {
156     let over_ride = match options {
157         Some(ref opts) => config_path(opts)?,
158         None => None,
159     };
160
161     let result = if let Some(over_ride) = over_ride {
162         Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
163     } else if let Some(file_path) = file_path {
164         Config::from_resolved_toml_path(file_path)
165     } else {
166         Ok((Config::default(), None))
167     };
168
169     result.map(|(mut c, p)| {
170         if let Some(options) = options {
171             options.apply_to(&mut c);
172         }
173         (c, p)
174     })
175 }
176
177 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
178 //
179 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
180 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
181     const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
182     for config_file_name in &CONFIG_FILE_NAMES {
183         let config_file = dir.join(config_file_name);
184         match fs::metadata(&config_file) {
185             // Only return if it's a file to handle the unlikely situation of a directory named
186             // `rustfmt.toml`.
187             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
188             // Return the error if it's something other than `NotFound`; otherwise we didn't
189             // find the project file yet, and continue searching.
190             Err(e) => {
191                 if e.kind() != ErrorKind::NotFound {
192                     return Err(e);
193                 }
194             }
195             _ => {}
196         }
197     }
198     Ok(None)
199 }
200
201 fn config_path(options: &CliOptions) -> Result<Option<PathBuf>, Error> {
202     let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
203         Err(Error::new(
204             ErrorKind::NotFound,
205             format!(
206                 "Error: unable to find a config file for the given path: `{}`",
207                 path
208             ),
209         ))
210     };
211
212     // Read the config_path and convert to parent dir if a file is provided.
213     // If a config file cannot be found from the given path, return error.
214     match options.config_path() {
215         Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
216         Some(path) if path.is_dir() => {
217             let config_file_path = get_toml_path(path)?;
218             if config_file_path.is_some() {
219                 Ok(config_file_path)
220             } else {
221                 config_path_not_found(path.to_str().unwrap())
222             }
223         }
224         path => Ok(path.map(|p| p.to_owned())),
225     }
226 }
227
228 #[cfg(test)]
229 mod test {
230     use super::*;
231     use std::str;
232
233     #[allow(dead_code)]
234     mod mock {
235         use super::super::*;
236
237         create_config! {
238             // Options that are used by the generated functions
239             max_width: usize, 100, true, "Maximum width of each line";
240             use_small_heuristics: Heuristics, Heuristics::Default, true,
241                 "Whether to use different formatting for items and \
242                  expressions if they satisfy a heuristic notion of 'small'.";
243             license_template_path: String, String::default(), false,
244                 "Beginning of file must match license template";
245             required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
246                 "Require a specific version of rustfmt.";
247             ignore: IgnoreList, IgnoreList::default(), false,
248                 "Skip formatting the specified files and directories.";
249             verbose: Verbosity, Verbosity::Normal, false,
250                 "How much to information to emit to the user";
251             file_lines: FileLines, FileLines::all(), false,
252                 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
253                     via the --file-lines option";
254             width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
255                 "'small' heuristic values";
256
257             // Options that are used by the tests
258             stable_option: bool, false, true, "A stable option";
259             unstable_option: bool, false, false, "An unstable option";
260         }
261     }
262
263     #[test]
264     fn test_config_set() {
265         let mut config = Config::default();
266         config.set().verbose(Verbosity::Quiet);
267         assert_eq!(config.verbose(), Verbosity::Quiet);
268         config.set().verbose(Verbosity::Normal);
269         assert_eq!(config.verbose(), Verbosity::Normal);
270     }
271
272     #[test]
273     fn test_config_used_to_toml() {
274         let config = Config::default();
275
276         let merge_derives = config.merge_derives();
277         let skip_children = config.skip_children();
278
279         let used_options = config.used_options();
280         let toml = used_options.to_toml().unwrap();
281         assert_eq!(
282             toml,
283             format!(
284                 "merge_derives = {}\nskip_children = {}\n",
285                 merge_derives, skip_children,
286             )
287         );
288     }
289
290     #[test]
291     fn test_was_set() {
292         use std::path::Path;
293         let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
294
295         assert_eq!(config.was_set().hard_tabs(), true);
296         assert_eq!(config.was_set().verbose(), false);
297     }
298
299     #[test]
300     fn test_print_docs_exclude_unstable() {
301         use self::mock::Config;
302
303         let mut output = Vec::new();
304         Config::print_docs(&mut output, false);
305
306         let s = str::from_utf8(&output).unwrap();
307
308         assert_eq!(s.contains("stable_option"), true);
309         assert_eq!(s.contains("unstable_option"), false);
310         assert_eq!(s.contains("(unstable)"), false);
311     }
312
313     #[test]
314     fn test_print_docs_include_unstable() {
315         use self::mock::Config;
316
317         let mut output = Vec::new();
318         Config::print_docs(&mut output, true);
319
320         let s = str::from_utf8(&output).unwrap();
321         assert_eq!(s.contains("stable_option"), true);
322         assert_eq!(s.contains("unstable_option"), true);
323         assert_eq!(s.contains("(unstable)"), true);
324     }
325
326     // FIXME(#2183) these tests cannot be run in parallel because they use env vars
327     // #[test]
328     // fn test_as_not_nightly_channel() {
329     //     let mut config = Config::default();
330     //     assert_eq!(config.was_set().unstable_features(), false);
331     //     config.set().unstable_features(true);
332     //     assert_eq!(config.was_set().unstable_features(), false);
333     // }
334
335     // #[test]
336     // fn test_as_nightly_channel() {
337     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
338     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
339     //     let mut config = Config::default();
340     //     config.set().unstable_features(true);
341     //     assert_eq!(config.was_set().unstable_features(), false);
342     //     config.set().unstable_features(true);
343     //     assert_eq!(config.unstable_features(), true);
344     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
345     // }
346
347     // #[test]
348     // fn test_unstable_from_toml() {
349     //     let mut config = Config::from_toml("unstable_features = true").unwrap();
350     //     assert_eq!(config.was_set().unstable_features(), false);
351     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
352     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
353     //     config = Config::from_toml("unstable_features = true").unwrap();
354     //     assert_eq!(config.was_set().unstable_features(), true);
355     //     assert_eq!(config.unstable_features(), true);
356     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
357     // }
358 }