2 use std::default::Default;
4 use std::io::{Error, ErrorKind, Read};
5 use std::path::{Path, PathBuf};
10 use crate::config::config_type::ConfigType;
11 #[allow(unreachable_pub)]
12 pub use crate::config::file_lines::{FileLines, FileName, Range};
13 #[allow(unreachable_pub)]
14 pub use crate::config::lists::*;
15 #[allow(unreachable_pub)]
16 pub use crate::config::options::*;
19 pub(crate) mod config_type;
21 pub(crate) mod options;
23 pub(crate) mod file_lines;
24 pub(crate) mod license;
27 // This macro defines configuration options used in rustfmt. Each option
28 // is defined as follows:
30 // `name: value type, default value, is stable, description;`
33 max_width: usize, 100, true, "Maximum width of each line";
34 hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment";
35 tab_spaces: usize, 4, true, "Number of spaces per tab";
36 newline_style: NewlineStyle, NewlineStyle::Auto, true, "Unix or Windows line endings";
37 use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different \
38 formatting for items and expressions if they satisfy a heuristic notion of 'small'";
39 indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items";
41 // Comments. macros, and strings
42 wrap_comments: bool, false, false, "Break comments to fit on the line";
43 format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments.";
44 comment_width: usize, 80, false,
45 "Maximum length of comments. No effect unless wrap_comments = true";
46 normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
47 normalize_doc_attributes: bool, false, false, "Normalize doc attributes as doc comments";
48 license_template_path: String, String::default(), false,
49 "Beginning of file must match license template";
50 format_strings: bool, false, false, "Format string literals where necessary";
51 format_macro_matchers: bool, false, false,
52 "Format the metavariable matching patterns in macros";
53 format_macro_bodies: bool, true, false, "Format the bodies of macros";
55 // Single line expressions and items
56 empty_item_single_line: bool, true, false,
57 "Put empty-body functions and impls on a single line";
58 struct_lit_single_line: bool, true, false,
59 "Put small struct literals on a single line";
60 fn_single_line: bool, false, false, "Put single-expression functions on a single line";
61 where_single_line: bool, false, false, "Force where-clauses to be on a single line";
64 imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports";
65 imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
66 merge_imports: bool, false, false, "Merge imports";
69 reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically";
70 reorder_modules: bool, true, true, "Reorder module statements alphabetically in group";
71 reorder_impl_items: bool, false, false, "Reorder impl items";
73 // Spaces around punctuation
74 type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
75 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
76 space_before_colon: bool, false, false, "Leave a space before the colon";
77 space_after_colon: bool, true, false, "Leave a space after the colon";
78 spaces_around_ranges: bool, false, false, "Put spaces around the .. and ..= range operators";
79 binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
80 "Where to put a binary operator when a binary expression goes multiline";
83 remove_nested_parens: bool, true, true, "Remove nested parens";
84 combine_control_expr: bool, true, false, "Combine control expressions with function calls";
85 overflow_delimited_expr: bool, false, false,
86 "Allow trailing bracket/brace delimited expressions to overflow";
87 struct_field_align_threshold: usize, 0, false,
88 "Align struct fields if their diffs fits within threshold";
89 enum_discrim_align_threshold: usize, 0, false,
90 "Align enum variants discrims, if their diffs fit within threshold";
91 match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
92 the same line with the pattern of arms";
93 force_multiline_blocks: bool, false, false,
94 "Force multiline closure bodies and match arms to be wrapped in a block";
95 fn_args_layout: Density, Density::Tall, true,
96 "Control the layout of arguments in a function";
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, true, "The edition of the parser (RFC 2052)";
111 version: Version, Version::One, false, "Version of formatting rules";
112 inline_attribute_width: usize, 0, false,
113 "Write an item and its attribute on the same line \
114 if their combined width is below a threshold";
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, true, "Replace uses of the try! macro by the ? shorthand";
119 use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible";
120 force_explicit_abi: bool, true, true, "Always print the abi for extern items";
121 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
124 // Control options (changes the operation of rustfmt, rather than the formatting)
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, false,
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: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user";
147 file_lines: FileLines, FileLines::all(), false,
148 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
149 via the --file-lines option";
150 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
151 "'small' heuristic values";
152 emit_mode: EmitMode, EmitMode::Files, false,
153 "What emit Mode to use when none is supplied";
154 make_backup: bool, false, false, "Backup changed files";
158 pub fn to_toml(&self) -> Result<String, String> {
159 // Non-user-facing options can't be specified in TOML
160 let mut cloned = self.clone();
161 cloned.file_lines = None;
162 cloned.verbose = None;
163 cloned.width_heuristics = None;
165 ::toml::to_string(&cloned).map_err(|e| format!("Could not output config: {}", e))
170 pub(crate) fn version_meets_requirement(&self) -> bool {
171 if self.was_set().required_version() {
172 let version = env!("CARGO_PKG_VERSION");
173 let required_version = self.required_version();
174 if version != required_version {
176 "Error: rustfmt version ({}) doesn't match the required version ({})",
177 version, required_version,
186 /// Constructs a `Config` from the toml file specified at `file_path`.
188 /// This method only looks at the provided path, for a method that
189 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
191 /// Returns a `Config` if the config could be read and parsed from
192 /// the file, otherwise errors.
193 pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
194 let mut file = File::open(&file_path)?;
195 let mut toml = String::new();
196 file.read_to_string(&mut toml)?;
197 Config::from_toml(&toml, file_path.parent().unwrap())
198 .map_err(|err| Error::new(ErrorKind::InvalidData, err))
201 /// Resolves the config for input in `dir`.
203 /// Searches for `rustfmt.toml` beginning with `dir`, and
204 /// recursively checking parents of `dir` if no config file is found.
205 /// If no config file exists in `dir` or in any parent, a
206 /// default `Config` will be returned (and the returned path will be empty).
208 /// Returns the `Config` to use, and the path of the project file if there was
210 pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
211 /// Try to find a project file in the given directory and its parents.
212 /// Returns the path of a the nearest project file if one exists,
213 /// or `None` if no project file was found.
214 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
215 let mut current = if dir.is_relative() {
216 env::current_dir()?.join(dir)
221 current = fs::canonicalize(current)?;
224 match get_toml_path(¤t) {
225 Ok(Some(path)) => return Ok(Some(path)),
226 Err(e) => return Err(e),
230 // If the current directory has no parent, we're done searching.
236 // If nothing was found, check in the home directory.
237 if let Some(home_dir) = dirs::home_dir() {
238 if let Some(path) = get_toml_path(&home_dir)? {
239 return Ok(Some(path));
243 // If none was found ther either, check in the user's configuration directory.
244 if let Some(mut config_dir) = dirs::config_dir() {
245 config_dir.push("rustfmt");
246 if let Some(path) = get_toml_path(&config_dir)? {
247 return Ok(Some(path));
254 match resolve_project_file(dir)? {
255 None => Ok((Config::default(), None)),
256 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
260 pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
261 let parsed: ::toml::Value = toml
263 .map_err(|e| format!("Could not parse TOML: {}", e))?;
264 let mut err = String::new();
267 .ok_or_else(|| String::from("Parsed config was not table"))?;
268 for key in table.keys() {
269 if !Config::is_valid_name(key) {
270 let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
274 match parsed.try_into() {
275 Ok(parsed_config) => {
279 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
282 err.push_str("Error: Decoding config file failed:\n");
283 err.push_str(format!("{}\n", e).as_str());
284 err.push_str("Please check your config file.");
291 /// Loads a config by checking the client-supplied options and if appropriate, the
292 /// file system (including searching the file system for overrides).
293 pub fn load_config<O: CliOptions>(
294 file_path: Option<&Path>,
296 ) -> Result<(Config, Option<PathBuf>), Error> {
297 let over_ride = match options {
298 Some(ref opts) => config_path(opts)?,
302 let result = if let Some(over_ride) = over_ride {
303 Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
304 } else if let Some(file_path) = file_path {
305 Config::from_resolved_toml_path(file_path)
307 Ok((Config::default(), None))
310 result.map(|(mut c, p)| {
311 if let Some(options) = options {
312 options.apply_to(&mut c);
318 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
320 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
321 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
322 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
323 for config_file_name in &CONFIG_FILE_NAMES {
324 let config_file = dir.join(config_file_name);
325 match fs::metadata(&config_file) {
326 // Only return if it's a file to handle the unlikely situation of a directory named
328 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
329 // Return the error if it's something other than `NotFound`; otherwise we didn't
330 // find the project file yet, and continue searching.
332 if e.kind() != ErrorKind::NotFound {
342 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
343 let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
347 "Error: unable to find a config file for the given path: `{}`",
353 // Read the config_path and convert to parent dir if a file is provided.
354 // If a config file cannot be found from the given path, return error.
355 match options.config_path() {
356 Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
357 Some(path) if path.is_dir() => {
358 let config_file_path = get_toml_path(path)?;
359 if config_file_path.is_some() {
362 config_path_not_found(path.to_str().unwrap())
365 path => Ok(path.map(ToOwned::to_owned)),
379 // Options that are used by the generated functions
380 max_width: usize, 100, true, "Maximum width of each line";
381 use_small_heuristics: Heuristics, Heuristics::Default, true,
382 "Whether to use different formatting for items and \
383 expressions if they satisfy a heuristic notion of 'small'.";
384 license_template_path: String, String::default(), false,
385 "Beginning of file must match license template";
386 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
387 "Require a specific version of rustfmt.";
388 ignore: IgnoreList, IgnoreList::default(), false,
389 "Skip formatting the specified files and directories.";
390 verbose: Verbosity, Verbosity::Normal, false,
391 "How much to information to emit to the user";
392 file_lines: FileLines, FileLines::all(), false,
393 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
394 via the --file-lines option";
395 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
396 "'small' heuristic values";
398 // Options that are used by the tests
399 stable_option: bool, false, true, "A stable option";
400 unstable_option: bool, false, false, "An unstable option";
405 fn test_config_set() {
406 let mut config = Config::default();
407 config.set().verbose(Verbosity::Quiet);
408 assert_eq!(config.verbose(), Verbosity::Quiet);
409 config.set().verbose(Verbosity::Normal);
410 assert_eq!(config.verbose(), Verbosity::Normal);
414 fn test_config_used_to_toml() {
415 let config = Config::default();
417 let merge_derives = config.merge_derives();
418 let skip_children = config.skip_children();
420 let used_options = config.used_options();
421 let toml = used_options.to_toml().unwrap();
425 "merge_derives = {}\nskip_children = {}\n",
426 merge_derives, skip_children,
433 let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
435 assert_eq!(config.was_set().hard_tabs(), true);
436 assert_eq!(config.was_set().verbose(), false);
440 fn test_print_docs_exclude_unstable() {
441 use self::mock::Config;
443 let mut output = Vec::new();
444 Config::print_docs(&mut output, false);
446 let s = str::from_utf8(&output).unwrap();
448 assert_eq!(s.contains("stable_option"), true);
449 assert_eq!(s.contains("unstable_option"), false);
450 assert_eq!(s.contains("(unstable)"), false);
454 fn test_print_docs_include_unstable() {
455 use self::mock::Config;
457 let mut output = Vec::new();
458 Config::print_docs(&mut output, true);
460 let s = str::from_utf8(&output).unwrap();
461 assert_eq!(s.contains("stable_option"), true);
462 assert_eq!(s.contains("unstable_option"), true);
463 assert_eq!(s.contains("(unstable)"), true);
467 fn test_dump_default_config() {
468 const DEFAULT_CONFIG: &str = r#"max_width = 100
471 newline_style = "Auto"
472 use_small_heuristics = "Default"
473 indent_style = "Block"
474 wrap_comments = false
475 format_code_in_doc_comments = false
477 normalize_comments = false
478 normalize_doc_attributes = false
479 license_template_path = ""
480 format_strings = false
481 format_macro_matchers = false
482 format_macro_bodies = true
483 empty_item_single_line = true
484 struct_lit_single_line = true
485 fn_single_line = false
486 where_single_line = false
487 imports_indent = "Block"
488 imports_layout = "Mixed"
489 merge_imports = false
490 reorder_imports = true
491 reorder_modules = true
492 reorder_impl_items = false
493 type_punctuation_density = "Wide"
494 space_before_colon = false
495 space_after_colon = true
496 spaces_around_ranges = false
497 binop_separator = "Front"
498 remove_nested_parens = true
499 combine_control_expr = true
500 overflow_delimited_expr = false
501 struct_field_align_threshold = 0
502 enum_discrim_align_threshold = 0
503 match_arm_blocks = true
504 force_multiline_blocks = false
505 fn_args_layout = "Tall"
506 brace_style = "SameLineWhere"
507 control_brace_style = "AlwaysSameLine"
508 trailing_semicolon = true
509 trailing_comma = "Vertical"
510 match_block_trailing_comma = false
511 blank_lines_upper_bound = 1
512 blank_lines_lower_bound = 0
515 inline_attribute_width = 0
517 use_try_shorthand = false
518 use_field_init_shorthand = false
519 force_explicit_abi = true
520 condense_wildcard_suffixes = false
522 required_version = "1.3.3"
523 unstable_features = false
524 disable_all_formatting = false
525 skip_children = false
526 hide_parse_errors = false
527 error_on_line_overflow = false
528 error_on_unformatted = false
529 report_todo = "Never"
530 report_fixme = "Never"
535 let toml = Config::default().all_options().to_toml().unwrap();
536 assert_eq!(&toml, DEFAULT_CONFIG);
539 // FIXME(#2183): these tests cannot be run in parallel because they use env vars.
541 // fn test_as_not_nightly_channel() {
542 // let mut config = Config::default();
543 // assert_eq!(config.was_set().unstable_features(), false);
544 // config.set().unstable_features(true);
545 // assert_eq!(config.was_set().unstable_features(), false);
549 // fn test_as_nightly_channel() {
550 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
551 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
552 // let mut config = Config::default();
553 // config.set().unstable_features(true);
554 // assert_eq!(config.was_set().unstable_features(), false);
555 // config.set().unstable_features(true);
556 // assert_eq!(config.unstable_features(), true);
557 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
561 // fn test_unstable_from_toml() {
562 // let mut config = Config::from_toml("unstable_features = true").unwrap();
563 // assert_eq!(config.was_set().unstable_features(), false);
564 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
565 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
566 // config = Config::from_toml("unstable_features = true").unwrap();
567 // assert_eq!(config.was_set().unstable_features(), true);
568 // assert_eq!(config.unstable_features(), true);
569 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);