]>
Commit | Line | Data |
---|---|---|
f20569fa XL |
1 | use std::cell::Cell; |
2 | use std::default::Default; | |
3 | use std::fs::File; | |
4 | use std::io::{Error, ErrorKind, Read}; | |
5 | use std::path::{Path, PathBuf}; | |
6 | use std::{env, fs}; | |
7 | ||
8 | use regex::Regex; | |
9 | use thiserror::Error; | |
10 | ||
11 | use crate::config::config_type::ConfigType; | |
12 | #[allow(unreachable_pub)] | |
13 | pub use crate::config::file_lines::{FileLines, FileName, Range}; | |
14 | #[allow(unreachable_pub)] | |
15 | pub use crate::config::lists::*; | |
16 | #[allow(unreachable_pub)] | |
17 | pub use crate::config::options::*; | |
18 | ||
19 | #[macro_use] | |
20 | pub(crate) mod config_type; | |
21 | #[macro_use] | |
22 | pub(crate) mod options; | |
23 | ||
24 | pub(crate) mod file_lines; | |
25 | pub(crate) mod license; | |
26 | pub(crate) mod lists; | |
27 | ||
28 | // This macro defines configuration options used in rustfmt. Each option | |
29 | // is defined as follows: | |
30 | // | |
31 | // `name: value type, default value, is stable, description;` | |
32 | create_config! { | |
33 | // Fundamental stuff | |
34 | max_width: usize, 100, true, "Maximum width of each line"; | |
35 | hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment"; | |
36 | tab_spaces: usize, 4, true, "Number of spaces per tab"; | |
37 | newline_style: NewlineStyle, NewlineStyle::Auto, true, "Unix or Windows line endings"; | |
cdc7bbd5 XL |
38 | indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items"; |
39 | ||
40 | // Width Heuristics | |
f20569fa XL |
41 | use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different \ |
42 | formatting for items and expressions if they satisfy a heuristic notion of 'small'"; | |
cdc7bbd5 XL |
43 | width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false, |
44 | "'small' heuristic values"; | |
45 | fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \ | |
46 | falling back to vertical formatting."; | |
47 | attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \ | |
48 | attributes before falling back to vertical formatting."; | |
49 | struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \ | |
50 | falling back to vertical formatting."; | |
51 | struct_variant_width: usize, 35, true, "Maximum width in the body of a struct variant before \ | |
52 | falling back to vertical formatting."; | |
53 | array_width: usize, 60, true, "Maximum width of an array literal before falling \ | |
54 | back to vertical formatting."; | |
55 | chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line."; | |
56 | single_line_if_else_max_width: usize, 50, true, "Maximum line length for single line if-else \ | |
57 | expressions. A value of zero means always break if-else expressions."; | |
f20569fa XL |
58 | |
59 | // Comments. macros, and strings | |
60 | wrap_comments: bool, false, false, "Break comments to fit on the line"; | |
61 | format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments."; | |
62 | comment_width: usize, 80, false, | |
63 | "Maximum length of comments. No effect unless wrap_comments = true"; | |
64 | normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible"; | |
65 | normalize_doc_attributes: bool, false, false, "Normalize doc attributes as doc comments"; | |
66 | license_template_path: String, String::default(), false, | |
67 | "Beginning of file must match license template"; | |
68 | format_strings: bool, false, false, "Format string literals where necessary"; | |
69 | format_macro_matchers: bool, false, false, | |
70 | "Format the metavariable matching patterns in macros"; | |
71 | format_macro_bodies: bool, true, false, "Format the bodies of macros"; | |
3c0e092e XL |
72 | hex_literal_case: HexLiteralCase, HexLiteralCase::Preserve, false, |
73 | "Format hexadecimal integer literals"; | |
f20569fa XL |
74 | |
75 | // Single line expressions and items | |
76 | empty_item_single_line: bool, true, false, | |
77 | "Put empty-body functions and impls on a single line"; | |
78 | struct_lit_single_line: bool, true, false, | |
79 | "Put small struct literals on a single line"; | |
80 | fn_single_line: bool, false, false, "Put single-expression functions on a single line"; | |
81 | where_single_line: bool, false, false, "Force where-clauses to be on a single line"; | |
82 | ||
83 | // Imports | |
84 | imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports"; | |
85 | imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block"; | |
86 | imports_granularity: ImportGranularity, ImportGranularity::Preserve, false, | |
87 | "Merge or split imports to the provided granularity"; | |
88 | group_imports: GroupImportsTactic, GroupImportsTactic::Preserve, false, | |
89 | "Controls the strategy for how imports are grouped together"; | |
90 | merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)"; | |
91 | ||
92 | // Ordering | |
93 | reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically"; | |
94 | reorder_modules: bool, true, true, "Reorder module statements alphabetically in group"; | |
95 | reorder_impl_items: bool, false, false, "Reorder impl items"; | |
96 | ||
97 | // Spaces around punctuation | |
98 | type_punctuation_density: TypeDensity, TypeDensity::Wide, false, | |
99 | "Determines if '+' or '=' are wrapped in spaces in the punctuation of types"; | |
100 | space_before_colon: bool, false, false, "Leave a space before the colon"; | |
101 | space_after_colon: bool, true, false, "Leave a space after the colon"; | |
102 | spaces_around_ranges: bool, false, false, "Put spaces around the .. and ..= range operators"; | |
103 | binop_separator: SeparatorPlace, SeparatorPlace::Front, false, | |
104 | "Where to put a binary operator when a binary expression goes multiline"; | |
105 | ||
106 | // Misc. | |
107 | remove_nested_parens: bool, true, true, "Remove nested parens"; | |
108 | combine_control_expr: bool, true, false, "Combine control expressions with function calls"; | |
109 | overflow_delimited_expr: bool, false, false, | |
110 | "Allow trailing bracket/brace delimited expressions to overflow"; | |
111 | struct_field_align_threshold: usize, 0, false, | |
112 | "Align struct fields if their diffs fits within threshold"; | |
113 | enum_discrim_align_threshold: usize, 0, false, | |
114 | "Align enum variants discrims, if their diffs fit within threshold"; | |
115 | match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \ | |
116 | the same line with the pattern of arms"; | |
117 | match_arm_leading_pipes: MatchArmLeadingPipe, MatchArmLeadingPipe::Never, true, | |
118 | "Determines whether leading pipes are emitted on match arms"; | |
119 | force_multiline_blocks: bool, false, false, | |
120 | "Force multiline closure bodies and match arms to be wrapped in a block"; | |
121 | fn_args_layout: Density, Density::Tall, true, | |
122 | "Control the layout of arguments in a function"; | |
123 | brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items"; | |
124 | control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false, | |
125 | "Brace style for control flow constructs"; | |
126 | trailing_semicolon: bool, true, false, | |
127 | "Add trailing semicolon after break, continue and return"; | |
128 | trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false, | |
129 | "How to handle trailing commas for lists"; | |
3c0e092e | 130 | match_block_trailing_comma: bool, false, true, |
f20569fa XL |
131 | "Put a trailing comma after a block based match arm (non-block arms are not affected)"; |
132 | blank_lines_upper_bound: usize, 1, false, | |
133 | "Maximum number of blank lines which can be put between items"; | |
134 | blank_lines_lower_bound: usize, 0, false, | |
135 | "Minimum number of blank lines which must be put between items"; | |
136 | edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)"; | |
137 | version: Version, Version::One, false, "Version of formatting rules"; | |
138 | inline_attribute_width: usize, 0, false, | |
139 | "Write an item and its attribute on the same line \ | |
140 | if their combined width is below a threshold"; | |
3c0e092e | 141 | format_generated_files: bool, true, false, "Format generated files"; |
f20569fa XL |
142 | |
143 | // Options that can change the source code beyond whitespace/blocks (somewhat linty things) | |
144 | merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one"; | |
145 | use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand"; | |
146 | use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible"; | |
147 | force_explicit_abi: bool, true, true, "Always print the abi for extern items"; | |
148 | condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \ | |
149 | in tuple patterns"; | |
150 | ||
151 | // Control options (changes the operation of rustfmt, rather than the formatting) | |
152 | color: Color, Color::Auto, false, | |
153 | "What Color option to use when none is supplied: Always, Never, Auto"; | |
154 | required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false, | |
155 | "Require a specific version of rustfmt"; | |
156 | unstable_features: bool, false, false, | |
157 | "Enables unstable features. Only available on nightly channel"; | |
3c0e092e | 158 | disable_all_formatting: bool, false, true, "Don't reformat anything"; |
f20569fa XL |
159 | skip_children: bool, false, false, "Don't reformat out of line modules"; |
160 | hide_parse_errors: bool, false, false, "Hide errors from the parser"; | |
161 | error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width"; | |
162 | error_on_unformatted: bool, false, false, | |
163 | "Error if unable to get comments or string literals within max_width, \ | |
164 | or they are left with trailing whitespaces"; | |
165 | report_todo: ReportTactic, ReportTactic::Never, false, | |
166 | "Report all, none or unnumbered occurrences of TODO in source file comments"; | |
167 | report_fixme: ReportTactic, ReportTactic::Never, false, | |
168 | "Report all, none or unnumbered occurrences of FIXME in source file comments"; | |
169 | ignore: IgnoreList, IgnoreList::default(), false, | |
170 | "Skip formatting the specified files and directories"; | |
171 | ||
172 | // Not user-facing | |
173 | verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user"; | |
174 | file_lines: FileLines, FileLines::all(), false, | |
175 | "Lines to format; this is not supported in rustfmt.toml, and can only be specified \ | |
176 | via the --file-lines option"; | |
f20569fa XL |
177 | emit_mode: EmitMode, EmitMode::Files, false, |
178 | "What emit Mode to use when none is supplied"; | |
179 | make_backup: bool, false, false, "Backup changed files"; | |
180 | print_misformatted_file_names: bool, false, true, | |
181 | "Prints the names of mismatched files that were formatted. Prints the names of \ | |
182 | files that would be formated when used with `--check` mode. "; | |
183 | } | |
184 | ||
185 | #[derive(Error, Debug)] | |
186 | #[error("Could not output config: {0}")] | |
187 | pub struct ToTomlError(toml::ser::Error); | |
188 | ||
189 | impl PartialConfig { | |
190 | pub fn to_toml(&self) -> Result<String, ToTomlError> { | |
191 | // Non-user-facing options can't be specified in TOML | |
192 | let mut cloned = self.clone(); | |
193 | cloned.file_lines = None; | |
194 | cloned.verbose = None; | |
195 | cloned.width_heuristics = None; | |
196 | cloned.print_misformatted_file_names = None; | |
197 | cloned.merge_imports = None; | |
198 | ||
199 | ::toml::to_string(&cloned).map_err(ToTomlError) | |
200 | } | |
201 | } | |
202 | ||
203 | impl Config { | |
204 | pub(crate) fn version_meets_requirement(&self) -> bool { | |
205 | if self.was_set().required_version() { | |
206 | let version = env!("CARGO_PKG_VERSION"); | |
207 | let required_version = self.required_version(); | |
208 | if version != required_version { | |
209 | println!( | |
210 | "Error: rustfmt version ({}) doesn't match the required version ({})", | |
211 | version, required_version, | |
212 | ); | |
213 | return false; | |
214 | } | |
215 | } | |
216 | ||
217 | true | |
218 | } | |
219 | ||
220 | /// Constructs a `Config` from the toml file specified at `file_path`. | |
221 | /// | |
222 | /// This method only looks at the provided path, for a method that | |
223 | /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`. | |
224 | /// | |
225 | /// Returns a `Config` if the config could be read and parsed from | |
226 | /// the file, otherwise errors. | |
227 | pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> { | |
228 | let mut file = File::open(&file_path)?; | |
229 | let mut toml = String::new(); | |
230 | file.read_to_string(&mut toml)?; | |
231 | Config::from_toml(&toml, file_path.parent().unwrap()) | |
232 | .map_err(|err| Error::new(ErrorKind::InvalidData, err)) | |
233 | } | |
234 | ||
235 | /// Resolves the config for input in `dir`. | |
236 | /// | |
237 | /// Searches for `rustfmt.toml` beginning with `dir`, and | |
238 | /// recursively checking parents of `dir` if no config file is found. | |
239 | /// If no config file exists in `dir` or in any parent, a | |
240 | /// default `Config` will be returned (and the returned path will be empty). | |
241 | /// | |
242 | /// Returns the `Config` to use, and the path of the project file if there was | |
243 | /// one. | |
244 | pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> { | |
245 | /// Try to find a project file in the given directory and its parents. | |
246 | /// Returns the path of a the nearest project file if one exists, | |
247 | /// or `None` if no project file was found. | |
248 | fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> { | |
249 | let mut current = if dir.is_relative() { | |
250 | env::current_dir()?.join(dir) | |
251 | } else { | |
252 | dir.to_path_buf() | |
253 | }; | |
254 | ||
255 | current = fs::canonicalize(current)?; | |
256 | ||
257 | loop { | |
258 | match get_toml_path(¤t) { | |
259 | Ok(Some(path)) => return Ok(Some(path)), | |
260 | Err(e) => return Err(e), | |
261 | _ => (), | |
262 | } | |
263 | ||
264 | // If the current directory has no parent, we're done searching. | |
265 | if !current.pop() { | |
266 | break; | |
267 | } | |
268 | } | |
269 | ||
270 | // If nothing was found, check in the home directory. | |
271 | if let Some(home_dir) = dirs::home_dir() { | |
272 | if let Some(path) = get_toml_path(&home_dir)? { | |
273 | return Ok(Some(path)); | |
274 | } | |
275 | } | |
276 | ||
277 | // If none was found ther either, check in the user's configuration directory. | |
278 | if let Some(mut config_dir) = dirs::config_dir() { | |
279 | config_dir.push("rustfmt"); | |
280 | if let Some(path) = get_toml_path(&config_dir)? { | |
281 | return Ok(Some(path)); | |
282 | } | |
283 | } | |
284 | ||
285 | Ok(None) | |
286 | } | |
287 | ||
288 | match resolve_project_file(dir)? { | |
289 | None => Ok((Config::default(), None)), | |
290 | Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))), | |
291 | } | |
292 | } | |
293 | ||
294 | pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> { | |
295 | let parsed: ::toml::Value = toml | |
296 | .parse() | |
297 | .map_err(|e| format!("Could not parse TOML: {}", e))?; | |
298 | let mut err = String::new(); | |
299 | let table = parsed | |
300 | .as_table() | |
301 | .ok_or_else(|| String::from("Parsed config was not table"))?; | |
302 | for key in table.keys() { | |
303 | if !Config::is_valid_name(key) { | |
304 | let msg = &format!("Warning: Unknown configuration option `{}`\n", key); | |
305 | err.push_str(msg) | |
306 | } | |
307 | } | |
308 | match parsed.try_into() { | |
309 | Ok(parsed_config) => { | |
310 | if !err.is_empty() { | |
311 | eprint!("{}", err); | |
312 | } | |
313 | Ok(Config::default().fill_from_parsed_config(parsed_config, dir)) | |
314 | } | |
315 | Err(e) => { | |
316 | err.push_str("Error: Decoding config file failed:\n"); | |
317 | err.push_str(format!("{}\n", e).as_str()); | |
318 | err.push_str("Please check your config file."); | |
319 | Err(err) | |
320 | } | |
321 | } | |
322 | } | |
323 | } | |
324 | ||
325 | /// Loads a config by checking the client-supplied options and if appropriate, the | |
326 | /// file system (including searching the file system for overrides). | |
327 | pub fn load_config<O: CliOptions>( | |
328 | file_path: Option<&Path>, | |
329 | options: Option<O>, | |
330 | ) -> Result<(Config, Option<PathBuf>), Error> { | |
331 | let over_ride = match options { | |
332 | Some(ref opts) => config_path(opts)?, | |
333 | None => None, | |
334 | }; | |
335 | ||
336 | let result = if let Some(over_ride) = over_ride { | |
337 | Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned()))) | |
338 | } else if let Some(file_path) = file_path { | |
339 | Config::from_resolved_toml_path(file_path) | |
340 | } else { | |
341 | Ok((Config::default(), None)) | |
342 | }; | |
343 | ||
344 | result.map(|(mut c, p)| { | |
345 | if let Some(options) = options { | |
346 | options.apply_to(&mut c); | |
347 | } | |
348 | (c, p) | |
349 | }) | |
350 | } | |
351 | ||
352 | // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir` | |
353 | // | |
354 | // Return the path if a config file exists, empty if no file exists, and Error for IO errors | |
355 | fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> { | |
356 | const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"]; | |
357 | for config_file_name in &CONFIG_FILE_NAMES { | |
358 | let config_file = dir.join(config_file_name); | |
359 | match fs::metadata(&config_file) { | |
360 | // Only return if it's a file to handle the unlikely situation of a directory named | |
361 | // `rustfmt.toml`. | |
362 | Ok(ref md) if md.is_file() => return Ok(Some(config_file)), | |
363 | // Return the error if it's something other than `NotFound`; otherwise we didn't | |
364 | // find the project file yet, and continue searching. | |
365 | Err(e) => { | |
366 | if e.kind() != ErrorKind::NotFound { | |
367 | return Err(e); | |
368 | } | |
369 | } | |
370 | _ => {} | |
371 | } | |
372 | } | |
373 | Ok(None) | |
374 | } | |
375 | ||
376 | fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> { | |
377 | let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> { | |
378 | Err(Error::new( | |
379 | ErrorKind::NotFound, | |
380 | format!( | |
381 | "Error: unable to find a config file for the given path: `{}`", | |
382 | path | |
383 | ), | |
384 | )) | |
385 | }; | |
386 | ||
387 | // Read the config_path and convert to parent dir if a file is provided. | |
388 | // If a config file cannot be found from the given path, return error. | |
389 | match options.config_path() { | |
390 | Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()), | |
391 | Some(path) if path.is_dir() => { | |
392 | let config_file_path = get_toml_path(path)?; | |
393 | if config_file_path.is_some() { | |
394 | Ok(config_file_path) | |
395 | } else { | |
396 | config_path_not_found(path.to_str().unwrap()) | |
397 | } | |
398 | } | |
399 | path => Ok(path.map(ToOwned::to_owned)), | |
400 | } | |
401 | } | |
402 | ||
403 | #[cfg(test)] | |
404 | mod test { | |
405 | use super::*; | |
406 | use std::str; | |
407 | ||
a2a8927a XL |
408 | use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test}; |
409 | ||
f20569fa XL |
410 | #[allow(dead_code)] |
411 | mod mock { | |
412 | use super::super::*; | |
413 | ||
414 | create_config! { | |
415 | // Options that are used by the generated functions | |
416 | max_width: usize, 100, true, "Maximum width of each line"; | |
f20569fa XL |
417 | license_template_path: String, String::default(), false, |
418 | "Beginning of file must match license template"; | |
419 | required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false, | |
420 | "Require a specific version of rustfmt."; | |
421 | ignore: IgnoreList, IgnoreList::default(), false, | |
422 | "Skip formatting the specified files and directories."; | |
423 | verbose: Verbosity, Verbosity::Normal, false, | |
424 | "How much to information to emit to the user"; | |
425 | file_lines: FileLines, FileLines::all(), false, | |
426 | "Lines to format; this is not supported in rustfmt.toml, and can only be specified \ | |
427 | via the --file-lines option"; | |
cdc7bbd5 | 428 | |
f20569fa XL |
429 | // merge_imports deprecation |
430 | imports_granularity: ImportGranularity, ImportGranularity::Preserve, false, | |
431 | "Merge imports"; | |
432 | merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)"; | |
433 | ||
cdc7bbd5 XL |
434 | // Width Heuristics |
435 | use_small_heuristics: Heuristics, Heuristics::Default, true, | |
436 | "Whether to use different formatting for items and \ | |
437 | expressions if they satisfy a heuristic notion of 'small'."; | |
438 | width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false, | |
439 | "'small' heuristic values"; | |
440 | ||
441 | fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \ | |
442 | falling back to vertical formatting."; | |
443 | attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \ | |
444 | attributes before falling back to vertical formatting."; | |
445 | struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \ | |
446 | falling back to vertical formatting."; | |
447 | struct_variant_width: usize, 35, true, "Maximum width in the body of a struct \ | |
448 | variant before falling back to vertical formatting."; | |
449 | array_width: usize, 60, true, "Maximum width of an array literal before falling \ | |
450 | back to vertical formatting."; | |
451 | chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line."; | |
452 | single_line_if_else_max_width: usize, 50, true, "Maximum line length for single \ | |
453 | line if-else expressions. A value of zero means always break if-else expressions."; | |
454 | ||
f20569fa XL |
455 | // Options that are used by the tests |
456 | stable_option: bool, false, true, "A stable option"; | |
457 | unstable_option: bool, false, false, "An unstable option"; | |
458 | } | |
459 | } | |
460 | ||
461 | #[test] | |
462 | fn test_config_set() { | |
463 | let mut config = Config::default(); | |
464 | config.set().verbose(Verbosity::Quiet); | |
465 | assert_eq!(config.verbose(), Verbosity::Quiet); | |
466 | config.set().verbose(Verbosity::Normal); | |
467 | assert_eq!(config.verbose(), Verbosity::Normal); | |
468 | } | |
469 | ||
470 | #[test] | |
471 | fn test_config_used_to_toml() { | |
472 | let config = Config::default(); | |
473 | ||
474 | let merge_derives = config.merge_derives(); | |
475 | let skip_children = config.skip_children(); | |
476 | ||
477 | let used_options = config.used_options(); | |
478 | let toml = used_options.to_toml().unwrap(); | |
479 | assert_eq!( | |
480 | toml, | |
481 | format!( | |
482 | "merge_derives = {}\nskip_children = {}\n", | |
483 | merge_derives, skip_children, | |
484 | ) | |
485 | ); | |
486 | } | |
487 | ||
488 | #[test] | |
489 | fn test_was_set() { | |
490 | let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap(); | |
491 | ||
492 | assert_eq!(config.was_set().hard_tabs(), true); | |
493 | assert_eq!(config.was_set().verbose(), false); | |
494 | } | |
495 | ||
496 | #[test] | |
497 | fn test_print_docs_exclude_unstable() { | |
498 | use self::mock::Config; | |
499 | ||
500 | let mut output = Vec::new(); | |
501 | Config::print_docs(&mut output, false); | |
502 | ||
503 | let s = str::from_utf8(&output).unwrap(); | |
504 | ||
505 | assert_eq!(s.contains("stable_option"), true); | |
506 | assert_eq!(s.contains("unstable_option"), false); | |
507 | assert_eq!(s.contains("(unstable)"), false); | |
508 | } | |
509 | ||
510 | #[test] | |
511 | fn test_print_docs_include_unstable() { | |
512 | use self::mock::Config; | |
513 | ||
514 | let mut output = Vec::new(); | |
515 | Config::print_docs(&mut output, true); | |
516 | ||
517 | let s = str::from_utf8(&output).unwrap(); | |
518 | assert_eq!(s.contains("stable_option"), true); | |
519 | assert_eq!(s.contains("unstable_option"), true); | |
520 | assert_eq!(s.contains("(unstable)"), true); | |
521 | } | |
522 | ||
523 | #[test] | |
524 | fn test_empty_string_license_template_path() { | |
525 | let toml = r#"license_template_path = """#; | |
526 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
527 | assert!(config.license_template.is_none()); | |
528 | } | |
529 | ||
a2a8927a | 530 | #[nightly_only_test] |
f20569fa XL |
531 | #[test] |
532 | fn test_valid_license_template_path() { | |
f20569fa XL |
533 | let toml = r#"license_template_path = "tests/license-template/lt.txt""#; |
534 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
535 | assert!(config.license_template.is_some()); | |
536 | } | |
537 | ||
a2a8927a | 538 | #[nightly_only_test] |
f20569fa XL |
539 | #[test] |
540 | fn test_override_existing_license_with_no_license() { | |
f20569fa XL |
541 | let toml = r#"license_template_path = "tests/license-template/lt.txt""#; |
542 | let mut config = Config::from_toml(toml, Path::new("")).unwrap(); | |
543 | assert!(config.license_template.is_some()); | |
544 | config.override_value("license_template_path", ""); | |
545 | assert!(config.license_template.is_none()); | |
546 | } | |
547 | ||
548 | #[test] | |
549 | fn test_dump_default_config() { | |
550 | let default_config = format!( | |
551 | r#"max_width = 100 | |
552 | hard_tabs = false | |
553 | tab_spaces = 4 | |
554 | newline_style = "Auto" | |
f20569fa | 555 | indent_style = "Block" |
cdc7bbd5 XL |
556 | use_small_heuristics = "Default" |
557 | fn_call_width = 60 | |
558 | attr_fn_like_width = 70 | |
559 | struct_lit_width = 18 | |
560 | struct_variant_width = 35 | |
561 | array_width = 60 | |
562 | chain_width = 60 | |
563 | single_line_if_else_max_width = 50 | |
f20569fa XL |
564 | wrap_comments = false |
565 | format_code_in_doc_comments = false | |
566 | comment_width = 80 | |
567 | normalize_comments = false | |
568 | normalize_doc_attributes = false | |
569 | license_template_path = "" | |
570 | format_strings = false | |
571 | format_macro_matchers = false | |
572 | format_macro_bodies = true | |
3c0e092e | 573 | hex_literal_case = "Preserve" |
f20569fa XL |
574 | empty_item_single_line = true |
575 | struct_lit_single_line = true | |
576 | fn_single_line = false | |
577 | where_single_line = false | |
578 | imports_indent = "Block" | |
579 | imports_layout = "Mixed" | |
580 | imports_granularity = "Preserve" | |
581 | group_imports = "Preserve" | |
582 | reorder_imports = true | |
583 | reorder_modules = true | |
584 | reorder_impl_items = false | |
585 | type_punctuation_density = "Wide" | |
586 | space_before_colon = false | |
587 | space_after_colon = true | |
588 | spaces_around_ranges = false | |
589 | binop_separator = "Front" | |
590 | remove_nested_parens = true | |
591 | combine_control_expr = true | |
592 | overflow_delimited_expr = false | |
593 | struct_field_align_threshold = 0 | |
594 | enum_discrim_align_threshold = 0 | |
595 | match_arm_blocks = true | |
596 | match_arm_leading_pipes = "Never" | |
597 | force_multiline_blocks = false | |
598 | fn_args_layout = "Tall" | |
599 | brace_style = "SameLineWhere" | |
600 | control_brace_style = "AlwaysSameLine" | |
601 | trailing_semicolon = true | |
602 | trailing_comma = "Vertical" | |
603 | match_block_trailing_comma = false | |
604 | blank_lines_upper_bound = 1 | |
605 | blank_lines_lower_bound = 0 | |
606 | edition = "2015" | |
607 | version = "One" | |
608 | inline_attribute_width = 0 | |
3c0e092e | 609 | format_generated_files = true |
f20569fa XL |
610 | merge_derives = true |
611 | use_try_shorthand = false | |
612 | use_field_init_shorthand = false | |
613 | force_explicit_abi = true | |
614 | condense_wildcard_suffixes = false | |
615 | color = "Auto" | |
616 | required_version = "{}" | |
617 | unstable_features = false | |
618 | disable_all_formatting = false | |
619 | skip_children = false | |
620 | hide_parse_errors = false | |
621 | error_on_line_overflow = false | |
622 | error_on_unformatted = false | |
623 | report_todo = "Never" | |
624 | report_fixme = "Never" | |
625 | ignore = [] | |
626 | emit_mode = "Files" | |
627 | make_backup = false | |
628 | "#, | |
629 | env!("CARGO_PKG_VERSION") | |
630 | ); | |
631 | let toml = Config::default().all_options().to_toml().unwrap(); | |
632 | assert_eq!(&toml, &default_config); | |
633 | } | |
634 | ||
a2a8927a XL |
635 | #[stable_only_test] |
636 | #[test] | |
637 | fn test_as_not_nightly_channel() { | |
638 | let mut config = Config::default(); | |
639 | assert_eq!(config.was_set().unstable_features(), false); | |
640 | config.set().unstable_features(true); | |
641 | assert_eq!(config.was_set().unstable_features(), false); | |
642 | } | |
643 | ||
644 | #[nightly_only_test] | |
645 | #[test] | |
646 | fn test_as_nightly_channel() { | |
647 | let mut config = Config::default(); | |
648 | config.set().unstable_features(true); | |
649 | // When we don't set the config from toml or command line options it | |
650 | // doesn't get marked as set by the user. | |
651 | assert_eq!(config.was_set().unstable_features(), false); | |
652 | config.set().unstable_features(true); | |
653 | assert_eq!(config.unstable_features(), true); | |
654 | } | |
655 | ||
656 | #[nightly_only_test] | |
657 | #[test] | |
658 | fn test_unstable_from_toml() { | |
659 | let config = Config::from_toml("unstable_features = true", Path::new("")).unwrap(); | |
660 | assert_eq!(config.was_set().unstable_features(), true); | |
661 | assert_eq!(config.unstable_features(), true); | |
662 | } | |
f20569fa XL |
663 | |
664 | #[cfg(test)] | |
665 | mod deprecated_option_merge_imports { | |
666 | use super::*; | |
667 | ||
a2a8927a | 668 | #[nightly_only_test] |
f20569fa XL |
669 | #[test] |
670 | fn test_old_option_set() { | |
f20569fa XL |
671 | let toml = r#" |
672 | unstable_features = true | |
673 | merge_imports = true | |
674 | "#; | |
675 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
676 | assert_eq!(config.imports_granularity(), ImportGranularity::Crate); | |
677 | } | |
678 | ||
a2a8927a | 679 | #[nightly_only_test] |
f20569fa XL |
680 | #[test] |
681 | fn test_both_set() { | |
f20569fa XL |
682 | let toml = r#" |
683 | unstable_features = true | |
684 | merge_imports = true | |
685 | imports_granularity = "Preserve" | |
686 | "#; | |
687 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
688 | assert_eq!(config.imports_granularity(), ImportGranularity::Preserve); | |
689 | } | |
690 | ||
a2a8927a | 691 | #[nightly_only_test] |
f20569fa XL |
692 | #[test] |
693 | fn test_new_overridden() { | |
f20569fa XL |
694 | let toml = r#" |
695 | unstable_features = true | |
696 | merge_imports = true | |
697 | "#; | |
698 | let mut config = Config::from_toml(toml, Path::new("")).unwrap(); | |
699 | config.override_value("imports_granularity", "Preserve"); | |
700 | assert_eq!(config.imports_granularity(), ImportGranularity::Preserve); | |
701 | } | |
702 | ||
a2a8927a | 703 | #[nightly_only_test] |
f20569fa XL |
704 | #[test] |
705 | fn test_old_overridden() { | |
f20569fa XL |
706 | let toml = r#" |
707 | unstable_features = true | |
708 | imports_granularity = "Module" | |
709 | "#; | |
710 | let mut config = Config::from_toml(toml, Path::new("")).unwrap(); | |
711 | config.override_value("merge_imports", "true"); | |
712 | // no effect: the new option always takes precedence | |
713 | assert_eq!(config.imports_granularity(), ImportGranularity::Module); | |
714 | } | |
715 | } | |
cdc7bbd5 XL |
716 | |
717 | #[cfg(test)] | |
718 | mod use_small_heuristics { | |
719 | use super::*; | |
720 | ||
721 | #[test] | |
722 | fn test_default_sets_correct_widths() { | |
723 | let toml = r#" | |
724 | use_small_heuristics = "Default" | |
725 | max_width = 200 | |
726 | "#; | |
727 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
728 | assert_eq!(config.array_width(), 120); | |
729 | assert_eq!(config.attr_fn_like_width(), 140); | |
730 | assert_eq!(config.chain_width(), 120); | |
731 | assert_eq!(config.fn_call_width(), 120); | |
732 | assert_eq!(config.single_line_if_else_max_width(), 100); | |
733 | assert_eq!(config.struct_lit_width(), 36); | |
734 | assert_eq!(config.struct_variant_width(), 70); | |
735 | } | |
736 | ||
737 | #[test] | |
738 | fn test_max_sets_correct_widths() { | |
739 | let toml = r#" | |
740 | use_small_heuristics = "Max" | |
741 | max_width = 120 | |
742 | "#; | |
743 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
744 | assert_eq!(config.array_width(), 120); | |
745 | assert_eq!(config.attr_fn_like_width(), 120); | |
746 | assert_eq!(config.chain_width(), 120); | |
747 | assert_eq!(config.fn_call_width(), 120); | |
748 | assert_eq!(config.single_line_if_else_max_width(), 120); | |
749 | assert_eq!(config.struct_lit_width(), 120); | |
750 | assert_eq!(config.struct_variant_width(), 120); | |
751 | } | |
752 | ||
753 | #[test] | |
754 | fn test_off_sets_correct_widths() { | |
755 | let toml = r#" | |
756 | use_small_heuristics = "Off" | |
757 | max_width = 100 | |
758 | "#; | |
759 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
760 | assert_eq!(config.array_width(), usize::max_value()); | |
761 | assert_eq!(config.attr_fn_like_width(), usize::max_value()); | |
762 | assert_eq!(config.chain_width(), usize::max_value()); | |
763 | assert_eq!(config.fn_call_width(), usize::max_value()); | |
764 | assert_eq!(config.single_line_if_else_max_width(), 0); | |
765 | assert_eq!(config.struct_lit_width(), 0); | |
766 | assert_eq!(config.struct_variant_width(), 0); | |
767 | } | |
768 | ||
769 | #[test] | |
770 | fn test_override_works_with_default() { | |
771 | let toml = r#" | |
772 | use_small_heuristics = "Default" | |
773 | array_width = 20 | |
774 | attr_fn_like_width = 40 | |
775 | chain_width = 20 | |
776 | fn_call_width = 90 | |
777 | single_line_if_else_max_width = 40 | |
778 | struct_lit_width = 30 | |
779 | struct_variant_width = 34 | |
780 | "#; | |
781 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
782 | assert_eq!(config.array_width(), 20); | |
783 | assert_eq!(config.attr_fn_like_width(), 40); | |
784 | assert_eq!(config.chain_width(), 20); | |
785 | assert_eq!(config.fn_call_width(), 90); | |
786 | assert_eq!(config.single_line_if_else_max_width(), 40); | |
787 | assert_eq!(config.struct_lit_width(), 30); | |
788 | assert_eq!(config.struct_variant_width(), 34); | |
789 | } | |
790 | ||
791 | #[test] | |
792 | fn test_override_with_max() { | |
793 | let toml = r#" | |
794 | use_small_heuristics = "Max" | |
795 | array_width = 20 | |
796 | attr_fn_like_width = 40 | |
797 | chain_width = 20 | |
798 | fn_call_width = 90 | |
799 | single_line_if_else_max_width = 40 | |
800 | struct_lit_width = 30 | |
801 | struct_variant_width = 34 | |
802 | "#; | |
803 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
804 | assert_eq!(config.array_width(), 20); | |
805 | assert_eq!(config.attr_fn_like_width(), 40); | |
806 | assert_eq!(config.chain_width(), 20); | |
807 | assert_eq!(config.fn_call_width(), 90); | |
808 | assert_eq!(config.single_line_if_else_max_width(), 40); | |
809 | assert_eq!(config.struct_lit_width(), 30); | |
810 | assert_eq!(config.struct_variant_width(), 34); | |
811 | } | |
812 | ||
813 | #[test] | |
814 | fn test_override_with_off() { | |
815 | let toml = r#" | |
816 | use_small_heuristics = "Off" | |
817 | array_width = 20 | |
818 | attr_fn_like_width = 40 | |
819 | chain_width = 20 | |
820 | fn_call_width = 90 | |
821 | single_line_if_else_max_width = 40 | |
822 | struct_lit_width = 30 | |
823 | struct_variant_width = 34 | |
824 | "#; | |
825 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
826 | assert_eq!(config.array_width(), 20); | |
827 | assert_eq!(config.attr_fn_like_width(), 40); | |
828 | assert_eq!(config.chain_width(), 20); | |
829 | assert_eq!(config.fn_call_width(), 90); | |
830 | assert_eq!(config.single_line_if_else_max_width(), 40); | |
831 | assert_eq!(config.struct_lit_width(), 30); | |
832 | assert_eq!(config.struct_variant_width(), 34); | |
833 | } | |
834 | ||
835 | #[test] | |
836 | fn test_fn_call_width_config_exceeds_max_width() { | |
837 | let toml = r#" | |
838 | max_width = 90 | |
839 | fn_call_width = 95 | |
840 | "#; | |
841 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
842 | assert_eq!(config.fn_call_width(), 90); | |
843 | } | |
844 | ||
845 | #[test] | |
846 | fn test_attr_fn_like_width_config_exceeds_max_width() { | |
847 | let toml = r#" | |
848 | max_width = 80 | |
849 | attr_fn_like_width = 90 | |
850 | "#; | |
851 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
852 | assert_eq!(config.attr_fn_like_width(), 80); | |
853 | } | |
854 | ||
855 | #[test] | |
856 | fn test_struct_lit_config_exceeds_max_width() { | |
857 | let toml = r#" | |
858 | max_width = 78 | |
859 | struct_lit_width = 90 | |
860 | "#; | |
861 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
862 | assert_eq!(config.struct_lit_width(), 78); | |
863 | } | |
864 | ||
865 | #[test] | |
866 | fn test_struct_variant_width_config_exceeds_max_width() { | |
867 | let toml = r#" | |
868 | max_width = 80 | |
869 | struct_variant_width = 90 | |
870 | "#; | |
871 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
872 | assert_eq!(config.struct_variant_width(), 80); | |
873 | } | |
874 | ||
875 | #[test] | |
876 | fn test_array_width_config_exceeds_max_width() { | |
877 | let toml = r#" | |
878 | max_width = 60 | |
879 | array_width = 80 | |
880 | "#; | |
881 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
882 | assert_eq!(config.array_width(), 60); | |
883 | } | |
884 | ||
885 | #[test] | |
886 | fn test_chain_width_config_exceeds_max_width() { | |
887 | let toml = r#" | |
888 | max_width = 80 | |
889 | chain_width = 90 | |
890 | "#; | |
891 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
892 | assert_eq!(config.chain_width(), 80); | |
893 | } | |
894 | ||
895 | #[test] | |
896 | fn test_single_line_if_else_max_width_config_exceeds_max_width() { | |
897 | let toml = r#" | |
898 | max_width = 70 | |
899 | single_line_if_else_max_width = 90 | |
900 | "#; | |
901 | let config = Config::from_toml(toml, Path::new("")).unwrap(); | |
902 | assert_eq!(config.single_line_if_else_max_width(), 70); | |
903 | } | |
904 | ||
905 | #[test] | |
906 | fn test_override_fn_call_width_exceeds_max_width() { | |
907 | let mut config = Config::default(); | |
908 | config.override_value("fn_call_width", "101"); | |
909 | assert_eq!(config.fn_call_width(), 100); | |
910 | } | |
911 | ||
912 | #[test] | |
913 | fn test_override_attr_fn_like_width_exceeds_max_width() { | |
914 | let mut config = Config::default(); | |
915 | config.override_value("attr_fn_like_width", "101"); | |
916 | assert_eq!(config.attr_fn_like_width(), 100); | |
917 | } | |
918 | ||
919 | #[test] | |
920 | fn test_override_struct_lit_exceeds_max_width() { | |
921 | let mut config = Config::default(); | |
922 | config.override_value("struct_lit_width", "101"); | |
923 | assert_eq!(config.struct_lit_width(), 100); | |
924 | } | |
925 | ||
926 | #[test] | |
927 | fn test_override_struct_variant_width_exceeds_max_width() { | |
928 | let mut config = Config::default(); | |
929 | config.override_value("struct_variant_width", "101"); | |
930 | assert_eq!(config.struct_variant_width(), 100); | |
931 | } | |
932 | ||
933 | #[test] | |
934 | fn test_override_array_width_exceeds_max_width() { | |
935 | let mut config = Config::default(); | |
936 | config.override_value("array_width", "101"); | |
937 | assert_eq!(config.array_width(), 100); | |
938 | } | |
939 | ||
940 | #[test] | |
941 | fn test_override_chain_width_exceeds_max_width() { | |
942 | let mut config = Config::default(); | |
943 | config.override_value("chain_width", "101"); | |
944 | assert_eq!(config.chain_width(), 100); | |
945 | } | |
946 | ||
947 | #[test] | |
948 | fn test_override_single_line_if_else_max_width_exceeds_max_width() { | |
949 | let mut config = Config::default(); | |
950 | config.override_value("single_line_if_else_max_width", "101"); | |
951 | assert_eq!(config.single_line_if_else_max_width(), 100); | |
952 | } | |
953 | } | |
f20569fa | 954 | } |