1 use crate::config::file_lines::FileLines;
2 use crate::config::options::{IgnoreList, WidthHeuristics};
4 /// Trait for types that can be used in `Config`.
5 pub(crate) trait ConfigType: Sized {
6 /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
7 /// pipe-separated list of variants; for other types it returns "<type>".
8 fn doc_hint() -> String;
11 impl ConfigType for bool {
12 fn doc_hint() -> String {
13 String::from("<boolean>")
17 impl ConfigType for usize {
18 fn doc_hint() -> String {
19 String::from("<unsigned integer>")
23 impl ConfigType for isize {
24 fn doc_hint() -> String {
25 String::from("<signed integer>")
29 impl ConfigType for String {
30 fn doc_hint() -> String {
31 String::from("<string>")
35 impl ConfigType for FileLines {
36 fn doc_hint() -> String {
37 String::from("<json>")
41 impl ConfigType for WidthHeuristics {
42 fn doc_hint() -> String {
47 impl ConfigType for IgnoreList {
48 fn doc_hint() -> String {
49 String::from("[<string>,..]")
53 macro_rules! create_config {
54 ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => (
56 use std::collections::HashSet;
59 use serde::{Deserialize, Serialize};
62 #[allow(unreachable_pub)]
64 // if a license_template_path has been specified, successfully read, parsed and compiled
65 // into a regex, it will be stored here
66 pub license_template: Option<Regex>,
67 // For each config item, we store a bool indicating whether it has
68 // been accessed and the value, and a bool whether the option was
69 // manually initialised, or taken from the default,
70 $($i: (Cell<bool>, bool, $ty, bool)),+
73 // Just like the Config struct but with each property wrapped
74 // as Option<T>. This is used to parse a rustfmt.toml that doesn't
75 // specify all properties of `Config`.
76 // We first parse into `PartialConfig`, then create a default `Config`
77 // and overwrite the properties with corresponding values from `PartialConfig`.
78 #[derive(Deserialize, Serialize, Clone)]
79 #[allow(unreachable_pub)]
80 pub struct PartialConfig {
81 $(pub $i: Option<$ty>),+
84 // Macro hygiene won't allow us to make `set_$i()` methods on Config
85 // for each item, so this struct is used to give the API to set values:
86 // `config.set().option(false)`. It's pretty ugly. Consider replacing
87 // with `config.set_option(false)` if we ever get a stable/usable
88 // `concat_idents!()`.
89 #[allow(unreachable_pub)]
90 pub struct ConfigSetter<'a>(&'a mut Config);
92 impl<'a> ConfigSetter<'a> {
94 #[allow(unreachable_pub)]
95 pub fn $i(&mut self, value: $ty) {
96 (self.0).$i.2 = value;
97 match stringify!($i) {
98 "max_width" | "use_small_heuristics" => self.0.set_heuristics(),
99 "license_template_path" => self.0.set_license_template(),
106 // Query each option, returns true if the user set the option, false if
107 // a default was used.
108 #[allow(unreachable_pub)]
109 pub struct ConfigWasSet<'a>(&'a Config);
111 impl<'a> ConfigWasSet<'a> {
113 #[allow(unreachable_pub)]
114 pub fn $i(&self) -> bool {
122 #[allow(unreachable_pub)]
123 pub fn $i(&self) -> $ty {
129 #[allow(unreachable_pub)]
130 pub fn set(&mut self) -> ConfigSetter<'_> {
134 #[allow(unreachable_pub)]
135 pub fn was_set(&self) -> ConfigWasSet<'_> {
139 fn fill_from_parsed_config(mut self, parsed: PartialConfig, dir: &Path) -> Config {
141 if let Some(val) = parsed.$i {
146 if crate::is_nightly_channel!() {
150 eprintln!("Warning: can't set `{} = {:?}`, unstable features are only \
151 available in nightly channel.", stringify!($i), val);
156 self.set_heuristics();
157 self.set_license_template();
158 self.set_ignore(dir);
162 /// Returns a hash set initialized with every user-facing config option name.
164 pub(crate) fn hash_set() -> HashSet<String> {
165 let mut hash_set = HashSet::new();
167 hash_set.insert(stringify!($i).to_owned());
172 pub(crate) fn is_valid_name(name: &str) -> bool {
175 stringify!($i) => true,
181 #[allow(unreachable_pub)]
182 pub fn used_options(&self) -> PartialConfig {
185 $i: if self.$i.0.get() {
186 Some(self.$i.2.clone())
194 #[allow(unreachable_pub)]
195 pub fn all_options(&self) -> PartialConfig {
198 $i: Some(self.$i.2.clone()),
203 #[allow(unreachable_pub)]
204 pub fn override_value(&mut self, key: &str, val: &str)
210 self.$i.2 = val.parse::<$ty>()
211 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
217 _ => panic!("Unknown config key in override: {}", key)
221 "max_width" | "use_small_heuristics" => self.set_heuristics(),
222 "license_template_path" => self.set_license_template(),
227 #[allow(unreachable_pub)]
228 pub fn is_hidden_option(name: &str) -> bool {
229 const HIDE_OPTIONS: [&str; 4] =
230 ["verbose", "verbose_diff", "file_lines", "width_heuristics"];
231 HIDE_OPTIONS.contains(&name)
234 #[allow(unreachable_pub)]
235 pub fn print_docs(out: &mut dyn Write, include_unstable: bool) {
238 $( let max = cmp::max(max, stringify!($i).len()+1); )+
239 let space_str = " ".repeat(max);
240 writeln!(out, "Configuration Options:").unwrap();
242 if $stb || include_unstable {
243 let name_raw = stringify!($i);
245 if !Config::is_hidden_option(name_raw) {
246 let mut name_out = String::with_capacity(max);
247 for _ in name_raw.len()..max-1 {
250 name_out.push_str(name_raw);
252 let mut default_str = format!("{}", $def);
253 if default_str.is_empty() {
254 default_str = String::from("\"\"");
257 "{}{} Default: {}{}",
261 if !$stb { " (unstable)" } else { "" }).unwrap();
263 writeln!(out, "{}{}", space_str, $dstring).unwrap();
265 writeln!(out).unwrap();
271 fn set_heuristics(&mut self) {
272 if self.use_small_heuristics.2 == Heuristics::Default {
273 let max_width = self.max_width.2;
274 self.set().width_heuristics(WidthHeuristics::scaled(max_width));
275 } else if self.use_small_heuristics.2 == Heuristics::Max {
276 let max_width = self.max_width.2;
277 self.set().width_heuristics(WidthHeuristics::set(max_width));
279 self.set().width_heuristics(WidthHeuristics::null());
283 fn set_license_template(&mut self) {
284 if self.was_set().license_template_path() {
285 let lt_path = self.license_template_path();
286 match license::load_and_compile_template(<_path) {
287 Ok(re) => self.license_template = Some(re),
288 Err(msg) => eprintln!("Warning for license template file {:?}: {}",
294 fn set_ignore(&mut self, dir: &Path) {
295 self.ignore.2.add_prefix(dir);
298 #[allow(unreachable_pub)]
299 /// Returns `true` if the config key was explicitly set and is the default value.
300 pub fn is_default(&self, key: &str) -> bool {
302 if let stringify!($i) = key {
303 return self.$i.1 && self.$i.2 == $def;
310 // Template for the default configuration
311 impl Default for Config {
312 fn default() -> Config {
314 license_template: None,
316 $i: (Cell::new(false), false, $def, $stb),