2 use std::default::Default;
4 use std::io::{Error, ErrorKind, Read};
5 use std::path::{Path, PathBuf};
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::*;
20 pub(crate) mod config_type;
22 pub(crate) mod options;
24 pub(crate) mod file_lines;
25 pub(crate) mod license;
28 // This macro defines configuration options used in rustfmt. Each option
29 // is defined as follows:
31 // `name: value type, default value, is stable, description;`
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";
38 use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different \
39 formatting for items and expressions if they satisfy a heuristic notion of 'small'";
40 indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items";
42 // Comments. macros, and strings
43 wrap_comments: bool, false, false, "Break comments to fit on the line";
44 format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments.";
45 comment_width: usize, 80, false,
46 "Maximum length of comments. No effect unless wrap_comments = true";
47 normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
48 normalize_doc_attributes: bool, false, false, "Normalize doc attributes as doc comments";
49 license_template_path: String, String::default(), false,
50 "Beginning of file must match license template";
51 format_strings: bool, false, false, "Format string literals where necessary";
52 format_macro_matchers: bool, false, false,
53 "Format the metavariable matching patterns in macros";
54 format_macro_bodies: bool, true, false, "Format the bodies of macros";
56 // Single line expressions and items
57 empty_item_single_line: bool, true, false,
58 "Put empty-body functions and impls on a single line";
59 struct_lit_single_line: bool, true, false,
60 "Put small struct literals on a single line";
61 fn_single_line: bool, false, false, "Put single-expression functions on a single line";
62 where_single_line: bool, false, false, "Force where-clauses to be on a single line";
65 imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports";
66 imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
67 merge_imports: bool, false, false, "Merge imports";
70 reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically";
71 reorder_modules: bool, true, true, "Reorder module statements alphabetically in group";
72 reorder_impl_items: bool, false, false, "Reorder impl items";
74 // Spaces around punctuation
75 type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
76 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
77 space_before_colon: bool, false, false, "Leave a space before the colon";
78 space_after_colon: bool, true, false, "Leave a space after the colon";
79 spaces_around_ranges: bool, false, false, "Put spaces around the .. and ..= range operators";
80 binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
81 "Where to put a binary operator when a binary expression goes multiline";
84 remove_nested_parens: bool, true, true, "Remove nested parens";
85 combine_control_expr: bool, true, false, "Combine control expressions with function calls";
86 overflow_delimited_expr: bool, false, false,
87 "Allow trailing bracket/brace delimited expressions to overflow";
88 struct_field_align_threshold: usize, 0, false,
89 "Align struct fields if their diffs fits within threshold";
90 enum_discrim_align_threshold: usize, 0, false,
91 "Align enum variants discrims, if their diffs fit within threshold";
92 match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
93 the same line with the pattern of arms";
94 match_arm_leading_pipes: MatchArmLeadingPipe, MatchArmLeadingPipe::Never, true,
95 "Determines whether leading pipes are emitted on match 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_layout: Density, Density::Tall, true,
99 "Control the layout of arguments in a function";
100 brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
101 control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
102 "Brace style for control flow constructs";
103 trailing_semicolon: bool, true, false,
104 "Add trailing semicolon after break, continue and return";
105 trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
106 "How to handle trailing commas for lists";
107 match_block_trailing_comma: bool, false, false,
108 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
109 blank_lines_upper_bound: usize, 1, false,
110 "Maximum number of blank lines which can be put between items";
111 blank_lines_lower_bound: usize, 0, false,
112 "Minimum number of blank lines which must be put between items";
113 edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)";
114 version: Version, Version::One, false, "Version of formatting rules";
115 inline_attribute_width: usize, 0, false,
116 "Write an item and its attribute on the same line \
117 if their combined width is below a threshold";
119 // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
120 merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
121 use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand";
122 use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible";
123 force_explicit_abi: bool, true, true, "Always print the abi for extern items";
124 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
127 // Control options (changes the operation of rustfmt, rather than the formatting)
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, false,
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, false, 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 ignore: IgnoreList, IgnoreList::default(), false,
146 "Skip formatting the specified files and directories";
149 verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user";
150 file_lines: FileLines, FileLines::all(), false,
151 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
152 via the --file-lines option";
153 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
154 "'small' heuristic values";
155 emit_mode: EmitMode, EmitMode::Files, false,
156 "What emit Mode to use when none is supplied";
157 make_backup: bool, false, false, "Backup changed files";
158 print_misformatted_file_names: bool, false, true,
159 "Prints the names of mismatched files that were formatted. Prints the names of \
160 files that would be formated when used with `--check` mode. ";
163 #[derive(Error, Debug)]
164 #[error("Could not output config: {0}")]
165 pub struct ToTomlError(toml::ser::Error);
168 pub fn to_toml(&self) -> Result<String, ToTomlError> {
169 // Non-user-facing options can't be specified in TOML
170 let mut cloned = self.clone();
171 cloned.file_lines = None;
172 cloned.verbose = None;
173 cloned.width_heuristics = None;
174 cloned.print_misformatted_file_names = None;
176 ::toml::to_string(&cloned).map_err(ToTomlError)
181 pub(crate) fn version_meets_requirement(&self) -> bool {
182 if self.was_set().required_version() {
183 let version = env!("CARGO_PKG_VERSION");
184 let required_version = self.required_version();
185 if version != required_version {
187 "Error: rustfmt version ({}) doesn't match the required version ({})",
188 version, required_version,
197 /// Constructs a `Config` from the toml file specified at `file_path`.
199 /// This method only looks at the provided path, for a method that
200 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
202 /// Returns a `Config` if the config could be read and parsed from
203 /// the file, otherwise errors.
204 pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
205 let mut file = File::open(&file_path)?;
206 let mut toml = String::new();
207 file.read_to_string(&mut toml)?;
208 Config::from_toml(&toml, file_path.parent().unwrap())
209 .map_err(|err| Error::new(ErrorKind::InvalidData, err))
212 /// Resolves the config for input in `dir`.
214 /// Searches for `rustfmt.toml` beginning with `dir`, and
215 /// recursively checking parents of `dir` if no config file is found.
216 /// If no config file exists in `dir` or in any parent, a
217 /// default `Config` will be returned (and the returned path will be empty).
219 /// Returns the `Config` to use, and the path of the project file if there was
221 pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
222 /// Try to find a project file in the given directory and its parents.
223 /// Returns the path of a the nearest project file if one exists,
224 /// or `None` if no project file was found.
225 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
226 let mut current = if dir.is_relative() {
227 env::current_dir()?.join(dir)
232 current = fs::canonicalize(current)?;
235 match get_toml_path(¤t) {
236 Ok(Some(path)) => return Ok(Some(path)),
237 Err(e) => return Err(e),
241 // If the current directory has no parent, we're done searching.
247 // If nothing was found, check in the home directory.
248 if let Some(home_dir) = dirs::home_dir() {
249 if let Some(path) = get_toml_path(&home_dir)? {
250 return Ok(Some(path));
254 // If none was found ther either, check in the user's configuration directory.
255 if let Some(mut config_dir) = dirs::config_dir() {
256 config_dir.push("rustfmt");
257 if let Some(path) = get_toml_path(&config_dir)? {
258 return Ok(Some(path));
265 match resolve_project_file(dir)? {
266 None => Ok((Config::default(), None)),
267 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
271 pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
272 let parsed: ::toml::Value = toml
274 .map_err(|e| format!("Could not parse TOML: {}", e))?;
275 let mut err = String::new();
278 .ok_or_else(|| String::from("Parsed config was not table"))?;
279 for key in table.keys() {
280 if !Config::is_valid_name(key) {
281 let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
285 match parsed.try_into() {
286 Ok(parsed_config) => {
290 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
293 err.push_str("Error: Decoding config file failed:\n");
294 err.push_str(format!("{}\n", e).as_str());
295 err.push_str("Please check your config file.");
302 /// Loads a config by checking the client-supplied options and if appropriate, the
303 /// file system (including searching the file system for overrides).
304 pub fn load_config<O: CliOptions>(
305 file_path: Option<&Path>,
307 ) -> Result<(Config, Option<PathBuf>), Error> {
308 let over_ride = match options {
309 Some(ref opts) => config_path(opts)?,
313 let result = if let Some(over_ride) = over_ride {
314 Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
315 } else if let Some(file_path) = file_path {
316 Config::from_resolved_toml_path(file_path)
318 Ok((Config::default(), None))
321 result.map(|(mut c, p)| {
322 if let Some(options) = options {
323 options.apply_to(&mut c);
329 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
331 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
332 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
333 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
334 for config_file_name in &CONFIG_FILE_NAMES {
335 let config_file = dir.join(config_file_name);
336 match fs::metadata(&config_file) {
337 // Only return if it's a file to handle the unlikely situation of a directory named
339 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
340 // Return the error if it's something other than `NotFound`; otherwise we didn't
341 // find the project file yet, and continue searching.
343 if e.kind() != ErrorKind::NotFound {
353 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
354 let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
358 "Error: unable to find a config file for the given path: `{}`",
364 // Read the config_path and convert to parent dir if a file is provided.
365 // If a config file cannot be found from the given path, return error.
366 match options.config_path() {
367 Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
368 Some(path) if path.is_dir() => {
369 let config_file_path = get_toml_path(path)?;
370 if config_file_path.is_some() {
373 config_path_not_found(path.to_str().unwrap())
376 path => Ok(path.map(ToOwned::to_owned)),
390 // Options that are used by the generated functions
391 max_width: usize, 100, true, "Maximum width of each line";
392 use_small_heuristics: Heuristics, Heuristics::Default, true,
393 "Whether to use different formatting for items and \
394 expressions if they satisfy a heuristic notion of 'small'.";
395 license_template_path: String, String::default(), false,
396 "Beginning of file must match license template";
397 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
398 "Require a specific version of rustfmt.";
399 ignore: IgnoreList, IgnoreList::default(), false,
400 "Skip formatting the specified files and directories.";
401 verbose: Verbosity, Verbosity::Normal, false,
402 "How much to information to emit to the user";
403 file_lines: FileLines, FileLines::all(), false,
404 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
405 via the --file-lines option";
406 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
407 "'small' heuristic values";
409 // Options that are used by the tests
410 stable_option: bool, false, true, "A stable option";
411 unstable_option: bool, false, false, "An unstable option";
416 fn test_config_set() {
417 let mut config = Config::default();
418 config.set().verbose(Verbosity::Quiet);
419 assert_eq!(config.verbose(), Verbosity::Quiet);
420 config.set().verbose(Verbosity::Normal);
421 assert_eq!(config.verbose(), Verbosity::Normal);
425 fn test_config_used_to_toml() {
426 let config = Config::default();
428 let merge_derives = config.merge_derives();
429 let skip_children = config.skip_children();
431 let used_options = config.used_options();
432 let toml = used_options.to_toml().unwrap();
436 "merge_derives = {}\nskip_children = {}\n",
437 merge_derives, skip_children,
444 let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
446 assert_eq!(config.was_set().hard_tabs(), true);
447 assert_eq!(config.was_set().verbose(), false);
451 fn test_print_docs_exclude_unstable() {
452 use self::mock::Config;
454 let mut output = Vec::new();
455 Config::print_docs(&mut output, false);
457 let s = str::from_utf8(&output).unwrap();
459 assert_eq!(s.contains("stable_option"), true);
460 assert_eq!(s.contains("unstable_option"), false);
461 assert_eq!(s.contains("(unstable)"), false);
465 fn test_print_docs_include_unstable() {
466 use self::mock::Config;
468 let mut output = Vec::new();
469 Config::print_docs(&mut output, true);
471 let s = str::from_utf8(&output).unwrap();
472 assert_eq!(s.contains("stable_option"), true);
473 assert_eq!(s.contains("unstable_option"), true);
474 assert_eq!(s.contains("(unstable)"), true);
478 fn test_empty_string_license_template_path() {
479 let toml = r#"license_template_path = """#;
480 let config = Config::from_toml(toml, Path::new("")).unwrap();
481 assert!(config.license_template.is_none());
485 fn test_valid_license_template_path() {
486 if !crate::is_nightly_channel!() {
489 let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
490 let config = Config::from_toml(toml, Path::new("")).unwrap();
491 assert!(config.license_template.is_some());
495 fn test_override_existing_license_with_no_license() {
496 if !crate::is_nightly_channel!() {
499 let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
500 let mut config = Config::from_toml(toml, Path::new("")).unwrap();
501 assert!(config.license_template.is_some());
502 config.override_value("license_template_path", "");
503 assert!(config.license_template.is_none());
507 fn test_dump_default_config() {
508 let default_config = format!(
512 newline_style = "Auto"
513 use_small_heuristics = "Default"
514 indent_style = "Block"
515 wrap_comments = false
516 format_code_in_doc_comments = false
518 normalize_comments = false
519 normalize_doc_attributes = false
520 license_template_path = ""
521 format_strings = false
522 format_macro_matchers = false
523 format_macro_bodies = true
524 empty_item_single_line = true
525 struct_lit_single_line = true
526 fn_single_line = false
527 where_single_line = false
528 imports_indent = "Block"
529 imports_layout = "Mixed"
530 merge_imports = false
531 reorder_imports = true
532 reorder_modules = true
533 reorder_impl_items = false
534 type_punctuation_density = "Wide"
535 space_before_colon = false
536 space_after_colon = true
537 spaces_around_ranges = false
538 binop_separator = "Front"
539 remove_nested_parens = true
540 combine_control_expr = true
541 overflow_delimited_expr = false
542 struct_field_align_threshold = 0
543 enum_discrim_align_threshold = 0
544 match_arm_blocks = true
545 match_arm_leading_pipes = "Never"
546 force_multiline_blocks = false
547 fn_args_layout = "Tall"
548 brace_style = "SameLineWhere"
549 control_brace_style = "AlwaysSameLine"
550 trailing_semicolon = true
551 trailing_comma = "Vertical"
552 match_block_trailing_comma = false
553 blank_lines_upper_bound = 1
554 blank_lines_lower_bound = 0
557 inline_attribute_width = 0
559 use_try_shorthand = false
560 use_field_init_shorthand = false
561 force_explicit_abi = true
562 condense_wildcard_suffixes = false
564 required_version = "{}"
565 unstable_features = false
566 disable_all_formatting = false
567 skip_children = false
568 hide_parse_errors = false
569 error_on_line_overflow = false
570 error_on_unformatted = false
571 report_todo = "Never"
572 report_fixme = "Never"
577 env!("CARGO_PKG_VERSION")
579 let toml = Config::default().all_options().to_toml().unwrap();
580 assert_eq!(&toml, &default_config);
583 // FIXME(#2183): these tests cannot be run in parallel because they use env vars.
585 // fn test_as_not_nightly_channel() {
586 // let mut config = Config::default();
587 // assert_eq!(config.was_set().unstable_features(), false);
588 // config.set().unstable_features(true);
589 // assert_eq!(config.was_set().unstable_features(), false);
593 // fn test_as_nightly_channel() {
594 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
595 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
596 // let mut config = Config::default();
597 // config.set().unstable_features(true);
598 // assert_eq!(config.was_set().unstable_features(), false);
599 // config.set().unstable_features(true);
600 // assert_eq!(config.unstable_features(), true);
601 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
605 // fn test_unstable_from_toml() {
606 // let mut config = Config::from_toml("unstable_features = true").unwrap();
607 // assert_eq!(config.was_set().unstable_features(), false);
608 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
609 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
610 // config = Config::from_toml("unstable_features = true").unwrap();
611 // assert_eq!(config.was_set().unstable_features(), true);
612 // assert_eq!(config.unstable_features(), true);
613 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);