]> git.lizzy.rs Git - rust.git/blob - src/config/mod.rs
Add merge_imports config option
[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 #[macro_use]
21 mod config_type;
22 #[macro_use]
23 mod options;
24
25 pub mod file_lines;
26 pub mod license;
27 pub mod lists;
28 pub mod summary;
29
30 use config::config_type::ConfigType;
31 use config::file_lines::FileLines;
32 pub use config::lists::*;
33 pub use config::options::*;
34 use config::summary::Summary;
35
36 /// This macro defines configuration options used in rustfmt. Each option
37 /// is defined as follows:
38 ///
39 /// `name: value type, default value, is stable, description;`
40 create_config! {
41     // Fundamental stuff
42     max_width: usize, 100, true, "Maximum width of each line";
43     hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment";
44     tab_spaces: usize, 4, true, "Number of spaces per tab";
45     newline_style: NewlineStyle, NewlineStyle::Unix, true, "Unix or Windows line endings";
46     use_small_heuristics: bool, true, false, "Whether to use different formatting for items and \
47         expressions if they satisfy a heuristic notion of 'small'.";
48     indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items.";
49
50     // Comments and strings
51     wrap_comments: bool, false, true, "Break comments to fit on the line";
52     comment_width: usize, 80, false,
53         "Maximum length of comments. No effect unless wrap_comments = true";
54     normalize_comments: bool, false, true, "Convert /* */ comments to // comments where possible";
55     license_template_path: String, String::default(), false, "Beginning of file must match license template";
56     format_strings: bool, false, false, "Format string literals where necessary";
57
58     // Single line expressions and items
59     empty_item_single_line: bool, true, false,
60         "Put empty-body functions and impls on a single line";
61     struct_lit_single_line: bool, true, false,
62         "Put small struct literals on a single line";
63     fn_single_line: bool, false, false, "Put single-expression functions on a single line";
64     where_single_line: bool, false, false, "Force where clauses to be on a single line";
65
66     // Imports
67     imports_indent: IndentStyle, IndentStyle::Visual, false, "Indent of imports";
68     imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
69     merge_imports: bool, false, false, "Merge imports";
70
71     // Ordering
72     reorder_extern_crates: bool, true, false, "Reorder extern crate statements alphabetically";
73     reorder_extern_crates_in_group: bool, true, false, "Reorder extern crate statements in group";
74     reorder_imports: bool, true, false, "Reorder import statements alphabetically";
75     reorder_imports_in_group: bool, true, false, "Reorder import statements in group";
76     reorder_imported_names: bool, true, false,
77         "Reorder lists of names in import statements alphabetically";
78     reorder_modules: bool, true, false, "Reorder module statemtents alphabetically in group";
79     reorder_impl_items: bool, false, false, "Reorder impl items";
80
81     // Spaces around punctuation
82     type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
83         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
84     space_before_colon: bool, false, false, "Leave a space before the colon";
85     space_after_colon: bool, true, false, "Leave a space after the colon";
86     spaces_around_ranges: bool, false, false, "Put spaces around the  .. and ... range operators";
87     spaces_within_parens_and_brackets: bool, false, false,
88         "Put spaces within non-empty parentheses or brackets";
89     binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
90         "Where to put a binary operator when a binary expression goes multiline.";
91
92     // Misc.
93     remove_blank_lines_at_start_or_end_of_block: bool, true, false,
94         "Remove blank lines at start or end of a block";
95     combine_control_expr: bool, true, false, "Combine control expressions with function calls.";
96     struct_field_align_threshold: usize, 0, false, "Align struct fields if their diffs fits within \
97                                              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
117     // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
118     merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
119     use_try_shorthand: bool, false, false, "Replace uses of the try! macro by the ? shorthand";
120     condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
121                                               in tuple patterns";
122     force_explicit_abi: bool, true, true, "Always print the abi for extern items";
123     use_field_init_shorthand: bool, false, false, "Use field initialization shorthand if possible";
124
125     // Control options (changes the operation of rustfmt, rather than the formatting)
126     write_mode: WriteMode, WriteMode::Overwrite, false,
127         "What Write Mode to use when none is supplied: \
128          Replace, Overwrite, Display, Plain, Diff, Coverage";
129     color: Color, Color::Auto, false,
130         "What Color option to use when none is supplied: Always, Never, Auto";
131     required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
132         "Require a specific version of rustfmt.";
133     unstable_features: bool, false, true,
134             "Enables unstable features. Only available on nightly channel";
135     disable_all_formatting: bool, false, false, "Don't reformat anything";
136     skip_children: bool, false, false, "Don't reformat out of line modules";
137     hide_parse_errors: bool, false, false, "Hide errors from the parser";
138     error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
139     error_on_unformatted: bool, false, false,
140         "Error if unable to get comments or string literals within max_width, \
141          or they are left with trailing whitespaces";
142     report_todo: ReportTactic, ReportTactic::Never, false,
143         "Report all, none or unnumbered occurrences of TODO in source file comments";
144     report_fixme: ReportTactic, ReportTactic::Never, false,
145         "Report all, none or unnumbered occurrences of FIXME in source file comments";
146     ignore: IgnoreList, IgnoreList::default(), false,
147         "Skip formatting the specified files and directories.";
148
149     // Not user-facing
150     verbose: bool, false, false, "Use verbose output";
151     file_lines: FileLines, FileLines::all(), false,
152         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
153          via the --file-lines option";
154     width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
155         "'small' heuristic values";
156 }
157
158 /// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
159 ///
160 /// Return the path if a config file exists, empty if no file exists, and Error for IO errors
161 pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
162     const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
163     for config_file_name in &CONFIG_FILE_NAMES {
164         let config_file = dir.join(config_file_name);
165         match fs::metadata(&config_file) {
166             // Only return if it's a file to handle the unlikely situation of a directory named
167             // `rustfmt.toml`.
168             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
169             // Return the error if it's something other than `NotFound`; otherwise we didn't
170             // find the project file yet, and continue searching.
171             Err(e) => {
172                 if e.kind() != ErrorKind::NotFound {
173                     return Err(e);
174                 }
175             }
176             _ => {}
177         }
178     }
179     Ok(None)
180 }
181
182 #[cfg(test)]
183 mod test {
184     use super::Config;
185     use std::str;
186
187     #[allow(dead_code)]
188     mod mock {
189         use super::super::*;
190
191         create_config! {
192             // Options that are used by the generated functions
193             max_width: usize, 100, true, "Maximum width of each line";
194             use_small_heuristics: bool, true, false, "Whether to use different formatting for items and \
195                 expressions if they satisfy a heuristic notion of 'small'.";
196             license_template_path: String, String::default(), false, "Beginning of file must match license template";
197             required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false, "Require a specific version of rustfmt.";
198             ignore: IgnoreList, IgnoreList::default(), false, "Skip formatting the specified files and directories.";
199             verbose: bool, false, false, "Use verbose output";
200             file_lines: FileLines, FileLines::all(), false,
201                 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
202                     via the --file-lines option";
203             width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false, "'small' heuristic values";
204
205             // Options that are used by the tests
206             stable_option: bool, false, true, "A stable option";
207             unstable_option: bool, false, false, "An unstable option";
208         }
209     }
210
211     #[test]
212     fn test_config_set() {
213         let mut config = Config::default();
214         config.set().verbose(false);
215         assert_eq!(config.verbose(), false);
216         config.set().verbose(true);
217         assert_eq!(config.verbose(), true);
218     }
219
220     #[test]
221     fn test_config_used_to_toml() {
222         let config = Config::default();
223
224         let merge_derives = config.merge_derives();
225         let skip_children = config.skip_children();
226
227         let used_options = config.used_options();
228         let toml = used_options.to_toml().unwrap();
229         assert_eq!(
230             toml,
231             format!(
232                 "merge_derives = {}\nskip_children = {}\n",
233                 merge_derives, skip_children,
234             )
235         );
236     }
237
238     #[test]
239     fn test_was_set() {
240         use std::path::Path;
241         let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
242
243         assert_eq!(config.was_set().hard_tabs(), true);
244         assert_eq!(config.was_set().verbose(), false);
245     }
246
247     #[test]
248     fn test_print_docs_exclude_unstable() {
249         use self::mock::Config;
250
251         let mut output = Vec::new();
252         Config::print_docs(&mut output, false);
253
254         let s = str::from_utf8(&output).unwrap();
255
256         assert_eq!(s.contains("stable_option"), true);
257         assert_eq!(s.contains("unstable_option"), false);
258         assert_eq!(s.contains("(unstable)"), false);
259     }
260
261     #[test]
262     fn test_print_docs_include_unstable() {
263         use self::mock::Config;
264
265         let mut output = Vec::new();
266         Config::print_docs(&mut output, true);
267
268         let s = str::from_utf8(&output).unwrap();
269         assert_eq!(s.contains("stable_option"), true);
270         assert_eq!(s.contains("unstable_option"), true);
271         assert_eq!(s.contains("(unstable)"), true);
272     }
273
274     // FIXME(#2183) these tests cannot be run in parallel because they use env vars
275     // #[test]
276     // fn test_as_not_nightly_channel() {
277     //     let mut config = Config::default();
278     //     assert_eq!(config.was_set().unstable_features(), false);
279     //     config.set().unstable_features(true);
280     //     assert_eq!(config.was_set().unstable_features(), false);
281     // }
282
283     // #[test]
284     // fn test_as_nightly_channel() {
285     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
286     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
287     //     let mut config = Config::default();
288     //     config.set().unstable_features(true);
289     //     assert_eq!(config.was_set().unstable_features(), false);
290     //     config.set().unstable_features(true);
291     //     assert_eq!(config.unstable_features(), true);
292     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
293     // }
294
295     // #[test]
296     // fn test_unstable_from_toml() {
297     //     let mut config = Config::from_toml("unstable_features = true").unwrap();
298     //     assert_eq!(config.was_set().unstable_features(), false);
299     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
300     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
301     //     config = Config::from_toml("unstable_features = true").unwrap();
302     //     assert_eq!(config.was_set().unstable_features(), true);
303     //     assert_eq!(config.unstable_features(), true);
304     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
305     // }
306 }