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