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