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