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 imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
68 "Merge or split imports to the provided granularity";
69 group_imports: GroupImportsTactic, GroupImportsTactic::Preserve, false,
70 "Controls the strategy for how imports are grouped together";
71 merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
74 reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically";
75 reorder_modules: bool, true, true, "Reorder module statements alphabetically in group";
76 reorder_impl_items: bool, false, false, "Reorder impl items";
78 // Spaces around punctuation
79 type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
80 "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
81 space_before_colon: bool, false, false, "Leave a space before the colon";
82 space_after_colon: bool, true, false, "Leave a space after the colon";
83 spaces_around_ranges: bool, false, false, "Put spaces around the .. and ..= range operators";
84 binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
85 "Where to put a binary operator when a binary expression goes multiline";
88 remove_nested_parens: bool, true, true, "Remove nested parens";
89 combine_control_expr: bool, true, false, "Combine control expressions with function calls";
90 overflow_delimited_expr: bool, false, false,
91 "Allow trailing bracket/brace delimited expressions to overflow";
92 struct_field_align_threshold: usize, 0, false,
93 "Align struct fields if their diffs fits within threshold";
94 enum_discrim_align_threshold: usize, 0, false,
95 "Align enum variants discrims, if their diffs fit within threshold";
96 match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
97 the same line with the pattern of arms";
98 match_arm_leading_pipes: MatchArmLeadingPipe, MatchArmLeadingPipe::Never, true,
99 "Determines whether leading pipes are emitted on match arms";
100 force_multiline_blocks: bool, false, false,
101 "Force multiline closure bodies and match arms to be wrapped in a block";
102 fn_args_layout: Density, Density::Tall, true,
103 "Control the layout of arguments in a function";
104 brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
105 control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
106 "Brace style for control flow constructs";
107 trailing_semicolon: bool, true, false,
108 "Add trailing semicolon after break, continue and return";
109 trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
110 "How to handle trailing commas for lists";
111 match_block_trailing_comma: bool, false, false,
112 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
113 blank_lines_upper_bound: usize, 1, false,
114 "Maximum number of blank lines which can be put between items";
115 blank_lines_lower_bound: usize, 0, false,
116 "Minimum number of blank lines which must be put between items";
117 edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)";
118 version: Version, Version::One, false, "Version of formatting rules";
119 inline_attribute_width: usize, 0, false,
120 "Write an item and its attribute on the same line \
121 if their combined width is below a threshold";
123 // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
124 merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
125 use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand";
126 use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible";
127 force_explicit_abi: bool, true, true, "Always print the abi for extern items";
128 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
131 // Control options (changes the operation of rustfmt, rather than the formatting)
132 color: Color, Color::Auto, false,
133 "What Color option to use when none is supplied: Always, Never, Auto";
134 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
135 "Require a specific version of rustfmt";
136 unstable_features: bool, false, false,
137 "Enables unstable features. Only available on nightly channel";
138 disable_all_formatting: bool, false, false, "Don't reformat anything";
139 skip_children: bool, false, false, "Don't reformat out of line modules";
140 hide_parse_errors: bool, false, false, "Hide errors from the parser";
141 error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
142 error_on_unformatted: bool, false, false,
143 "Error if unable to get comments or string literals within max_width, \
144 or they are left with trailing whitespaces";
145 report_todo: ReportTactic, ReportTactic::Never, false,
146 "Report all, none or unnumbered occurrences of TODO in source file comments";
147 report_fixme: ReportTactic, ReportTactic::Never, false,
148 "Report all, none or unnumbered occurrences of FIXME in source file comments";
149 ignore: IgnoreList, IgnoreList::default(), false,
150 "Skip formatting the specified files and directories";
153 verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user";
154 file_lines: FileLines, FileLines::all(), false,
155 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
156 via the --file-lines option";
157 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
158 "'small' heuristic values";
159 emit_mode: EmitMode, EmitMode::Files, false,
160 "What emit Mode to use when none is supplied";
161 make_backup: bool, false, false, "Backup changed files";
162 print_misformatted_file_names: bool, false, true,
163 "Prints the names of mismatched files that were formatted. Prints the names of \
164 files that would be formated when used with `--check` mode. ";
167 #[derive(Error, Debug)]
168 #[error("Could not output config: {0}")]
169 pub struct ToTomlError(toml::ser::Error);
172 pub fn to_toml(&self) -> Result<String, ToTomlError> {
173 // Non-user-facing options can't be specified in TOML
174 let mut cloned = self.clone();
175 cloned.file_lines = None;
176 cloned.verbose = None;
177 cloned.width_heuristics = None;
178 cloned.print_misformatted_file_names = None;
179 cloned.merge_imports = None;
181 ::toml::to_string(&cloned).map_err(ToTomlError)
186 pub(crate) fn version_meets_requirement(&self) -> bool {
187 if self.was_set().required_version() {
188 let version = env!("CARGO_PKG_VERSION");
189 let required_version = self.required_version();
190 if version != required_version {
192 "Error: rustfmt version ({}) doesn't match the required version ({})",
193 version, required_version,
202 /// Constructs a `Config` from the toml file specified at `file_path`.
204 /// This method only looks at the provided path, for a method that
205 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
207 /// Returns a `Config` if the config could be read and parsed from
208 /// the file, otherwise errors.
209 pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
210 let mut file = File::open(&file_path)?;
211 let mut toml = String::new();
212 file.read_to_string(&mut toml)?;
213 Config::from_toml(&toml, file_path.parent().unwrap())
214 .map_err(|err| Error::new(ErrorKind::InvalidData, err))
217 /// Resolves the config for input in `dir`.
219 /// Searches for `rustfmt.toml` beginning with `dir`, and
220 /// recursively checking parents of `dir` if no config file is found.
221 /// If no config file exists in `dir` or in any parent, a
222 /// default `Config` will be returned (and the returned path will be empty).
224 /// Returns the `Config` to use, and the path of the project file if there was
226 pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
227 /// Try to find a project file in the given directory and its parents.
228 /// Returns the path of a the nearest project file if one exists,
229 /// or `None` if no project file was found.
230 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
231 let mut current = if dir.is_relative() {
232 env::current_dir()?.join(dir)
237 current = fs::canonicalize(current)?;
240 match get_toml_path(¤t) {
241 Ok(Some(path)) => return Ok(Some(path)),
242 Err(e) => return Err(e),
246 // If the current directory has no parent, we're done searching.
252 // If nothing was found, check in the home directory.
253 if let Some(home_dir) = dirs::home_dir() {
254 if let Some(path) = get_toml_path(&home_dir)? {
255 return Ok(Some(path));
259 // If none was found ther either, check in the user's configuration directory.
260 if let Some(mut config_dir) = dirs::config_dir() {
261 config_dir.push("rustfmt");
262 if let Some(path) = get_toml_path(&config_dir)? {
263 return Ok(Some(path));
270 match resolve_project_file(dir)? {
271 None => Ok((Config::default(), None)),
272 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
276 pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
277 let parsed: ::toml::Value = toml
279 .map_err(|e| format!("Could not parse TOML: {}", e))?;
280 let mut err = String::new();
283 .ok_or_else(|| String::from("Parsed config was not table"))?;
284 for key in table.keys() {
285 if !Config::is_valid_name(key) {
286 let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
290 match parsed.try_into() {
291 Ok(parsed_config) => {
295 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
298 err.push_str("Error: Decoding config file failed:\n");
299 err.push_str(format!("{}\n", e).as_str());
300 err.push_str("Please check your config file.");
307 /// Loads a config by checking the client-supplied options and if appropriate, the
308 /// file system (including searching the file system for overrides).
309 pub fn load_config<O: CliOptions>(
310 file_path: Option<&Path>,
312 ) -> Result<(Config, Option<PathBuf>), Error> {
313 let over_ride = match options {
314 Some(ref opts) => config_path(opts)?,
318 let result = if let Some(over_ride) = over_ride {
319 Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
320 } else if let Some(file_path) = file_path {
321 Config::from_resolved_toml_path(file_path)
323 Ok((Config::default(), None))
326 result.map(|(mut c, p)| {
327 if let Some(options) = options {
328 options.apply_to(&mut c);
334 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
336 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
337 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
338 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
339 for config_file_name in &CONFIG_FILE_NAMES {
340 let config_file = dir.join(config_file_name);
341 match fs::metadata(&config_file) {
342 // Only return if it's a file to handle the unlikely situation of a directory named
344 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
345 // Return the error if it's something other than `NotFound`; otherwise we didn't
346 // find the project file yet, and continue searching.
348 if e.kind() != ErrorKind::NotFound {
358 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
359 let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
363 "Error: unable to find a config file for the given path: `{}`",
369 // Read the config_path and convert to parent dir if a file is provided.
370 // If a config file cannot be found from the given path, return error.
371 match options.config_path() {
372 Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
373 Some(path) if path.is_dir() => {
374 let config_file_path = get_toml_path(path)?;
375 if config_file_path.is_some() {
378 config_path_not_found(path.to_str().unwrap())
381 path => Ok(path.map(ToOwned::to_owned)),
395 // Options that are used by the generated functions
396 max_width: usize, 100, true, "Maximum width of each line";
397 use_small_heuristics: Heuristics, Heuristics::Default, true,
398 "Whether to use different formatting for items and \
399 expressions if they satisfy a heuristic notion of 'small'.";
400 license_template_path: String, String::default(), false,
401 "Beginning of file must match license template";
402 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
403 "Require a specific version of rustfmt.";
404 ignore: IgnoreList, IgnoreList::default(), false,
405 "Skip formatting the specified files and directories.";
406 verbose: Verbosity, Verbosity::Normal, false,
407 "How much to information to emit to the user";
408 file_lines: FileLines, FileLines::all(), false,
409 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
410 via the --file-lines option";
411 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
412 "'small' heuristic values";
413 // merge_imports deprecation
414 imports_granularity: ImportGranularity, ImportGranularity::Preserve, false,
416 merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
418 // Options that are used by the tests
419 stable_option: bool, false, true, "A stable option";
420 unstable_option: bool, false, false, "An unstable option";
425 fn test_config_set() {
426 let mut config = Config::default();
427 config.set().verbose(Verbosity::Quiet);
428 assert_eq!(config.verbose(), Verbosity::Quiet);
429 config.set().verbose(Verbosity::Normal);
430 assert_eq!(config.verbose(), Verbosity::Normal);
434 fn test_config_used_to_toml() {
435 let config = Config::default();
437 let merge_derives = config.merge_derives();
438 let skip_children = config.skip_children();
440 let used_options = config.used_options();
441 let toml = used_options.to_toml().unwrap();
445 "merge_derives = {}\nskip_children = {}\n",
446 merge_derives, skip_children,
453 let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
455 assert_eq!(config.was_set().hard_tabs(), true);
456 assert_eq!(config.was_set().verbose(), false);
460 fn test_print_docs_exclude_unstable() {
461 use self::mock::Config;
463 let mut output = Vec::new();
464 Config::print_docs(&mut output, false);
466 let s = str::from_utf8(&output).unwrap();
468 assert_eq!(s.contains("stable_option"), true);
469 assert_eq!(s.contains("unstable_option"), false);
470 assert_eq!(s.contains("(unstable)"), false);
474 fn test_print_docs_include_unstable() {
475 use self::mock::Config;
477 let mut output = Vec::new();
478 Config::print_docs(&mut output, true);
480 let s = str::from_utf8(&output).unwrap();
481 assert_eq!(s.contains("stable_option"), true);
482 assert_eq!(s.contains("unstable_option"), true);
483 assert_eq!(s.contains("(unstable)"), true);
487 fn test_empty_string_license_template_path() {
488 let toml = r#"license_template_path = """#;
489 let config = Config::from_toml(toml, Path::new("")).unwrap();
490 assert!(config.license_template.is_none());
494 fn test_valid_license_template_path() {
495 if !crate::is_nightly_channel!() {
498 let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
499 let config = Config::from_toml(toml, Path::new("")).unwrap();
500 assert!(config.license_template.is_some());
504 fn test_override_existing_license_with_no_license() {
505 if !crate::is_nightly_channel!() {
508 let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
509 let mut config = Config::from_toml(toml, Path::new("")).unwrap();
510 assert!(config.license_template.is_some());
511 config.override_value("license_template_path", "");
512 assert!(config.license_template.is_none());
516 fn test_dump_default_config() {
517 let default_config = format!(
521 newline_style = "Auto"
522 use_small_heuristics = "Default"
523 indent_style = "Block"
524 wrap_comments = false
525 format_code_in_doc_comments = false
527 normalize_comments = false
528 normalize_doc_attributes = false
529 license_template_path = ""
530 format_strings = false
531 format_macro_matchers = false
532 format_macro_bodies = true
533 empty_item_single_line = true
534 struct_lit_single_line = true
535 fn_single_line = false
536 where_single_line = false
537 imports_indent = "Block"
538 imports_layout = "Mixed"
539 imports_granularity = "Preserve"
540 group_imports = "Preserve"
541 reorder_imports = true
542 reorder_modules = true
543 reorder_impl_items = false
544 type_punctuation_density = "Wide"
545 space_before_colon = false
546 space_after_colon = true
547 spaces_around_ranges = false
548 binop_separator = "Front"
549 remove_nested_parens = true
550 combine_control_expr = true
551 overflow_delimited_expr = false
552 struct_field_align_threshold = 0
553 enum_discrim_align_threshold = 0
554 match_arm_blocks = true
555 match_arm_leading_pipes = "Never"
556 force_multiline_blocks = false
557 fn_args_layout = "Tall"
558 brace_style = "SameLineWhere"
559 control_brace_style = "AlwaysSameLine"
560 trailing_semicolon = true
561 trailing_comma = "Vertical"
562 match_block_trailing_comma = false
563 blank_lines_upper_bound = 1
564 blank_lines_lower_bound = 0
567 inline_attribute_width = 0
569 use_try_shorthand = false
570 use_field_init_shorthand = false
571 force_explicit_abi = true
572 condense_wildcard_suffixes = false
574 required_version = "{}"
575 unstable_features = false
576 disable_all_formatting = false
577 skip_children = false
578 hide_parse_errors = false
579 error_on_line_overflow = false
580 error_on_unformatted = false
581 report_todo = "Never"
582 report_fixme = "Never"
587 env!("CARGO_PKG_VERSION")
589 let toml = Config::default().all_options().to_toml().unwrap();
590 assert_eq!(&toml, &default_config);
593 // FIXME(#2183): these tests cannot be run in parallel because they use env vars.
595 // fn test_as_not_nightly_channel() {
596 // let mut config = Config::default();
597 // assert_eq!(config.was_set().unstable_features(), false);
598 // config.set().unstable_features(true);
599 // assert_eq!(config.was_set().unstable_features(), false);
603 // fn test_as_nightly_channel() {
604 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
605 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
606 // let mut config = Config::default();
607 // config.set().unstable_features(true);
608 // assert_eq!(config.was_set().unstable_features(), false);
609 // config.set().unstable_features(true);
610 // assert_eq!(config.unstable_features(), true);
611 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
615 // fn test_unstable_from_toml() {
616 // let mut config = Config::from_toml("unstable_features = true").unwrap();
617 // assert_eq!(config.was_set().unstable_features(), false);
618 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
619 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
620 // config = Config::from_toml("unstable_features = true").unwrap();
621 // assert_eq!(config.was_set().unstable_features(), true);
622 // assert_eq!(config.unstable_features(), true);
623 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
627 mod deprecated_option_merge_imports {
631 fn test_old_option_set() {
633 unstable_features = true
636 let config = Config::from_toml(toml, Path::new("")).unwrap();
637 assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
643 unstable_features = true
645 imports_granularity = "Preserve"
647 let config = Config::from_toml(toml, Path::new("")).unwrap();
648 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
652 fn test_new_overridden() {
654 unstable_features = true
657 let mut config = Config::from_toml(toml, Path::new("")).unwrap();
658 config.override_value("imports_granularity", "Preserve");
659 assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
663 fn test_old_overridden() {
665 unstable_features = true
666 imports_granularity = "Module"
668 let mut config = Config::from_toml(toml, Path::new("")).unwrap();
669 config.override_value("merge_imports", "true");
670 // no effect: the new option always takes precedence
671 assert_eq!(config.imports_granularity(), ImportGranularity::Module);