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 force_multiline_blocks: bool, false, false,
95 "Force multiline closure bodies and match arms to be wrapped in a block";
96 fn_args_layout: Density, Density::Tall, true,
97 "Control the layout of arguments in a function";
98 brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
99 control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
100 "Brace style for control flow constructs";
101 trailing_semicolon: bool, true, false,
102 "Add trailing semicolon after break, continue and return";
103 trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
104 "How to handle trailing commas for lists";
105 match_block_trailing_comma: bool, false, false,
106 "Put a trailing comma after a block based match arm (non-block arms are not affected)";
107 blank_lines_upper_bound: usize, 1, false,
108 "Maximum number of blank lines which can be put between items";
109 blank_lines_lower_bound: usize, 0, false,
110 "Minimum number of blank lines which must be put between items";
111 edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)";
112 version: Version, Version::One, false, "Version of formatting rules";
113 inline_attribute_width: usize, 0, false,
114 "Write an item and its attribute on the same line \
115 if their combined width is below a threshold";
117 // Options that can change the source code beyond whitespace/blocks (somewhat linty things)
118 merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one";
119 use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand";
120 use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible";
121 force_explicit_abi: bool, true, true, "Always print the abi for extern items";
122 condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
125 // Control options (changes the operation of rustfmt, rather than the formatting)
126 color: Color, Color::Auto, false,
127 "What Color option to use when none is supplied: Always, Never, Auto";
128 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
129 "Require a specific version of rustfmt";
130 unstable_features: bool, false, false,
131 "Enables unstable features. Only available on nightly channel";
132 disable_all_formatting: bool, false, false, "Don't reformat anything";
133 skip_children: bool, false, false, "Don't reformat out of line modules";
134 hide_parse_errors: bool, false, false, "Hide errors from the parser";
135 error_on_line_overflow: bool, false, false, "Error if unable to get all lines within max_width";
136 error_on_unformatted: bool, false, false,
137 "Error if unable to get comments or string literals within max_width, \
138 or they are left with trailing whitespaces";
139 report_todo: ReportTactic, ReportTactic::Never, false,
140 "Report all, none or unnumbered occurrences of TODO in source file comments";
141 report_fixme: ReportTactic, ReportTactic::Never, false,
142 "Report all, none or unnumbered occurrences of FIXME in source file comments";
143 ignore: IgnoreList, IgnoreList::default(), false,
144 "Skip formatting the specified files and directories";
147 verbose: Verbosity, Verbosity::Normal, false, "How much to information to emit to the user";
148 file_lines: FileLines, FileLines::all(), false,
149 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
150 via the --file-lines option";
151 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
152 "'small' heuristic values";
153 emit_mode: EmitMode, EmitMode::Files, false,
154 "What emit Mode to use when none is supplied";
155 make_backup: bool, false, false, "Backup changed files";
156 print_misformatted_file_names: bool, false, true,
157 "Prints the names of mismatched files that were formatted. Prints the names of \
158 files that would be formated when used with `--check` mode. ";
161 #[derive(Error, Debug)]
162 #[error("Could not output config: {0}")]
163 pub struct ToTomlError(toml::ser::Error);
166 pub fn to_toml(&self) -> Result<String, ToTomlError> {
167 // Non-user-facing options can't be specified in TOML
168 let mut cloned = self.clone();
169 cloned.file_lines = None;
170 cloned.verbose = None;
171 cloned.width_heuristics = None;
172 cloned.print_misformatted_file_names = None;
174 ::toml::to_string(&cloned).map_err(ToTomlError)
179 pub(crate) fn version_meets_requirement(&self) -> bool {
180 if self.was_set().required_version() {
181 let version = env!("CARGO_PKG_VERSION");
182 let required_version = self.required_version();
183 if version != required_version {
185 "Error: rustfmt version ({}) doesn't match the required version ({})",
186 version, required_version,
195 /// Constructs a `Config` from the toml file specified at `file_path`.
197 /// This method only looks at the provided path, for a method that
198 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
200 /// Returns a `Config` if the config could be read and parsed from
201 /// the file, otherwise errors.
202 pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
203 let mut file = File::open(&file_path)?;
204 let mut toml = String::new();
205 file.read_to_string(&mut toml)?;
206 Config::from_toml(&toml, file_path.parent().unwrap())
207 .map_err(|err| Error::new(ErrorKind::InvalidData, err))
210 /// Resolves the config for input in `dir`.
212 /// Searches for `rustfmt.toml` beginning with `dir`, and
213 /// recursively checking parents of `dir` if no config file is found.
214 /// If no config file exists in `dir` or in any parent, a
215 /// default `Config` will be returned (and the returned path will be empty).
217 /// Returns the `Config` to use, and the path of the project file if there was
219 pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
220 /// Try to find a project file in the given directory and its parents.
221 /// Returns the path of a the nearest project file if one exists,
222 /// or `None` if no project file was found.
223 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
224 let mut current = if dir.is_relative() {
225 env::current_dir()?.join(dir)
230 current = fs::canonicalize(current)?;
233 match get_toml_path(¤t) {
234 Ok(Some(path)) => return Ok(Some(path)),
235 Err(e) => return Err(e),
239 // If the current directory has no parent, we're done searching.
245 // If nothing was found, check in the home directory.
246 if let Some(home_dir) = dirs::home_dir() {
247 if let Some(path) = get_toml_path(&home_dir)? {
248 return Ok(Some(path));
252 // If none was found ther either, check in the user's configuration directory.
253 if let Some(mut config_dir) = dirs::config_dir() {
254 config_dir.push("rustfmt");
255 if let Some(path) = get_toml_path(&config_dir)? {
256 return Ok(Some(path));
263 match resolve_project_file(dir)? {
264 None => Ok((Config::default(), None)),
265 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
269 pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
270 let parsed: ::toml::Value = toml
272 .map_err(|e| format!("Could not parse TOML: {}", e))?;
273 let mut err = String::new();
276 .ok_or_else(|| String::from("Parsed config was not table"))?;
277 for key in table.keys() {
278 if !Config::is_valid_name(key) {
279 let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
283 match parsed.try_into() {
284 Ok(parsed_config) => {
288 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
291 err.push_str("Error: Decoding config file failed:\n");
292 err.push_str(format!("{}\n", e).as_str());
293 err.push_str("Please check your config file.");
300 /// Loads a config by checking the client-supplied options and if appropriate, the
301 /// file system (including searching the file system for overrides).
302 pub fn load_config<O: CliOptions>(
303 file_path: Option<&Path>,
305 ) -> Result<(Config, Option<PathBuf>), Error> {
306 let over_ride = match options {
307 Some(ref opts) => config_path(opts)?,
311 let result = if let Some(over_ride) = over_ride {
312 Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
313 } else if let Some(file_path) = file_path {
314 Config::from_resolved_toml_path(file_path)
316 Ok((Config::default(), None))
319 result.map(|(mut c, p)| {
320 if let Some(options) = options {
321 options.apply_to(&mut c);
327 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
329 // Return the path if a config file exists, empty if no file exists, and Error for IO errors
330 fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
331 const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
332 for config_file_name in &CONFIG_FILE_NAMES {
333 let config_file = dir.join(config_file_name);
334 match fs::metadata(&config_file) {
335 // Only return if it's a file to handle the unlikely situation of a directory named
337 Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
338 // Return the error if it's something other than `NotFound`; otherwise we didn't
339 // find the project file yet, and continue searching.
341 if e.kind() != ErrorKind::NotFound {
351 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
352 let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
356 "Error: unable to find a config file for the given path: `{}`",
362 // Read the config_path and convert to parent dir if a file is provided.
363 // If a config file cannot be found from the given path, return error.
364 match options.config_path() {
365 Some(path) if !path.exists() => config_path_not_found(path.to_str().unwrap()),
366 Some(path) if path.is_dir() => {
367 let config_file_path = get_toml_path(path)?;
368 if config_file_path.is_some() {
371 config_path_not_found(path.to_str().unwrap())
374 path => Ok(path.map(ToOwned::to_owned)),
388 // Options that are used by the generated functions
389 max_width: usize, 100, true, "Maximum width of each line";
390 use_small_heuristics: Heuristics, Heuristics::Default, true,
391 "Whether to use different formatting for items and \
392 expressions if they satisfy a heuristic notion of 'small'.";
393 license_template_path: String, String::default(), false,
394 "Beginning of file must match license template";
395 required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
396 "Require a specific version of rustfmt.";
397 ignore: IgnoreList, IgnoreList::default(), false,
398 "Skip formatting the specified files and directories.";
399 verbose: Verbosity, Verbosity::Normal, false,
400 "How much to information to emit to the user";
401 file_lines: FileLines, FileLines::all(), false,
402 "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
403 via the --file-lines option";
404 width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
405 "'small' heuristic values";
407 // Options that are used by the tests
408 stable_option: bool, false, true, "A stable option";
409 unstable_option: bool, false, false, "An unstable option";
414 fn test_config_set() {
415 let mut config = Config::default();
416 config.set().verbose(Verbosity::Quiet);
417 assert_eq!(config.verbose(), Verbosity::Quiet);
418 config.set().verbose(Verbosity::Normal);
419 assert_eq!(config.verbose(), Verbosity::Normal);
423 fn test_config_used_to_toml() {
424 let config = Config::default();
426 let merge_derives = config.merge_derives();
427 let skip_children = config.skip_children();
429 let used_options = config.used_options();
430 let toml = used_options.to_toml().unwrap();
434 "merge_derives = {}\nskip_children = {}\n",
435 merge_derives, skip_children,
442 let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
444 assert_eq!(config.was_set().hard_tabs(), true);
445 assert_eq!(config.was_set().verbose(), false);
449 fn test_print_docs_exclude_unstable() {
450 use self::mock::Config;
452 let mut output = Vec::new();
453 Config::print_docs(&mut output, false);
455 let s = str::from_utf8(&output).unwrap();
457 assert_eq!(s.contains("stable_option"), true);
458 assert_eq!(s.contains("unstable_option"), false);
459 assert_eq!(s.contains("(unstable)"), false);
463 fn test_print_docs_include_unstable() {
464 use self::mock::Config;
466 let mut output = Vec::new();
467 Config::print_docs(&mut output, true);
469 let s = str::from_utf8(&output).unwrap();
470 assert_eq!(s.contains("stable_option"), true);
471 assert_eq!(s.contains("unstable_option"), true);
472 assert_eq!(s.contains("(unstable)"), true);
476 fn test_empty_string_license_template_path() {
477 let toml = r#"license_template_path = """#;
478 let config = Config::from_toml(toml, Path::new("")).unwrap();
479 assert!(config.license_template.is_none());
483 fn test_valid_license_template_path() {
484 if !crate::is_nightly_channel!() {
487 let toml = r#"license_template_path = "tests/license-template/lt.txt""#;
488 let config = Config::from_toml(toml, Path::new("")).unwrap();
489 assert!(config.license_template.is_some());
493 fn test_dump_default_config() {
494 let default_config = format!(
498 newline_style = "Auto"
499 use_small_heuristics = "Default"
500 indent_style = "Block"
501 wrap_comments = false
502 format_code_in_doc_comments = false
504 normalize_comments = false
505 normalize_doc_attributes = false
506 license_template_path = ""
507 format_strings = false
508 format_macro_matchers = false
509 format_macro_bodies = true
510 empty_item_single_line = true
511 struct_lit_single_line = true
512 fn_single_line = false
513 where_single_line = false
514 imports_indent = "Block"
515 imports_layout = "Mixed"
516 merge_imports = false
517 reorder_imports = true
518 reorder_modules = true
519 reorder_impl_items = false
520 type_punctuation_density = "Wide"
521 space_before_colon = false
522 space_after_colon = true
523 spaces_around_ranges = false
524 binop_separator = "Front"
525 remove_nested_parens = true
526 combine_control_expr = true
527 overflow_delimited_expr = false
528 struct_field_align_threshold = 0
529 enum_discrim_align_threshold = 0
530 match_arm_blocks = true
531 force_multiline_blocks = false
532 fn_args_layout = "Tall"
533 brace_style = "SameLineWhere"
534 control_brace_style = "AlwaysSameLine"
535 trailing_semicolon = true
536 trailing_comma = "Vertical"
537 match_block_trailing_comma = false
538 blank_lines_upper_bound = 1
539 blank_lines_lower_bound = 0
542 inline_attribute_width = 0
544 use_try_shorthand = false
545 use_field_init_shorthand = false
546 force_explicit_abi = true
547 condense_wildcard_suffixes = false
549 required_version = "{}"
550 unstable_features = false
551 disable_all_formatting = false
552 skip_children = false
553 hide_parse_errors = false
554 error_on_line_overflow = false
555 error_on_unformatted = false
556 report_todo = "Never"
557 report_fixme = "Never"
562 env!("CARGO_PKG_VERSION")
564 let toml = Config::default().all_options().to_toml().unwrap();
565 assert_eq!(&toml, &default_config);
568 // FIXME(#2183): these tests cannot be run in parallel because they use env vars.
570 // fn test_as_not_nightly_channel() {
571 // let mut config = Config::default();
572 // assert_eq!(config.was_set().unstable_features(), false);
573 // config.set().unstable_features(true);
574 // assert_eq!(config.was_set().unstable_features(), false);
578 // fn test_as_nightly_channel() {
579 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
580 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
581 // let mut config = Config::default();
582 // config.set().unstable_features(true);
583 // assert_eq!(config.was_set().unstable_features(), false);
584 // config.set().unstable_features(true);
585 // assert_eq!(config.unstable_features(), true);
586 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
590 // fn test_unstable_from_toml() {
591 // let mut config = Config::from_toml("unstable_features = true").unwrap();
592 // assert_eq!(config.was_set().unstable_features(), false);
593 // let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
594 // ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
595 // config = Config::from_toml("unstable_features = true").unwrap();
596 // assert_eq!(config.was_set().unstable_features(), true);
597 // assert_eq!(config.unstable_features(), true);
598 // ::std::env::set_var("CFG_RELEASE_CHANNEL", v);