]> git.lizzy.rs Git - rust.git/blob - src/config/config_type.rs
fix a few typos found via codespell.
[rust.git] / src / config / config_type.rs
1 // Copyright 2018 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 use config::file_lines::FileLines;
12 use config::options::{IgnoreList, WidthHeuristics};
13
14 /// Trait for types that can be used in `Config`.
15 pub trait ConfigType: Sized {
16     /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
17     /// pipe-separated list of variants; for other types it returns "<type>".
18     fn doc_hint() -> String;
19 }
20
21 impl ConfigType for bool {
22     fn doc_hint() -> String {
23         String::from("<boolean>")
24     }
25 }
26
27 impl ConfigType for usize {
28     fn doc_hint() -> String {
29         String::from("<unsigned integer>")
30     }
31 }
32
33 impl ConfigType for isize {
34     fn doc_hint() -> String {
35         String::from("<signed integer>")
36     }
37 }
38
39 impl ConfigType for String {
40     fn doc_hint() -> String {
41         String::from("<string>")
42     }
43 }
44
45 impl ConfigType for FileLines {
46     fn doc_hint() -> String {
47         String::from("<json>")
48     }
49 }
50
51 impl ConfigType for WidthHeuristics {
52     fn doc_hint() -> String {
53         String::new()
54     }
55 }
56
57 impl ConfigType for IgnoreList {
58     fn doc_hint() -> String {
59         String::from("[<string>,..]")
60     }
61 }
62
63 /// Check if we're in a nightly build.
64 ///
65 /// The environment variable `CFG_RELEASE_CHANNEL` is set during the rustc bootstrap
66 /// to "stable", "beta", or "nightly" depending on what toolchain is being built.
67 /// If we are being built as part of the stable or beta toolchains, we want
68 /// to disable unstable configuration options.
69 ///
70 /// If we're being built by cargo (e.g. `cargo +nightly install rustfmt-nightly`),
71 /// `CFG_RELEASE_CHANNEL` is not set. As we only support being built against the
72 /// nightly compiler when installed from crates.io, default to nightly mode.
73 macro_rules! is_nightly_channel {
74     () => {
75         option_env!("CFG_RELEASE_CHANNEL").map_or(true, |c| c == "nightly" || c == "dev")
76     };
77 }
78
79 macro_rules! create_config {
80     ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => (
81         #[cfg(test)]
82         use std::collections::HashSet;
83         use std::io::Write;
84
85         #[derive(Clone)]
86         pub struct Config {
87             // if a license_template_path has been specified, successfully read, parsed and compiled
88             // into a regex, it will be stored here
89             pub license_template: Option<Regex>,
90             // For each config item, we store a bool indicating whether it has
91             // been accessed and the value, and a bool whether the option was
92             // manually initialised, or taken from the default,
93             $($i: (Cell<bool>, bool, $ty, bool)),+
94         }
95
96         // Just like the Config struct but with each property wrapped
97         // as Option<T>. This is used to parse a rustfmt.toml that doesn't
98         // specify all properties of `Config`.
99         // We first parse into `PartialConfig`, then create a default `Config`
100         // and overwrite the properties with corresponding values from `PartialConfig`.
101         #[derive(Deserialize, Serialize, Clone)]
102         pub struct PartialConfig {
103             $(pub $i: Option<$ty>),+
104         }
105
106         impl PartialConfig {
107             pub fn to_toml(&self) -> Result<String, String> {
108                 // Non-user-facing options can't be specified in TOML
109                 let mut cloned = self.clone();
110                 cloned.file_lines = None;
111                 cloned.verbose = None;
112                 cloned.width_heuristics = None;
113
114                 ::toml::to_string(&cloned)
115                     .map_err(|e| format!("Could not output config: {}", e))
116             }
117         }
118
119         // Macro hygiene won't allow us to make `set_$i()` methods on Config
120         // for each item, so this struct is used to give the API to set values:
121         // `config.set().option(false)`. It's pretty ugly. Consider replacing
122         // with `config.set_option(false)` if we ever get a stable/usable
123         // `concat_idents!()`.
124         pub struct ConfigSetter<'a>(&'a mut Config);
125
126         impl<'a> ConfigSetter<'a> {
127             $(
128             pub fn $i(&mut self, value: $ty) {
129                 (self.0).$i.2 = value;
130                 match stringify!($i) {
131                     "max_width" | "use_small_heuristics" => self.0.set_heuristics(),
132                     "license_template_path" => self.0.set_license_template(),
133                     &_ => (),
134                 }
135             }
136             )+
137         }
138
139         // Query each option, returns true if the user set the option, false if
140         // a default was used.
141         pub struct ConfigWasSet<'a>(&'a Config);
142
143         impl<'a> ConfigWasSet<'a> {
144             $(
145             pub fn $i(&self) -> bool {
146                 (self.0).$i.1
147             }
148             )+
149         }
150
151         impl Config {
152             pub(crate) fn version_meets_requirement(&self) -> bool {
153                 if self.was_set().required_version() {
154                     let version = env!("CARGO_PKG_VERSION");
155                     let required_version = self.required_version();
156                     if version != required_version {
157                         println!(
158                             "Error: rustfmt version ({}) doesn't match the required version ({})",
159                             version,
160                             required_version,
161                         );
162                         return false;
163                     }
164                 }
165
166                 true
167             }
168
169             $(
170             pub fn $i(&self) -> $ty {
171                 self.$i.0.set(true);
172                 self.$i.2.clone()
173             }
174             )+
175
176             pub fn set(&mut self) -> ConfigSetter {
177                 ConfigSetter(self)
178             }
179
180             pub fn was_set(&self) -> ConfigWasSet {
181                 ConfigWasSet(self)
182             }
183
184             fn fill_from_parsed_config(mut self, parsed: PartialConfig, dir: &Path) -> Config {
185             $(
186                 if let Some(val) = parsed.$i {
187                     if self.$i.3 {
188                         self.$i.1 = true;
189                         self.$i.2 = val;
190                     } else {
191                         if is_nightly_channel!() {
192                             self.$i.1 = true;
193                             self.$i.2 = val;
194                         } else {
195                             eprintln!("Warning: can't set `{} = {:?}`, unstable features are only \
196                                        available in nightly channel.", stringify!($i), val);
197                         }
198                     }
199                 }
200             )+
201                 self.set_heuristics();
202                 self.set_license_template();
203                 self.set_ignore(dir);
204                 self
205             }
206
207             /// Returns a hash set initialized with every user-facing config option name.
208             #[cfg(test)]
209             pub(crate) fn hash_set() -> HashSet<String> {
210                 let mut hash_set = HashSet::new();
211                 $(
212                     hash_set.insert(stringify!($i).to_owned());
213                 )+
214                 hash_set
215             }
216
217             pub(crate) fn is_valid_name(name: &str) -> bool {
218                 match name {
219                     $(
220                         stringify!($i) => true,
221                     )+
222                         _ => false,
223                 }
224             }
225
226             pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
227                 let parsed: ::toml::Value =
228                     toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
229                 let mut err: String = String::new();
230                 {
231                     let table = parsed
232                         .as_table()
233                         .ok_or(String::from("Parsed config was not table"))?;
234                     for key in table.keys() {
235                         if !Config::is_valid_name(key) {
236                             let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
237                             err.push_str(msg)
238                         }
239                     }
240                 }
241                 match parsed.try_into() {
242                     Ok(parsed_config) => {
243                         if !err.is_empty() {
244                             eprint!("{}", err);
245                         }
246                         Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
247                     }
248                     Err(e) => {
249                         err.push_str("Error: Decoding config file failed:\n");
250                         err.push_str(format!("{}\n", e).as_str());
251                         err.push_str("Please check your config file.");
252                         Err(err)
253                     }
254                 }
255             }
256
257             pub fn used_options(&self) -> PartialConfig {
258                 PartialConfig {
259                     $(
260                         $i: if self.$i.0.get() {
261                                 Some(self.$i.2.clone())
262                             } else {
263                                 None
264                             },
265                     )+
266                 }
267             }
268
269             pub fn all_options(&self) -> PartialConfig {
270                 PartialConfig {
271                     $(
272                         $i: Some(self.$i.2.clone()),
273                     )+
274                 }
275             }
276
277             pub fn override_value(&mut self, key: &str, val: &str)
278             {
279                 match key {
280                     $(
281                         stringify!($i) => {
282                             self.$i.1 = true;
283                             self.$i.2 = val.parse::<$ty>()
284                                 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
285                                                  stringify!($i),
286                                                  val,
287                                                  stringify!($ty)));
288                         }
289                     )+
290                     _ => panic!("Unknown config key in override: {}", key)
291                 }
292
293                 match key {
294                     "max_width" | "use_small_heuristics" => self.set_heuristics(),
295                     "license_template_path" => self.set_license_template(),
296                     &_ => (),
297                 }
298             }
299
300             /// Construct a `Config` from the toml file specified at `file_path`.
301             ///
302             /// This method only looks at the provided path, for a method that
303             /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
304             ///
305             /// Return a `Config` if the config could be read and parsed from
306             /// the file, Error otherwise.
307             pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
308                 let mut file = File::open(&file_path)?;
309                 let mut toml = String::new();
310                 file.read_to_string(&mut toml)?;
311                 Config::from_toml(&toml, file_path.parent().unwrap())
312                     .map_err(|err| Error::new(ErrorKind::InvalidData, err))
313             }
314
315             /// Resolve the config for input in `dir`.
316             ///
317             /// Searches for `rustfmt.toml` beginning with `dir`, and
318             /// recursively checking parents of `dir` if no config file is found.
319             /// If no config file exists in `dir` or in any parent, a
320             /// default `Config` will be returned (and the returned path will be empty).
321             ///
322             /// Returns the `Config` to use, and the path of the project file if there was
323             /// one.
324             pub(super) fn from_resolved_toml_path(
325                 dir: &Path,
326             ) -> Result<(Config, Option<PathBuf>), Error> {
327                 /// Try to find a project file in the given directory and its parents.
328                 /// Returns the path of a the nearest project file if one exists,
329                 /// or `None` if no project file was found.
330                 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
331                     let mut current = if dir.is_relative() {
332                         env::current_dir()?.join(dir)
333                     } else {
334                         dir.to_path_buf()
335                     };
336
337                     current = fs::canonicalize(current)?;
338
339                     loop {
340                         match get_toml_path(&current) {
341                             Ok(Some(path)) => return Ok(Some(path)),
342                             Err(e) => return Err(e),
343                             _ => ()
344                         }
345
346                         // If the current directory has no parent, we're done searching.
347                         if !current.pop() {
348                             return Ok(None);
349                         }
350                     }
351                 }
352
353                 match resolve_project_file(dir)? {
354                     None => Ok((Config::default(), None)),
355                     Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
356                 }
357             }
358
359             pub fn is_hidden_option(name: &str) -> bool {
360                 const HIDE_OPTIONS: [&str; 4] =
361                     ["verbose", "verbose_diff", "file_lines", "width_heuristics"];
362                 HIDE_OPTIONS.contains(&name)
363             }
364
365             pub fn print_docs(out: &mut Write, include_unstable: bool) {
366                 use std::cmp;
367                 let max = 0;
368                 $( let max = cmp::max(max, stringify!($i).len()+1); )+
369                 let mut space_str = String::with_capacity(max);
370                 for _ in 0..max {
371                     space_str.push(' ');
372                 }
373                 writeln!(out, "Configuration Options:").unwrap();
374                 $(
375                     if $stb || include_unstable {
376                         let name_raw = stringify!($i);
377
378                         if !Config::is_hidden_option(name_raw) {
379                             let mut name_out = String::with_capacity(max);
380                             for _ in name_raw.len()..max-1 {
381                                 name_out.push(' ')
382                             }
383                             name_out.push_str(name_raw);
384                             name_out.push(' ');
385                             writeln!(out,
386                                     "{}{} Default: {:?}{}",
387                                     name_out,
388                                     <$ty>::doc_hint(),
389                                     $def,
390                                     if !$stb { " (unstable)" } else { "" }).unwrap();
391                             $(
392                                 writeln!(out, "{}{}", space_str, $dstring).unwrap();
393                             )+
394                             writeln!(out).unwrap();
395                         }
396                     }
397                 )+
398             }
399
400             fn set_heuristics(&mut self) {
401                 if self.use_small_heuristics.2 == Heuristics::Default {
402                     let max_width = self.max_width.2;
403                     self.set().width_heuristics(WidthHeuristics::scaled(max_width));
404                 } else if self.use_small_heuristics.2 == Heuristics::Max {
405                     let max_width = self.max_width.2;
406                     self.set().width_heuristics(WidthHeuristics::set(max_width));
407                 } else {
408                     self.set().width_heuristics(WidthHeuristics::null());
409                 }
410             }
411
412             fn set_license_template(&mut self) {
413                 if self.was_set().license_template_path() {
414                     let lt_path = self.license_template_path();
415                     match license::load_and_compile_template(&lt_path) {
416                         Ok(re) => self.license_template = Some(re),
417                         Err(msg) => eprintln!("Warning for license template file {:?}: {}",
418                                               lt_path, msg),
419                     }
420                 }
421             }
422
423             fn set_ignore(&mut self, dir: &Path) {
424                 self.ignore.2.add_prefix(dir);
425             }
426
427             /// Returns true if the config key was explicitly set and is the default value.
428             pub fn is_default(&self, key: &str) -> bool {
429                 $(
430                     if let stringify!($i) = key {
431                         return self.$i.1 && self.$i.2 == $def;
432                     }
433                  )+
434                 false
435             }
436         }
437
438         // Template for the default configuration
439         impl Default for Config {
440             fn default() -> Config {
441                 Config {
442                     license_template: None,
443                     $(
444                         $i: (Cell::new(false), false, $def, $stb),
445                     )+
446                 }
447             }
448         }
449     )
450 }