]> git.lizzy.rs Git - rust.git/blob - src/config/mod.rs
Refactor parsing code into struct
[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::{env, fs};
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
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 lists;
27 pub mod summary;
28 pub mod license;
29
30 use config::config_type::ConfigType;
31 use config::file_lines::FileLines;
32 use config::license::TemplateParser;
33 pub use config::lists::*;
34 pub use config::options::*;
35 use config::summary::Summary;
36
37 /// This macro defines configuration options used in rustfmt. Each option
38 /// is defined as follows:
39 ///
40 /// `name: value type, default value, is stable, description;`
41 create_config! {
42     // Fundamental stuff
43     max_width: usize, 100, true, "Maximum width of each line";
44     hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment";
45     tab_spaces: usize, 4, true, "Number of spaces per tab";
46     newline_style: NewlineStyle, NewlineStyle::Unix, true, "Unix or Windows line endings";
47     indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items.";
48     use_small_heuristics: bool, true, false, "Whether to use different formatting for items and \
49         expressions if they satisfy a heuristic notion of 'small'.";
50
51     // strings and comments
52     format_strings: bool, false, false, "Format string literals where necessary";
53     wrap_comments: bool, false, true, "Break comments to fit on the line";
54     comment_width: usize, 80, false,
55         "Maximum length of comments. No effect unless wrap_comments = true";
56     normalize_comments: bool, false, true, "Convert /* */ comments to // comments where possible";
57     license_template_path: String, String::default(), false, "Beginning of file must match license template";
58
59     // Single line expressions and items.
60     empty_item_single_line: bool, true, false,
61         "Put empty-body functions and impls on a single line";
62     struct_lit_single_line: bool, true, false,
63         "Put small struct literals on a single line";
64     fn_single_line: bool, false, false, "Put single-expression functions on a single line";
65     where_single_line: bool, false, false, "To force single line where layout";
66
67     // Imports
68     imports_indent: IndentStyle, IndentStyle::Visual, false, "Indent of imports";
69     imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
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, false, false, "Reorder import statements alphabetically";
75     reorder_imports_in_group: bool, false, 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, false, false, "Reorder module statemtents alphabetically in group";
79
80     // Spaces around punctuation
81     binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
82         "Where to put a binary operator when a binary expression goes multiline.";
83     type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
84         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
85     space_before_colon: bool, false, false, "Leave a space before the colon";
86     space_after_colon: bool, true, false, "Leave a space after the colon";
87     spaces_around_ranges: bool, false, false, "Put spaces around the  .. and ... range operators";
88     spaces_within_parens_and_brackets: bool, false, false,
89         "Put spaces within non-empty parentheses or brackets";
90
91     // Misc.
92     combine_control_expr: bool, true, false, "Combine control expressions with function calls.";
93     struct_field_align_threshold: usize, 0, false, "Align struct fields if their diffs fits within \
94                                              threshold.";
95     remove_blank_lines_at_start_or_end_of_block: bool, true, false,
96         "Remove blank lines at start or end of a block";
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_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
106         "How to handle trailing commas for lists";
107     trailing_semicolon: bool, true, false,
108         "Add trailing semicolon after break, continue and return";
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
116     // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
117     merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
118     use_try_shorthand: bool, false, false, "Replace uses of the try! macro by the ? shorthand";
119     condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
120                                               in tuple patterns";
121     force_explicit_abi: bool, true, true, "Always print the abi for extern items";
122     use_field_init_shorthand: bool, false, false, "Use field initialization shorthand if possible";
123
124     // Control options (changes the operation of rustfmt, rather than the formatting)
125     write_mode: WriteMode, WriteMode::Overwrite, false,
126         "What Write Mode to use when none is supplied: \
127          Replace, Overwrite, Display, Plain, Diff, Coverage";
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, true,
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, true, 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
146     // Not user-facing.
147     verbose: bool, false, false, "Use verbose output";
148     file_lines: FileLines, FileLines::all(), false,
149         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
150          via the --file-lines option";
151     width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
152         "'small' heuristic values";
153 }
154
155 /// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
156 ///
157 /// Return the path if a config file exists, empty if no file exists, and Error for IO errors
158 pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
159     const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
160     for config_file_name in &CONFIG_FILE_NAMES {
161         let config_file = dir.join(config_file_name);
162         match fs::metadata(&config_file) {
163             // Only return if it's a file to handle the unlikely situation of a directory named
164             // `rustfmt.toml`.
165             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
166             // Return the error if it's something other than `NotFound`; otherwise we didn't
167             // find the project file yet, and continue searching.
168             Err(e) => {
169                 if e.kind() != ErrorKind::NotFound {
170                     return Err(e);
171                 }
172             }
173             _ => {}
174         }
175     }
176     Ok(None)
177 }
178
179 #[cfg(test)]
180 mod test {
181     use super::Config;
182
183     #[test]
184     fn test_config_set() {
185         let mut config = Config::default();
186         config.set().verbose(false);
187         assert_eq!(config.verbose(), false);
188         config.set().verbose(true);
189         assert_eq!(config.verbose(), true);
190     }
191
192     #[test]
193     fn test_config_used_to_toml() {
194         let config = Config::default();
195
196         let merge_derives = config.merge_derives();
197         let skip_children = config.skip_children();
198
199         let used_options = config.used_options();
200         let toml = used_options.to_toml().unwrap();
201         assert_eq!(
202             toml,
203             format!(
204                 "merge_derives = {}\nskip_children = {}\n",
205                 merge_derives, skip_children,
206             )
207         );
208     }
209
210     #[test]
211     fn test_was_set() {
212         let config = Config::from_toml("hard_tabs = true").unwrap();
213
214         assert_eq!(config.was_set().hard_tabs(), true);
215         assert_eq!(config.was_set().verbose(), false);
216     }
217
218     // FIXME(#2183) these tests cannot be run in parallel because they use env vars
219     // #[test]
220     // fn test_as_not_nightly_channel() {
221     //     let mut config = Config::default();
222     //     assert_eq!(config.was_set().unstable_features(), false);
223     //     config.set().unstable_features(true);
224     //     assert_eq!(config.was_set().unstable_features(), false);
225     // }
226
227     // #[test]
228     // fn test_as_nightly_channel() {
229     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
230     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
231     //     let mut config = Config::default();
232     //     config.set().unstable_features(true);
233     //     assert_eq!(config.was_set().unstable_features(), false);
234     //     config.set().unstable_features(true);
235     //     assert_eq!(config.unstable_features(), true);
236     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
237     // }
238
239     // #[test]
240     // fn test_unstable_from_toml() {
241     //     let mut config = Config::from_toml("unstable_features = true").unwrap();
242     //     assert_eq!(config.was_set().unstable_features(), false);
243     //     let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
244     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
245     //     config = Config::from_toml("unstable_features = true").unwrap();
246     //     assert_eq!(config.was_set().unstable_features(), true);
247     //     assert_eq!(config.unstable_features(), true);
248     //     ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
249     // }
250 }