]> git.lizzy.rs Git - rust.git/blob - src/config/mod.rs
transition to Rust 2018
[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 std::cell::Cell;
12 use std::default::Default;
13 use std::fs::File;
14 use std::io::{Error, ErrorKind, Read};
15 use std::path::{Path, PathBuf};
16 use std::{env, fs};
17
18 use regex::Regex;
19
20 use crate::config::config_type::ConfigType;
21 pub use crate::config::file_lines::{FileLines, FileName, Range};
22 pub use crate::config::lists::*;
23 pub use crate::config::options::*;
24
25 #[macro_use]
26 pub mod config_type;
27 #[macro_use]
28 pub mod options;
29
30 pub mod file_lines;
31 pub mod license;
32 pub mod lists;
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::Auto, 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. macros, and strings
49     wrap_comments: bool, false, false, "Break comments to fit on the line";
50     format_doc_comments: bool, false, false, "Format doc comments.";
51     comment_width: usize, 80, false,
52         "Maximum length of comments. No effect unless wrap_comments = true";
53     normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
54     normalize_doc_attributes: bool, false, false, "Normalize doc attributes as doc comments";
55     license_template_path: String, String::default(), false,
56         "Beginning of file must match license template";
57     format_strings: bool, false, false, "Format string literals where necessary";
58     format_macro_matchers: bool, false, false,
59         "Format the metavariable matching patterns in macros";
60     format_macro_bodies: bool, true, false, "Format the bodies of macros";
61
62     // Single line expressions and items
63     empty_item_single_line: bool, true, false,
64         "Put empty-body functions and impls on a single line";
65     struct_lit_single_line: bool, true, false,
66         "Put small struct literals on a single line";
67     fn_single_line: bool, false, false, "Put single-expression functions on a single line";
68     where_single_line: bool, false, false, "Force where clauses to be on a single line";
69
70     // Imports
71     imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports";
72     imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
73     merge_imports: bool, false, false, "Merge imports";
74
75     // Ordering
76     reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically";
77     reorder_modules: bool, true, true, "Reorder module statements alphabetically in group";
78     reorder_impl_items: bool, false, false, "Reorder impl items";
79
80     // Spaces around punctuation
81     type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
82         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
83     space_before_colon: bool, false, false, "Leave a space before the colon";
84     space_after_colon: bool, true, false, "Leave a space after the colon";
85     spaces_around_ranges: bool, false, false, "Put spaces around the  .. and ..= range operators";
86     binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
87         "Where to put a binary operator when a binary expression goes multiline";
88
89     // Misc.
90     remove_nested_parens: bool, true, true, "Remove nested parens";
91     combine_control_expr: bool, true, false, "Combine control expressions with function calls";
92     overflow_delimited_expr: bool, false, false,
93         "Allow trailing bracket/brace delimited expressions to overflow";
94     struct_field_align_threshold: usize, 0, false,
95         "Align struct fields if their diffs fits within threshold";
96     enum_discrim_align_threshold: usize, 0, false,
97         "Align enum variants discrims, if their diffs fit within threshold";
98     match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
99         the same line with the pattern of arms";
100     force_multiline_blocks: bool, false, false,
101         "Force multiline closure bodies and match arms to be wrapped in a block";
102     fn_args_density: Density, Density::Tall, false, "Argument density in functions";
103     brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
104     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
105         "Brace style for control flow constructs";
106     trailing_semicolon: bool, true, false,
107         "Add trailing semicolon after break, continue and return";
108     trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
109         "How to handle trailing commas for lists";
110     match_block_trailing_comma: bool, false, false,
111         "Put a trailing comma after a block based match arm (non-block arms are not affected)";
112     blank_lines_upper_bound: usize, 1, false,
113         "Maximum number of blank lines which can be put between items";
114     blank_lines_lower_bound: usize, 0, false,
115         "Minimum number of blank lines which must be put between items";
116     edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)";
117     version: Version, Version::One, false, "Version of formatting rules";
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 }
159
160 /// Load a config by checking the client-supplied options and if appropriate, the
161 /// file system (including searching the file system for overrides).
162 pub fn load_config<O: CliOptions>(
163     file_path: Option<&Path>,
164     options: Option<O>,
165 ) -> Result<(Config, Option<PathBuf>), Error> {
166     let over_ride = match options {
167         Some(ref opts) => config_path(opts)?,
168         None => None,
169     };
170
171     let result = if let Some(over_ride) = over_ride {
172         Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
173     } else if let Some(file_path) = file_path {
174         Config::from_resolved_toml_path(file_path)
175     } else {
176         Ok((Config::default(), None))
177     };
178
179     result.map(|(mut c, p)| {
180         if let Some(options) = options {
181             options.apply_to(&mut c);
182         }
183         (c, p)
184     })
185 }
186
187 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
188 //
189 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
190 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
191     const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
192     for config_file_name in &CONFIG_FILE_NAMES {
193         let config_file = dir.join(config_file_name);
194         match fs::metadata(&config_file) {
195             // Only return if it's a file to handle the unlikely situation of a directory named
196             // `rustfmt.toml`.
197             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
198             // Return the error if it's something other than `NotFound`; otherwise we didn't
199             // find the project file yet, and continue searching.
200             Err(e) => {
201                 if e.kind() != ErrorKind::NotFound {
202                     return Err(e);
203                 }
204             }
205             _ => {}
206         }
207     }
208     Ok(None)
209 }
210
211 fn config_path(options: &CliOptions) -> Result<Option<PathBuf>, Error> {
212     let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
213         Err(Error::new(
214             ErrorKind::NotFound,
215             format!(
216                 "Error: unable to find a config file for the given path: `{}`",
217                 path
218             ),
219         ))
220     };
221
222     // Read the config_path and convert to parent dir if a file is provided.
223     // If a config file cannot be found from the given path, return error.
224     match options.config_path() {
225         Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
226         Some(path) if path.is_dir() => {
227             let config_file_path = get_toml_path(path)?;
228             if config_file_path.is_some() {
229                 Ok(config_file_path)
230             } else {
231                 config_path_not_found(path.to_str().unwrap())
232             }
233         }
234         path => Ok(path.map(|p| p.to_owned())),
235     }
236 }
237
238 #[cfg(test)]
239 mod test {
240     use super::*;
241     use std::str;
242
243     #[allow(dead_code)]
244     mod mock {
245         use super::super::*;
246
247         create_config! {
248             // Options that are used by the generated functions
249             max_width: usize, 100, true, "Maximum width of each line";
250             use_small_heuristics: Heuristics, Heuristics::Default, true,
251                 "Whether to use different formatting for items and \
252                  expressions if they satisfy a heuristic notion of 'small'.";
253             license_template_path: String, String::default(), false,
254                 "Beginning of file must match license template";
255             required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
256                 "Require a specific version of rustfmt.";
257             ignore: IgnoreList, IgnoreList::default(), false,
258                 "Skip formatting the specified files and directories.";
259             verbose: Verbosity, Verbosity::Normal, false,
260                 "How much to information to emit to the user";
261             file_lines: FileLines, FileLines::all(), false,
262                 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
263                     via the --file-lines option";
264             width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
265                 "'small' heuristic values";
266
267             // Options that are used by the tests
268             stable_option: bool, false, true, "A stable option";
269             unstable_option: bool, false, false, "An unstable option";
270         }
271     }
272
273     #[test]
274     fn test_config_set() {
275         let mut config = Config::default();
276         config.set().verbose(Verbosity::Quiet);
277         assert_eq!(config.verbose(), Verbosity::Quiet);
278         config.set().verbose(Verbosity::Normal);
279         assert_eq!(config.verbose(), Verbosity::Normal);
280     }
281
282     #[test]
283     fn test_config_used_to_toml() {
284         let config = Config::default();
285
286         let merge_derives = config.merge_derives();
287         let skip_children = config.skip_children();
288
289         let used_options = config.used_options();
290         let toml = used_options.to_toml().unwrap();
291         assert_eq!(
292             toml,
293             format!(
294                 "merge_derives = {}\nskip_children = {}\n",
295                 merge_derives, skip_children,
296             )
297         );
298     }
299
300     #[test]
301     fn test_was_set() {
302         use std::path::Path;
303         let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
304
305         assert_eq!(config.was_set().hard_tabs(), true);
306         assert_eq!(config.was_set().verbose(), false);
307     }
308
309     #[test]
310     fn test_print_docs_exclude_unstable() {
311         use self::mock::Config;
312
313         let mut output = Vec::new();
314         Config::print_docs(&mut output, false);
315
316         let s = str::from_utf8(&output).unwrap();
317
318         assert_eq!(s.contains("stable_option"), true);
319         assert_eq!(s.contains("unstable_option"), false);
320         assert_eq!(s.contains("(unstable)"), false);
321     }
322
323     #[test]
324     fn test_print_docs_include_unstable() {
325         use self::mock::Config;
326
327         let mut output = Vec::new();
328         Config::print_docs(&mut output, true);
329
330         let s = str::from_utf8(&output).unwrap();
331         assert_eq!(s.contains("stable_option"), true);
332         assert_eq!(s.contains("unstable_option"), true);
333         assert_eq!(s.contains("(unstable)"), true);
334     }
335
336     // FIXME(#2183) these tests cannot be run in parallel because they use env vars
337     // #[test]
338     // fn test_as_not_nightly_channel() {
339     //     let mut config = Config::default();
340     //     assert_eq!(config.was_set().unstable_features(), false);
341     //     config.set().unstable_features(true);
342     //     assert_eq!(config.was_set().unstable_features(), false);
343     // }
344
345     // #[test]
346     // fn test_as_nightly_channel() {
347     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
348     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
349     //     let mut config = Config::default();
350     //     config.set().unstable_features(true);
351     //     assert_eq!(config.was_set().unstable_features(), false);
352     //     config.set().unstable_features(true);
353     //     assert_eq!(config.unstable_features(), true);
354     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
355     // }
356
357     // #[test]
358     // fn test_unstable_from_toml() {
359     //     let mut config = Config::from_toml("unstable_features = true").unwrap();
360     //     assert_eq!(config.was_set().unstable_features(), false);
361     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
362     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
363     //     config = Config::from_toml("unstable_features = true").unwrap();
364     //     assert_eq!(config.was_set().unstable_features(), true);
365     //     assert_eq!(config.unstable_features(), true);
366     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
367     // }
368 }