1 //! Read configurations files.
3 #![allow(clippy::module_name_repetitions)]
5 use serde::de::{Deserializer, IgnoredAny, IntoDeserializer, MapAccess, Visitor};
6 use serde::Deserialize;
8 use std::path::{Path, PathBuf};
9 use std::{env, fmt, fs, io};
11 /// Conf with parse errors
15 pub errors: Vec<String>,
19 fn from_error(error: impl Error) -> Self {
21 conf: Conf::default(),
22 errors: vec![error.to_string()],
27 macro_rules! define_Conf {
30 $(#[conf_deprecated($dep:literal)])?
31 ($name:ident: $ty:ty = $default:expr),
33 /// Clippy lint configuration
35 $(#[$doc] pub $name: $ty,)*
39 $(pub fn $name() -> $ty { $default })*
42 impl Default for Conf {
43 fn default() -> Self {
44 Self { $($name: defaults::$name(),)* }
48 impl<'de> Deserialize<'de> for TryConf {
49 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
50 deserializer.deserialize_map(ConfVisitor)
54 #[derive(Deserialize)]
55 #[serde(field_identifier, rename_all = "kebab-case")]
56 #[allow(non_camel_case_types)]
57 enum Field { $($name,)* third_party, }
61 impl<'de> Visitor<'de> for ConfVisitor {
64 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65 formatter.write_str("Conf")
68 fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de> {
69 let mut errors = Vec::new();
70 $(let mut $name = None;)*
71 // could get `Field` here directly, but get `str` first for diagnostics
72 while let Some(name) = map.next_key::<&str>()? {
73 match Field::deserialize(name.into_deserializer())? {
75 $(errors.push(format!("deprecated field `{}`. {}", name, $dep));)?
76 match map.next_value() {
77 Err(e) => errors.push(e.to_string()),
78 Ok(value) => match $name {
79 Some(_) => errors.push(format!("duplicate field `{}`", name)),
80 None => $name = Some(value),
84 // white-listed; ignore
85 Field::third_party => drop(map.next_value::<IgnoredAny>())
88 let conf = Conf { $($name: $name.unwrap_or_else(defaults::$name),)* };
89 Ok(TryConf { conf, errors })
95 // N.B., this macro is parsed by util/lintlib.py
97 /// Lint: CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE. The minimum rust version that the project supports
98 (msrv: Option<String> = None),
99 /// Lint: BLACKLISTED_NAME. The list of blacklisted names to lint about. NB: `bar` is not here since it has legitimate uses
100 (blacklisted_names: Vec<String> = ["foo", "baz", "quux"].iter().map(ToString::to_string).collect()),
101 /// Lint: COGNITIVE_COMPLEXITY. The maximum cognitive complexity a function can have
102 (cognitive_complexity_threshold: u64 = 25),
103 /// DEPRECATED LINT: CYCLOMATIC_COMPLEXITY. Use the Cognitive Complexity lint instead.
104 #[conf_deprecated("Please use `cognitive-complexity-threshold` instead")]
105 (cyclomatic_complexity_threshold: Option<u64> = None),
106 /// Lint: DOC_MARKDOWN. The list of words this lint should not consider as identifiers needing ticks
107 (doc_valid_idents: Vec<String> = [
108 "KiB", "MiB", "GiB", "TiB", "PiB", "EiB",
114 "ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript",
118 "OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenDNS",
123 "TeX", "LaTeX", "BibTeX", "BibLaTeX",
126 ].iter().map(ToString::to_string).collect()),
127 /// Lint: TOO_MANY_ARGUMENTS. The maximum number of argument a function or method can have
128 (too_many_arguments_threshold: u64 = 7),
129 /// Lint: TYPE_COMPLEXITY. The maximum complexity a type can have
130 (type_complexity_threshold: u64 = 250),
131 /// Lint: MANY_SINGLE_CHAR_NAMES. The maximum number of single char bindings a scope may have
132 (single_char_binding_names_threshold: u64 = 4),
133 /// Lint: BOXED_LOCAL, USELESS_VEC. The maximum size of objects (in bytes) that will be linted. Larger objects are ok on the heap
134 (too_large_for_stack: u64 = 200),
135 /// Lint: ENUM_VARIANT_NAMES. The minimum number of enum variants for the lints about variant names to trigger
136 (enum_variant_name_threshold: u64 = 3),
137 /// Lint: LARGE_ENUM_VARIANT. The maximum size of a enum's variant to avoid box suggestion
138 (enum_variant_size_threshold: u64 = 200),
139 /// Lint: VERBOSE_BIT_MASK. The maximum allowed size of a bit mask before suggesting to use 'trailing_zeros'
140 (verbose_bit_mask_threshold: u64 = 1),
141 /// Lint: DECIMAL_LITERAL_REPRESENTATION. The lower bound for linting decimal literals
142 (literal_representation_threshold: u64 = 16384),
143 /// Lint: TRIVIALLY_COPY_PASS_BY_REF. The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by reference.
144 (trivial_copy_size_limit: Option<u64> = None),
145 /// Lint: LARGE_TYPE_PASS_BY_MOVE. The minimum size (in bytes) to consider a type for passing by reference instead of by value.
146 (pass_by_value_size_limit: u64 = 256),
147 /// Lint: TOO_MANY_LINES. The maximum number of lines a function or method can have
148 (too_many_lines_threshold: u64 = 100),
149 /// Lint: LARGE_STACK_ARRAYS, LARGE_CONST_ARRAYS. The maximum allowed size for arrays on the stack
150 (array_size_threshold: u64 = 512_000),
151 /// Lint: VEC_BOX. The size of the boxed type in bytes, where boxing in a `Vec` is allowed
152 (vec_box_size_threshold: u64 = 4096),
153 /// Lint: TYPE_REPETITION_IN_BOUNDS. The maximum number of bounds a trait can have to be linted
154 (max_trait_bounds: u64 = 3),
155 /// Lint: STRUCT_EXCESSIVE_BOOLS. The maximum number of bools a struct can have
156 (max_struct_bools: u64 = 3),
157 /// Lint: FN_PARAMS_EXCESSIVE_BOOLS. The maximum number of bools function parameters can have
158 (max_fn_params_bools: u64 = 3),
159 /// Lint: WILDCARD_IMPORTS. Whether to allow certain wildcard imports (prelude, super in tests).
160 (warn_on_all_wildcard_imports: bool = false),
161 /// Lint: DISALLOWED_METHOD. The list of disallowed methods, written as fully qualified paths.
162 (disallowed_methods: Vec<String> = Vec::new()),
163 /// Lint: UNREADABLE_LITERAL. Should the fraction of a decimal be linted to include separators.
164 (unreadable_literal_lint_fractions: bool = true),
165 /// Lint: UPPER_CASE_ACRONYMS. Enables verbose mode. Triggers if there is more than one uppercase char next to each other
166 (upper_case_acronyms_aggressive: bool = false),
167 /// Lint: _CARGO_COMMON_METADATA. For internal testing only, ignores the current `publish` settings in the Cargo manifest.
168 (cargo_ignore_publish: bool = false),
171 /// Search for the configuration file.
172 pub fn lookup_conf_file() -> io::Result<Option<PathBuf>> {
173 /// Possible filename to search for.
174 const CONFIG_FILE_NAMES: [&str; 2] = [".clippy.toml", "clippy.toml"];
176 // Start looking for a config file in CLIPPY_CONF_DIR, or failing that, CARGO_MANIFEST_DIR.
177 // If neither of those exist, use ".".
178 let mut current = env::var_os("CLIPPY_CONF_DIR")
179 .or_else(|| env::var_os("CARGO_MANIFEST_DIR"))
180 .map_or_else(|| PathBuf::from("."), PathBuf::from);
182 for config_file_name in &CONFIG_FILE_NAMES {
183 let config_file = current.join(config_file_name);
184 match fs::metadata(&config_file) {
185 // Only return if it's a file to handle the unlikely situation of a directory named
187 Ok(ref md) if !md.is_dir() => return Ok(Some(config_file)),
188 // Return the error if it's something other than `NotFound`; otherwise we didn't
189 // find the project file yet, and continue searching.
190 Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
195 // If the current directory has no parent, we're done searching.
202 /// Read the `toml` configuration file.
204 /// In case of error, the function tries to continue as much as possible.
205 pub fn read(path: &Path) -> TryConf {
206 let content = match fs::read_to_string(path) {
207 Err(e) => return TryConf::from_error(e),
208 Ok(content) => content,
210 toml::from_str(&content).unwrap_or_else(TryConf::from_error)