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.
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.
13 use std::default::Default;
15 use std::io::{ErrorKind, Read};
16 use std::path::{Path, PathBuf};
21 use config::config_type::ConfigType;
22 use config::file_lines::FileLines;
23 pub use config::lists::*;
24 pub use config::options::*;
37 /// This macro defines configuration options used in rustfmt. Each option
38 /// is defined as follows:
40 /// `name: value type, default value, is stable, description;`
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 use_small_heuristics: bool, true, false, "Whether to use different formatting for items and \
48 expressions if they satisfy a heuristic notion of 'small'.";
49 indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items.";
51 // Comments and strings
52 wrap_comments: bool, false, true, "Break comments to fit on the line";
53 comment_width: usize, 80, false,
54 "Maximum length of comments. No effect unless wrap_comments = true";
55 normalize_comments: bool, false, true, "Convert /* */ comments to // comments where possible";
56 license_template_path: String, String::default(), false, "Beginning of file must match license template";
57 format_strings: bool, false, false, "Format string literals where necessary";
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, "Force where clauses to be on a single line";
68 imports_indent: IndentStyle, IndentStyle::Visual, false, "Indent of imports";
69 imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
70 merge_imports: bool, false, false, "Merge imports";
73 reorder_imports: bool, true, false, "Reorder import and extern crate statements alphabetically";
74 reorder_modules: bool, true, false, "Reorder module statements alphabetically in group";
75 reorder_impl_items: bool, false, false, "Reorder impl items";
77 // Spaces around punctuation
78 type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
79 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
80 space_before_colon: bool, false, false, "Leave a space before the colon";
81 space_after_colon: bool, true, false, "Leave a space after the colon";
82 spaces_around_ranges: bool, false, false, "Put spaces around the .. and ... range operators";
83 spaces_within_parens_and_brackets: bool, false, false,
84 "Put spaces within non-empty parentheses or brackets";
85 binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
86 "Where to put a binary operator when a binary expression goes multiline.";
89 remove_blank_lines_at_start_or_end_of_block: bool, true, false,
90 "Remove blank lines at start or end of a block";
91 combine_control_expr: bool, true, false, "Combine control expressions with function calls.";
92 struct_field_align_threshold: usize, 0, false, "Align struct fields if their diffs fits within \
94 match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
95 the same line with the pattern of arms";
96 force_multiline_blocks: bool, false, false,
97 "Force multiline closure bodies and match arms to be wrapped in a block";
98 fn_args_density: Density, Density::Tall, false, "Argument density in functions";
99 brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
100 control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
101 "Brace style for control flow constructs";
102 trailing_semicolon: bool, true, false,
103 "Add trailing semicolon after break, continue and return";
104 trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
105 "How to handle trailing commas for lists";
106 match_block_trailing_comma: bool, false, false,
107 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
108 blank_lines_upper_bound: usize, 1, false,
109 "Maximum number of blank lines which can be put between items.";
110 blank_lines_lower_bound: usize, 0, false,
111 "Minimum number of blank lines which must be put between items.";
113 // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
114 merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
115 use_try_shorthand: bool, false, false, "Replace uses of the try! macro by the ? shorthand";
116 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
118 force_explicit_abi: bool, true, true, "Always print the abi for extern items";
119 use_field_init_shorthand: bool, false, false, "Use field initialization shorthand if possible";
121 // Control options (changes the operation of rustfmt, rather than the formatting)
122 write_mode: WriteMode, WriteMode::Overwrite, false,
123 "What Write Mode to use when none is supplied: \
124 Replace, Overwrite, Display, Plain, Diff, Coverage, Check";
125 color: Color, Color::Auto, false,
126 "What Color option to use when none is supplied: Always, Never, Auto";
127 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
128 "Require a specific version of rustfmt.";
129 unstable_features: bool, false, true,
130 "Enables unstable features. Only available on nightly channel";
131 disable_all_formatting: bool, false, false, "Don't reformat anything";
132 skip_children: bool, false, false, "Don't reformat out of line modules";
133 hide_parse_errors: bool, false, false, "Hide errors from the parser";
134 error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
135 error_on_unformatted: bool, false, false,
136 "Error if unable to get comments or string literals within max_width, \
137 or they are left with trailing whitespaces";
138 report_todo: ReportTactic, ReportTactic::Never, false,
139 "Report all, none or unnumbered occurrences of TODO in source file comments";
140 report_fixme: ReportTactic, ReportTactic::Never, false,
141 "Report all, none or unnumbered occurrences of FIXME in source file comments";
142 ignore: IgnoreList, IgnoreList::default(), false,
143 "Skip formatting the specified files and directories.";
146 verbose: bool, false, false, "Use verbose output";
147 verbose_diff: bool, false, false, "Emit verbose diffs";
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";
156 file_path: Option<&Path>,
157 options: Option<&CliOptions>,
158 ) -> FmtResult<(Config, Option<PathBuf>)> {
159 let over_ride = match options {
160 Some(opts) => config_path(opts)?,
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)
169 Ok((Config::default(), None))
172 result.map(|(mut c, p)| {
173 if let Some(options) = options {
174 options.clone().apply_to(&mut c);
180 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
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) -> FmtResult<Option<PathBuf>> {
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
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.
194 if e.kind() != ErrorKind::NotFound {
195 return Err(Error::from(e));
204 fn config_path(options: &CliOptions) -> FmtResult<Option<PathBuf>> {
205 let config_path_not_found = |path: &str| -> FmtResult<Option<PathBuf>> {
207 "Error: unable to find a config file for the given path: `{}`",
212 // Read the config_path and convert to parent dir if a file is provided.
213 // If a config file cannot be found from the given path, return error.
214 match options.config_path {
215 Some(ref path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
216 Some(ref path) if path.is_dir() => {
217 let config_file_path = get_toml_path(path)?;
218 if config_file_path.is_some() {
221 config_path_not_found(path.to_str().unwrap())
224 ref path => Ok(path.to_owned()),
238 // Options that are used by the generated functions
239 max_width: usize, 100, true, "Maximum width of each line";
240 use_small_heuristics: bool, true, false, "Whether to use different formatting for items and \
241 expressions if they satisfy a heuristic notion of 'small'.";
242 license_template_path: String, String::default(), false, "Beginning of file must match license template";
243 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false, "Require a specific version of rustfmt.";
244 ignore: IgnoreList, IgnoreList::default(), false, "Skip formatting the specified files and directories.";
245 verbose: bool, false, false, "Use verbose output";
246 file_lines: FileLines, FileLines::all(), false,
247 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
248 via the --file-lines option";
249 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false, "'small' heuristic values";
251 // Options that are used by the tests
252 stable_option: bool, false, true, "A stable option";
253 unstable_option: bool, false, false, "An unstable option";
258 fn test_config_set() {
259 let mut config = Config::default();
260 config.set().verbose(false);
261 assert_eq!(config.verbose(), false);
262 config.set().verbose(true);
263 assert_eq!(config.verbose(), true);
267 fn test_config_used_to_toml() {
268 let config = Config::default();
270 let merge_derives = config.merge_derives();
271 let skip_children = config.skip_children();
273 let used_options = config.used_options();
274 let toml = used_options.to_toml().unwrap();
278 "merge_derives = {}\nskip_children = {}\n",
279 merge_derives, skip_children,
287 let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
289 assert_eq!(config.was_set().hard_tabs(), true);
290 assert_eq!(config.was_set().verbose(), false);
294 fn test_print_docs_exclude_unstable() {
295 use self::mock::Config;
297 let mut output = Vec::new();
298 Config::print_docs(&mut output, false);
300 let s = str::from_utf8(&output).unwrap();
302 assert_eq!(s.contains("stable_option"), true);
303 assert_eq!(s.contains("unstable_option"), false);
304 assert_eq!(s.contains("(unstable)"), false);
308 fn test_print_docs_include_unstable() {
309 use self::mock::Config;
311 let mut output = Vec::new();
312 Config::print_docs(&mut output, true);
314 let s = str::from_utf8(&output).unwrap();
315 assert_eq!(s.contains("stable_option"), true);
316 assert_eq!(s.contains("unstable_option"), true);
317 assert_eq!(s.contains("(unstable)"), true);
320 // FIXME(#2183) these tests cannot be run in parallel because they use env vars
322 // fn test_as_not_nightly_channel() {
323 // let mut config = Config::default();
324 // assert_eq!(config.was_set().unstable_features(), false);
325 // config.set().unstable_features(true);
326 // assert_eq!(config.was_set().unstable_features(), false);
330 // fn test_as_nightly_channel() {
331 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
332 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
333 // let mut config = Config::default();
334 // config.set().unstable_features(true);
335 // assert_eq!(config.was_set().unstable_features(), false);
336 // config.set().unstable_features(true);
337 // assert_eq!(config.unstable_features(), true);
338 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
342 // fn test_unstable_from_toml() {
343 // let mut config = Config::from_toml("unstable_features = true").unwrap();
344 // assert_eq!(config.was_set().unstable_features(), false);
345 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
346 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
347 // config = Config::from_toml("unstable_features = true").unwrap();
348 // assert_eq!(config.was_set().unstable_features(), true);
349 // assert_eq!(config.unstable_features(), true);
350 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);