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