]> git.lizzy.rs Git - rust.git/blob - src/config.rs
Remove `chain_split_single_child` option
[rust.git] / src / config.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 extern crate toml;
12
13 use std::{env, fs};
14 use std::cell::Cell;
15 use std::fs::File;
16 use std::io::{Error, ErrorKind, Read};
17 use std::path::{Path, PathBuf};
18
19 use file_lines::FileLines;
20 use lists::{ListTactic, SeparatorPlace, SeparatorTactic};
21 use Summary;
22
23
24 macro_rules! is_nightly_channel {
25     () => {
26     env::var("CFG_RELEASE_CHANNEL")
27         .map(|c| c == "nightly")
28         .unwrap_or(false)
29     }
30 }
31
32 macro_rules! configuration_option_enum{
33     ($e:ident: $( $x:ident ),+ $(,)*) => {
34         #[derive(Copy, Clone, Eq, PartialEq, Debug)]
35         pub enum $e {
36             $( $x ),+
37         }
38
39         impl_enum_serialize_and_deserialize!($e, $( $x ),+);
40     }
41 }
42
43 configuration_option_enum! { NewlineStyle:
44     Windows, // \r\n
45     Unix, // \n
46     Native, // \r\n in Windows, \n on other platforms
47 }
48
49 configuration_option_enum! { BraceStyle:
50     AlwaysNextLine,
51     PreferSameLine,
52     // Prefer same line except where there is a where clause, in which case force
53     // the brace to the next line.
54     SameLineWhere,
55 }
56
57 configuration_option_enum! { ControlBraceStyle:
58     // K&R style, Rust community default
59     AlwaysSameLine,
60     // Stroustrup style
61     ClosingNextLine,
62     // Allman style
63     AlwaysNextLine,
64 }
65
66 configuration_option_enum! { IndentStyle:
67     // First line on the same line as the opening brace, all lines aligned with
68     // the first line.
69     Visual,
70     // First line is on a new line and all lines align with block indent.
71     Block,
72 }
73
74 configuration_option_enum! { Density:
75     // Fit as much on one line as possible.
76     Compressed,
77     // Use more lines.
78     Tall,
79     // Try to compress if the body is empty.
80     CompressedIfEmpty,
81     // Place every item on a separate line.
82     Vertical,
83 }
84
85 configuration_option_enum! { TypeDensity:
86     // No spaces around "=" and "+"
87     Compressed,
88     // Spaces around " = " and " + "
89     Wide,
90 }
91
92
93 impl Density {
94     pub fn to_list_tactic(self) -> ListTactic {
95         match self {
96             Density::Compressed => ListTactic::Mixed,
97             Density::Tall | Density::CompressedIfEmpty => ListTactic::HorizontalVertical,
98             Density::Vertical => ListTactic::Vertical,
99         }
100     }
101 }
102
103 configuration_option_enum! { MultilineStyle:
104     // Use horizontal layout if it fits in one line, fall back to vertical
105     PreferSingle,
106     // Use vertical layout
107     ForceMulti,
108 }
109
110 impl MultilineStyle {
111     pub fn to_list_tactic(self) -> ListTactic {
112         match self {
113             MultilineStyle::PreferSingle => ListTactic::HorizontalVertical,
114             MultilineStyle::ForceMulti => ListTactic::Vertical,
115         }
116     }
117 }
118
119 configuration_option_enum! { ReportTactic:
120     Always,
121     Unnumbered,
122     Never,
123 }
124
125 configuration_option_enum! { WriteMode:
126     // Backs the original file up and overwrites the original.
127     Replace,
128     // Overwrites original file without backup.
129     Overwrite,
130     // Writes the output to stdout.
131     Display,
132     // Writes the diff to stdout.
133     Diff,
134     // Displays how much of the input file was processed
135     Coverage,
136     // Unfancy stdout
137     Plain,
138     // Outputs a checkstyle XML file.
139     Checkstyle,
140 }
141
142 configuration_option_enum! { Color:
143     // Always use color, whether it is a piped or terminal output
144     Always,
145     // Never use color
146     Never,
147     // Automatically use color, if supported by terminal
148     Auto,
149 }
150
151 /// Trait for types that can be used in `Config`.
152 pub trait ConfigType: Sized {
153     /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
154     /// pipe-separated list of variants; for other types it returns "<type>".
155     fn doc_hint() -> String;
156 }
157
158 impl ConfigType for bool {
159     fn doc_hint() -> String {
160         String::from("<boolean>")
161     }
162 }
163
164 impl ConfigType for usize {
165     fn doc_hint() -> String {
166         String::from("<unsigned integer>")
167     }
168 }
169
170 impl ConfigType for isize {
171     fn doc_hint() -> String {
172         String::from("<signed integer>")
173     }
174 }
175
176 impl ConfigType for String {
177     fn doc_hint() -> String {
178         String::from("<string>")
179     }
180 }
181
182 impl ConfigType for FileLines {
183     fn doc_hint() -> String {
184         String::from("<json>")
185     }
186 }
187
188 pub struct ConfigHelpItem {
189     option_name: &'static str,
190     doc_string: &'static str,
191     variant_names: String,
192     default: &'static str,
193 }
194
195 impl ConfigHelpItem {
196     pub fn option_name(&self) -> &'static str {
197         self.option_name
198     }
199
200     pub fn doc_string(&self) -> &'static str {
201         self.doc_string
202     }
203
204     pub fn variant_names(&self) -> &String {
205         &self.variant_names
206     }
207
208     pub fn default(&self) -> &'static str {
209         self.default
210     }
211 }
212
213 macro_rules! create_config {
214     ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => (
215         #[derive(Clone)]
216         pub struct Config {
217             // For each config item, we store a bool indicating whether it has
218             // been accessed and the value, and a bool whether the option was
219             // manually initialised, or taken from the default,
220             $($i: (Cell<bool>, bool, $ty, bool)),+
221         }
222
223         // Just like the Config struct but with each property wrapped
224         // as Option<T>. This is used to parse a rustfmt.toml that doesn't
225         // specify all properties of `Config`.
226         // We first parse into `PartialConfig`, then create a default `Config`
227         // and overwrite the properties with corresponding values from `PartialConfig`.
228         #[derive(Deserialize, Serialize, Clone)]
229         pub struct PartialConfig {
230             $(pub $i: Option<$ty>),+
231         }
232
233         impl PartialConfig {
234             pub fn to_toml(&self) -> Result<String, String> {
235                 // file_lines can't be specified in TOML
236                 let mut cloned = self.clone();
237                 cloned.file_lines = None;
238
239                 toml::to_string(&cloned)
240                     .map_err(|e| format!("Could not output config: {}", e.to_string()))
241             }
242         }
243
244         // Macro hygiene won't allow us to make `set_$i()` methods on Config
245         // for each item, so this struct is used to give the API to set values:
246         // `config.get().option(false)`. It's pretty ugly. Consider replacing
247         // with `config.set_option(false)` if we ever get a stable/usable
248         // `concat_idents!()`.
249         pub struct ConfigSetter<'a>(&'a mut Config);
250
251         impl<'a> ConfigSetter<'a> {
252             $(
253             pub fn $i(&mut self, value: $ty) {
254                 (self.0).$i.2 = value;
255             }
256             )+
257         }
258
259         // Query each option, returns true if the user set the option, false if
260         // a default was used.
261         pub struct ConfigWasSet<'a>(&'a Config);
262
263         impl<'a> ConfigWasSet<'a> {
264             $(
265             pub fn $i(&self) -> bool {
266                 (self.0).$i.1
267             }
268             )+
269         }
270
271         impl Config {
272             pub fn version_meets_requirement(&self, error_summary: &mut Summary) -> bool {
273                 if self.was_set().required_version() {
274                     let version = env!("CARGO_PKG_VERSION");
275                     let required_version = self.required_version();
276                     if version != required_version {
277                         println!(
278                             "Error: rustfmt version ({}) doesn't match the required version ({})",
279                             version,
280                             required_version,
281                         );
282                         error_summary.add_formatting_error();
283                         return false;
284                     }
285                 }
286
287                 true
288             }
289
290             $(
291             pub fn $i(&self) -> $ty {
292                 self.$i.0.set(true);
293                 self.$i.2.clone()
294             }
295             )+
296
297             pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
298                 ConfigSetter(self)
299             }
300
301             pub fn was_set<'a>(&'a self) -> ConfigWasSet<'a> {
302                 ConfigWasSet(self)
303             }
304
305             fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
306             $(
307                 if let Some(val) = parsed.$i {
308                     if !self.$i.3 {
309                         self.$i.1 = true;
310                         self.$i.2 = val;
311                     } else {
312                         if is_nightly_channel!() {
313                             self.$i.1 = true;
314                             self.$i.2 = val;
315                         } else {
316                             println!("Warning: can't set some features as unstable \
317                                     features are only available in nightly channel.");
318                         }
319                     }
320                 }
321             )+
322                 self
323             }
324
325             pub fn from_toml(toml: &str) -> Result<Config, String> {
326                 let parsed: toml::Value =
327                     toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
328                 let mut err: String = String::new();
329                 {
330                     let table = parsed
331                         .as_table()
332                         .ok_or(String::from("Parsed config was not table"))?;
333                     for key in table.keys() {
334                         match &**key {
335                             $(
336                                 stringify!($i) => (),
337                             )+
338                                 _ => {
339                                     let msg =
340                                         &format!("Warning: Unknown configuration option `{}`\n",
341                                                  key);
342                                     err.push_str(msg)
343                                 }
344                         }
345                     }
346                 }
347                 match parsed.try_into() {
348                     Ok(parsed_config) =>
349                         Ok(Config::default().fill_from_parsed_config(parsed_config)),
350                     Err(e) => {
351                         err.push_str("Error: Decoding config file failed:\n");
352                         err.push_str(format!("{}\n", e).as_str());
353                         err.push_str("Please check your config file.\n");
354                         Err(err)
355                     }
356                 }
357             }
358
359             pub fn used_options(&self) -> PartialConfig {
360                 PartialConfig {
361                     $(
362                         $i: if self.$i.0.get() {
363                                 Some(self.$i.2.clone())
364                             } else {
365                                 None
366                             },
367                     )+
368                 }
369             }
370
371             pub fn all_options(&self) -> PartialConfig {
372                 PartialConfig {
373                     $(
374                         $i: Some(self.$i.2.clone()),
375                     )+
376                 }
377             }
378
379             pub fn override_value(&mut self, key: &str, val: &str)
380             {
381                 match key {
382                     $(
383                         stringify!($i) => {
384                             self.$i.2 = val.parse::<$ty>()
385                                 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
386                                                  stringify!($i),
387                                                  val,
388                                                  stringify!($ty)));
389                         }
390                     )+
391                     _ => panic!("Unknown config key in override: {}", key)
392                 }
393             }
394
395             /// Construct a `Config` from the toml file specified at `file_path`.
396             ///
397             /// This method only looks at the provided path, for a method that
398             /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
399             ///
400             /// Return a `Config` if the config could be read and parsed from
401             /// the file, Error otherwise.
402             pub fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
403                 let mut file = File::open(&file_path)?;
404                 let mut toml = String::new();
405                 file.read_to_string(&mut toml)?;
406                 Config::from_toml(&toml).map_err(|err| Error::new(ErrorKind::InvalidData, err))
407             }
408
409             /// Resolve the config for input in `dir`.
410             ///
411             /// Searches for `rustfmt.toml` beginning with `dir`, and
412             /// recursively checking parents of `dir` if no config file is found.
413             /// If no config file exists in `dir` or in any parent, a
414             /// default `Config` will be returned (and the returned path will be empty).
415             ///
416             /// Returns the `Config` to use, and the path of the project file if there was
417             /// one.
418             pub fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
419
420                 /// Try to find a project file in the given directory and its parents.
421                 /// Returns the path of a the nearest project file if one exists,
422                 /// or `None` if no project file was found.
423                 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
424                     let mut current = if dir.is_relative() {
425                         env::current_dir()?.join(dir)
426                     } else {
427                         dir.to_path_buf()
428                     };
429
430                     current = fs::canonicalize(current)?;
431
432                     loop {
433                         match get_toml_path(&current) {
434                             Ok(Some(path)) => return Ok(Some(path)),
435                             Err(e) => return Err(e),
436                             _ => ()
437                         }
438
439                         // If the current directory has no parent, we're done searching.
440                         if !current.pop() {
441                             return Ok(None);
442                         }
443                     }
444                 }
445
446                 match resolve_project_file(dir)? {
447                     None => Ok((Config::default(), None)),
448                     Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
449                 }
450             }
451
452
453             pub fn print_docs() {
454                 use std::cmp;
455                 let max = 0;
456                 $( let max = cmp::max(max, stringify!($i).len()+1); )+
457                 let mut space_str = String::with_capacity(max);
458                 for _ in 0..max {
459                     space_str.push(' ');
460                 }
461                 println!("Configuration Options:");
462                 $(
463                     let name_raw = stringify!($i);
464                     let mut name_out = String::with_capacity(max);
465                     for _ in name_raw.len()..max-1 {
466                         name_out.push(' ')
467                     }
468                     name_out.push_str(name_raw);
469                     name_out.push(' ');
470                     println!("{}{} Default: {:?}",
471                              name_out,
472                              <$ty>::doc_hint(),
473                              $def);
474                     $(
475                         println!("{}{}", space_str, $dstring);
476                     )+
477                     println!();
478                 )+
479             }
480         }
481
482         // Template for the default configuration
483         impl Default for Config {
484             fn default() -> Config {
485                 Config {
486                     $(
487                         $i: (Cell::new(false), false, $def, $stb),
488                     )+
489                 }
490             }
491         }
492     )
493 }
494
495 /// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
496 ///
497 /// Return the path if a config file exists, empty if no file exists, and Error for IO errors
498 pub fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
499     const CONFIG_FILE_NAMES: [&str; 2] = [".rustfmt.toml", "rustfmt.toml"];
500     for config_file_name in &CONFIG_FILE_NAMES {
501         let config_file = dir.join(config_file_name);
502         match fs::metadata(&config_file) {
503             // Only return if it's a file to handle the unlikely situation of a directory named
504             // `rustfmt.toml`.
505             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
506             // Return the error if it's something other than `NotFound`; otherwise we didn't
507             // find the project file yet, and continue searching.
508             Err(e) => if e.kind() != ErrorKind::NotFound {
509                 return Err(e);
510             },
511             _ => {}
512         }
513     }
514     Ok(None)
515 }
516
517
518
519 create_config! {
520     indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items.";
521     unstable_features: bool, false, true,
522             "Enables unstable features. Only available on nightly channel";
523     verbose: bool, false, false, "Use verbose output";
524     disable_all_formatting: bool, false, false, "Don't reformat anything";
525     skip_children: bool, false, false, "Don't reformat out of line modules";
526     file_lines: FileLines, FileLines::all(), false,
527         "Lines to format; this is not supported in rustfmt.toml, and can only be specified \
528          via the --file-lines option";
529     max_width: usize, 100, false, "Maximum width of each line";
530     error_on_line_overflow: bool, true, false, "Error if unable to get all lines within max_width";
531     error_on_line_overflow_comments: bool, true, false,
532         "Error if unable to get comments within max_width";
533     tab_spaces: usize, 4, false, "Number of spaces per tab";
534     fn_call_width: usize, 60, false,
535         "Maximum width of the args of a function call before falling back to vertical formatting";
536     struct_lit_width: usize, 18, false,
537         "Maximum width in the body of a struct lit before falling back to vertical formatting";
538     struct_variant_width: usize, 35, false,
539         "Maximum width in the body of a struct variant before falling back to vertical formatting";
540     force_explicit_abi: bool, true, false, "Always print the abi for extern items";
541     newline_style: NewlineStyle, NewlineStyle::Unix, false, "Unix or Windows line endings";
542     brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items";
543     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false,
544         "Brace style for control flow constructs";
545     impl_empty_single_line: bool, true, false, "Put empty-body implementations on a single line";
546     trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false,
547         "How to handle trailing commas for lists";
548     trailing_semicolon: bool, true, false,
549         "Add trailing semicolon after break, continue and return";
550     fn_empty_single_line: bool, true, false, "Put empty-body functions on a single line";
551     fn_single_line: bool, false, false, "Put single-expression functions on a single line";
552     fn_args_density: Density, Density::Tall, false, "Argument density in functions";
553     array_width: usize, 60, false,
554         "Maximum width of an array literal before falling back to vertical formatting";
555     array_horizontal_layout_threshold: usize, 0, false,
556         "How many elements array must have before rustfmt uses horizontal layout.";
557     type_punctuation_density: TypeDensity, TypeDensity::Wide, false,
558         "Determines if '+' or '=' are wrapped in spaces in the punctuation of types";
559     // TODO:
560     // 1. Should we at least try to put the where clause on the same line as the rest of the
561     // function decl?
562     // 2. Currently options `Tall` and `Vertical` produce the same output.
563     where_density: Density, Density::Vertical, false, "Density of a where clause";
564     where_single_line: bool, false, false, "To force single line where layout";
565     where_layout: ListTactic, ListTactic::Vertical, false, "Element layout inside a where clause";
566     struct_lit_multiline_style: MultilineStyle, MultilineStyle::PreferSingle, false,
567         "Multiline style on literal structs";
568     report_todo: ReportTactic, ReportTactic::Never, false,
569         "Report all, none or unnumbered occurrences of TODO in source file comments";
570     report_fixme: ReportTactic, ReportTactic::Never, false,
571         "Report all, none or unnumbered occurrences of FIXME in source file comments";
572     chain_width: usize, 60, false, "Maximum length of a chain to fit on a single line";
573     imports_indent: IndentStyle, IndentStyle::Visual, false, "Indent of imports";
574     imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block";
575     reorder_extern_crates: bool, true, false, "Reorder extern crate statements alphabetically";
576     reorder_extern_crates_in_group: bool, true, false, "Reorder extern crate statements in group";
577     reorder_imports: bool, false, false, "Reorder import statements alphabetically";
578     reorder_imports_in_group: bool, false, false, "Reorder import statements in group";
579     reorder_imported_names: bool, true, false,
580         "Reorder lists of names in import statements alphabetically";
581     single_line_if_else_max_width: usize, 50, false, "Maximum line length for single line if-else \
582                                                 expressions. A value of zero means always break \
583                                                 if-else expressions.";
584     format_strings: bool, false, false, "Format string literals where necessary";
585     hard_tabs: bool, false, false, "Use tab characters for indentation, spaces for alignment";
586     wrap_comments: bool, false, false, "Break comments to fit on the line";
587     comment_width: usize, 80, false,
588         "Maximum length of comments. No effect unless wrap_comments = true";
589     normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible";
590     wrap_match_arms: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \
591                                   the same line with the pattern of arms";
592     match_block_trailing_comma: bool, false, false,
593         "Put a trailing comma after a block based match arm (non-block arms are not affected)";
594     match_arm_forces_newline: bool, false, false,
595         "Force match arm bodies to be in a new lines";
596     indent_match_arms: bool, true, false, "Indent match arms instead of keeping them at the same \
597                                     indentation level as the match keyword";
598     space_before_colon: bool, false, false, "Leave a space before the colon";
599     space_after_colon: bool, true, false, "Leave a space after the colon";
600     spaces_around_ranges: bool, false, false, "Put spaces around the  .. and ... range operators";
601     spaces_within_parens_and_brackets: bool, false, false,
602         "Put spaces within non-empty parentheses or brackets";
603     use_try_shorthand: bool, false, false, "Replace uses of the try! macro by the ? shorthand";
604     write_mode: WriteMode, WriteMode::Overwrite, false,
605         "What Write Mode to use when none is supplied: \
606          Replace, Overwrite, Display, Plain, Diff, Coverage";
607     color: Color, Color::Auto, false,
608         "What Color option to use when none is supplied: Always, Never, Auto";
609     condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \
610                                               in tuple patterns";
611     combine_control_expr: bool, true, false, "Combine control expressions with function calls.";
612     struct_field_align_threshold: usize, 0, false, "Align struct fields if their diffs fits within \
613                                              threshold.";
614     remove_blank_lines_at_start_or_end_of_block: bool, true, false,
615         "Remove blank lines at start or end of a block";
616     attributes_on_same_line_as_field: bool, true, false,
617         "Try to put attributes on the same line as fields.";
618     attributes_on_same_line_as_variant: bool, true, false,
619         "Try to put attributes on the same line as variants in enum declarations.";
620     multiline_closure_forces_block: bool, false, false,
621         "Force multiline closure bodies to be wrapped in a block";
622     multiline_match_arm_forces_block: bool, false, false,
623         "Force multiline match arm bodies to be wrapped in a block";
624     merge_derives: bool, true, false, "Merge multiple `#[derive(...)]` into a single one";
625     binop_separator: SeparatorPlace, SeparatorPlace::Front, false,
626         "Where to put a binary operator when a binary expression goes multiline.";
627     required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
628         "Require a specific version of rustfmt."
629 }
630
631 #[cfg(test)]
632 mod test {
633     use super::Config;
634
635     #[test]
636     fn test_config_set() {
637         let mut config = Config::default();
638         config.set().verbose(false);
639         assert_eq!(config.verbose(), false);
640         config.set().verbose(true);
641         assert_eq!(config.verbose(), true);
642     }
643
644     #[test]
645     fn test_config_used_to_toml() {
646         let config = Config::default();
647
648         let verbose = config.verbose();
649         let skip_children = config.skip_children();
650
651         let used_options = config.used_options();
652         let toml = used_options.to_toml().unwrap();
653         assert_eq!(
654             toml,
655             format!("verbose = {}\nskip_children = {}\n", verbose, skip_children)
656         );
657     }
658
659     #[test]
660     fn test_was_set() {
661         let config = Config::from_toml("hard_tabs = true").unwrap();
662
663         assert_eq!(config.was_set().hard_tabs(), true);
664         assert_eq!(config.was_set().verbose(), false);
665     }
666
667     #[test]
668     fn test_as_not_nightly_channel() {
669         let mut config = Config::default();
670         assert_eq!(config.was_set().unstable_features(), false);
671         config.set().unstable_features(true);
672         assert_eq!(config.was_set().unstable_features(), false);
673     }
674
675     #[test]
676     fn test_as_nightly_channel() {
677         let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
678         ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
679         let mut config = Config::default();
680         config.set().unstable_features(true);
681         assert_eq!(config.was_set().unstable_features(), false);
682         config.set().unstable_features(true);
683         assert_eq!(config.unstable_features(), true);
684         ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
685     }
686
687     #[test]
688     fn test_unstable_from_toml() {
689         let mut config = Config::from_toml("unstable_features = true").unwrap();
690         assert_eq!(config.was_set().unstable_features(), false);
691         let v = ::std::env::var("CFG_RELEASE_CHANNEL").unwrap_or(String::from(""));
692         ::std::env::set_var("CFG_RELEASE_CHANNEL", "nightly");
693         config = Config::from_toml("unstable_features = true").unwrap();
694         assert_eq!(config.was_set().unstable_features(), true);
695         assert_eq!(config.unstable_features(), true);
696         ::std::env::set_var("CFG_RELEASE_CHANNEL", v);
697     }
698
699 }