]> git.lizzy.rs Git - rust.git/blob - src/config/mod.rs
Rename `merge_imports` to `imports_granularity` and add a `Module` option.
[rust.git] / src / config / mod.rs
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";
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";
41
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";
55
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";
63
64     // Imports
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)";
72
73     // Ordering
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";
77
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";
86
87     // Misc.
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";
122
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 .. \
129                                                      in tuple patterns";
130
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";
151
152     // Not user-facing
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. ";
165 }
166
167 #[derive(Error, Debug)]
168 #[error("Could not output config: {0}")]
169 pub struct ToTomlError(toml::ser::Error);
170
171 impl PartialConfig {
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;
180
181         ::toml::to_string(&cloned).map_err(ToTomlError)
182     }
183 }
184
185 impl Config {
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 {
191                 println!(
192                     "Error: rustfmt version ({}) doesn't match the required version ({})",
193                     version, required_version,
194                 );
195                 return false;
196             }
197         }
198
199         true
200     }
201
202     /// Constructs a `Config` from the toml file specified at `file_path`.
203     ///
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`.
206     ///
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))
215     }
216
217     /// Resolves the config for input in `dir`.
218     ///
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).
223     ///
224     /// Returns the `Config` to use, and the path of the project file if there was
225     /// one.
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)
233             } else {
234                 dir.to_path_buf()
235             };
236
237             current = fs::canonicalize(current)?;
238
239             loop {
240                 match get_toml_path(&current) {
241                     Ok(Some(path)) => return Ok(Some(path)),
242                     Err(e) => return Err(e),
243                     _ => (),
244                 }
245
246                 // If the current directory has no parent, we're done searching.
247                 if !current.pop() {
248                     break;
249                 }
250             }
251
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));
256                 }
257             }
258
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));
264                 }
265             }
266
267             Ok(None)
268         }
269
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))),
273         }
274     }
275
276     pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
277         let parsed: ::toml::Value = toml
278             .parse()
279             .map_err(|e| format!("Could not parse TOML: {}", e))?;
280         let mut err = String::new();
281         let table = parsed
282             .as_table()
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);
287                 err.push_str(msg)
288             }
289         }
290         match parsed.try_into() {
291             Ok(parsed_config) => {
292                 if !err.is_empty() {
293                     eprint!("{}", err);
294                 }
295                 Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
296             }
297             Err(e) => {
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.");
301                 Err(err)
302             }
303         }
304     }
305 }
306
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>,
311     options: Option<O>,
312 ) -> Result<(Config, Option<PathBuf>), Error> {
313     let over_ride = match options {
314         Some(ref opts) => config_path(opts)?,
315         None => None,
316     };
317
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)
322     } else {
323         Ok((Config::default(), None))
324     };
325
326     result.map(|(mut c, p)| {
327         if let Some(options) = options {
328             options.apply_to(&mut c);
329         }
330         (c, p)
331     })
332 }
333
334 // Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
335 //
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
343             // `rustfmt.toml`.
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.
347             Err(e) => {
348                 if e.kind() != ErrorKind::NotFound {
349                     return Err(e);
350                 }
351             }
352             _ => {}
353         }
354     }
355     Ok(None)
356 }
357
358 fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
359     let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
360         Err(Error::new(
361             ErrorKind::NotFound,
362             format!(
363                 "Error: unable to find a config file for the given path: `{}`",
364                 path
365             ),
366         ))
367     };
368
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() {
376                 Ok(config_file_path)
377             } else {
378                 config_path_not_found(path.to_str().unwrap())
379             }
380         }
381         path => Ok(path.map(ToOwned::to_owned)),
382     }
383 }
384
385 #[cfg(test)]
386 mod test {
387     use super::*;
388     use std::str;
389
390     #[allow(dead_code)]
391     mod mock {
392         use super::super::*;
393
394         create_config! {
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,
415                 "Merge imports";
416             merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)";
417
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";
421         }
422     }
423
424     #[test]
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);
431     }
432
433     #[test]
434     fn test_config_used_to_toml() {
435         let config = Config::default();
436
437         let merge_derives = config.merge_derives();
438         let skip_children = config.skip_children();
439
440         let used_options = config.used_options();
441         let toml = used_options.to_toml().unwrap();
442         assert_eq!(
443             toml,
444             format!(
445                 "merge_derives = {}\nskip_children = {}\n",
446                 merge_derives, skip_children,
447             )
448         );
449     }
450
451     #[test]
452     fn test_was_set() {
453         let config = Config::from_toml("hard_tabs = true", Path::new("")).unwrap();
454
455         assert_eq!(config.was_set().hard_tabs(), true);
456         assert_eq!(config.was_set().verbose(), false);
457     }
458
459     #[test]
460     fn test_print_docs_exclude_unstable() {
461         use self::mock::Config;
462
463         let mut output = Vec::new();
464         Config::print_docs(&mut output, false);
465
466         let s = str::from_utf8(&output).unwrap();
467
468         assert_eq!(s.contains("stable_option"), true);
469         assert_eq!(s.contains("unstable_option"), false);
470         assert_eq!(s.contains("(unstable)"), false);
471     }
472
473     #[test]
474     fn test_print_docs_include_unstable() {
475         use self::mock::Config;
476
477         let mut output = Vec::new();
478         Config::print_docs(&mut output, true);
479
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);
484     }
485
486     #[test]
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());
491     }
492
493     #[test]
494     fn test_valid_license_template_path() {
495         if !crate::is_nightly_channel!() {
496             return;
497         }
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());
501     }
502
503     #[test]
504     fn test_override_existing_license_with_no_license() {
505         if !crate::is_nightly_channel!() {
506             return;
507         }
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());
513     }
514
515     #[test]
516     fn test_dump_default_config() {
517         let default_config = format!(
518             r#"max_width = 100
519 hard_tabs = false
520 tab_spaces = 4
521 newline_style = "Auto"
522 use_small_heuristics = "Default"
523 indent_style = "Block"
524 wrap_comments = false
525 format_code_in_doc_comments = false
526 comment_width = 80
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
565 edition = "2015"
566 version = "One"
567 inline_attribute_width = 0
568 merge_derives = true
569 use_try_shorthand = false
570 use_field_init_shorthand = false
571 force_explicit_abi = true
572 condense_wildcard_suffixes = false
573 color = "Auto"
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"
583 ignore = []
584 emit_mode = "Files"
585 make_backup = false
586 "#,
587             env!("CARGO_PKG_VERSION")
588         );
589         let toml = Config::default().all_options().to_toml().unwrap();
590         assert_eq!(&toml, &default_config);
591     }
592
593     // FIXME(#2183): these tests cannot be run in parallel because they use env vars.
594     // #[test]
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);
600     // }
601
602     // #[test]
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);
612     // }
613
614     // #[test]
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);
624     // }
625
626     #[cfg(test)]
627     mod deprecated_option_merge_imports {
628         use super::*;
629
630         #[test]
631         fn test_old_option_set() {
632             let toml = r#"
633                 unstable_features = true
634                 merge_imports = true
635             "#;
636             let config = Config::from_toml(toml, Path::new("")).unwrap();
637             assert_eq!(config.imports_granularity(), ImportGranularity::Crate);
638         }
639
640         #[test]
641         fn test_both_set() {
642             let toml = r#"
643                 unstable_features = true
644                 merge_imports = true
645                 imports_granularity = "Preserve"
646             "#;
647             let config = Config::from_toml(toml, Path::new("")).unwrap();
648             assert_eq!(config.imports_granularity(), ImportGranularity::Preserve);
649         }
650
651         #[test]
652         fn test_new_overridden() {
653             let toml = r#"
654                 unstable_features = true
655                 merge_imports = true
656             "#;
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);
660         }
661
662         #[test]
663         fn test_old_overridden() {
664             let toml = r#"
665                 unstable_features = true
666                 imports_granularity = "Module"
667             "#;
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);
672         }
673     }
674 }