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