rust-clippy/clippy_lints/src/utils/conf.rs

230 lines
10 KiB
Rust
Raw Normal View History

//! Read configurations files.
2021-04-28 02:04:06 +00:00
#![allow(clippy::module_name_repetitions)]
2021-04-28 02:04:06 +00:00
use serde::de::{Deserializer, IgnoredAny, IntoDeserializer, MapAccess, Visitor};
use serde::Deserialize;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::{env, fmt, fs, io};
2018-07-19 07:11:15 +00:00
2021-04-28 02:04:06 +00:00
/// Conf with parse errors
#[derive(Default)]
pub struct TryConf {
pub conf: Conf,
pub errors: Vec<String>,
}
2021-04-28 02:04:06 +00:00
impl TryConf {
fn from_error(error: impl Error) -> Self {
Self {
conf: Conf::default(),
errors: vec![error.to_string()],
}
}
}
2021-04-28 02:04:06 +00:00
macro_rules! define_Conf {
($(
#[doc = $doc:literal]
2021-04-28 02:04:06 +00:00
$(#[conf_deprecated($dep:literal)])?
2021-05-02 22:50:22 +00:00
($name:ident: $ty:ty = $default:expr),
2021-04-28 02:04:06 +00:00
)*) => {
/// Clippy lint configuration
pub struct Conf {
$(#[doc = $doc] pub $name: $ty,)*
2021-04-28 02:04:06 +00:00
}
2021-04-28 02:04:06 +00:00
mod defaults {
2021-05-02 22:50:22 +00:00
$(pub fn $name() -> $ty { $default })*
2021-04-28 02:04:06 +00:00
}
2021-04-28 02:04:06 +00:00
impl Default for Conf {
fn default() -> Self {
Self { $($name: defaults::$name(),)* }
}
2021-04-28 02:04:06 +00:00
}
2021-04-28 02:04:06 +00:00
impl<'de> Deserialize<'de> for TryConf {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
deserializer.deserialize_map(ConfVisitor)
}
}
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "kebab-case")]
#[allow(non_camel_case_types)]
enum Field { $($name,)* third_party, }
struct ConfVisitor;
impl<'de> Visitor<'de> for ConfVisitor {
type Value = TryConf;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Conf")
}
2021-04-28 02:04:06 +00:00
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de> {
let mut errors = Vec::new();
$(let mut $name = None;)*
// could get `Field` here directly, but get `str` first for diagnostics
while let Some(name) = map.next_key::<&str>()? {
match Field::deserialize(name.into_deserializer())? {
$(Field::$name => {
$(errors.push(format!("deprecated field `{}`. {}", name, $dep));)?
match map.next_value() {
Err(e) => errors.push(e.to_string()),
Ok(value) => match $name {
Some(_) => errors.push(format!("duplicate field `{}`", name)),
None => $name = Some(value),
}
}
})*
// white-listed; ignore
Field::third_party => drop(map.next_value::<IgnoredAny>())
}
2017-05-09 13:23:38 +00:00
}
2021-04-28 02:04:06 +00:00
let conf = Conf { $($name: $name.unwrap_or_else(defaults::$name),)* };
Ok(TryConf { conf, errors })
}
}
#[cfg(feature = "metadata-collector-lint")]
pub mod metadata {
use crate::utils::internal_lints::metadata_collector::ClippyConfigurationBasicInfo;
pub(crate) fn get_configuration_metadata() -> Vec<ClippyConfigurationBasicInfo> {
vec![
$(
ClippyConfigurationBasicInfo {
name: stringify!($name),
config_type: stringify!($ty),
default: stringify!($default),
doc_comment: $doc,
},
)+
]
}
}
};
2016-02-22 13:25:51 +00:00
}
2021-05-02 22:50:22 +00:00
// N.B., this macro is parsed by util/lintlib.py
define_Conf! {
2021-05-06 05:04:50 +00:00
/// 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
2021-05-02 22:50:22 +00:00
(msrv: Option<String> = None),
/// Lint: BLACKLISTED_NAME. The list of blacklisted names to lint about. NB: `bar` is not here since it has legitimate uses
2021-04-28 02:04:06 +00:00
(blacklisted_names: Vec<String> = ["foo", "baz", "quux"].iter().map(ToString::to_string).collect()),
/// Lint: COGNITIVE_COMPLEXITY. The maximum cognitive complexity a function can have
2021-04-28 02:04:06 +00:00
(cognitive_complexity_threshold: u64 = 25),
/// Lint: CYCLOMATIC_COMPLEXITY. Use the Cognitive Complexity lint instead.
2021-05-02 21:56:46 +00:00
#[conf_deprecated("Please use `cognitive-complexity-threshold` instead")]
2021-05-02 22:50:22 +00:00
(cyclomatic_complexity_threshold: Option<u64> = None),
/// Lint: DOC_MARKDOWN. The list of words this lint should not consider as identifiers needing ticks
2021-04-28 02:04:06 +00:00
(doc_valid_idents: Vec<String> = [
2017-05-06 19:31:54 +00:00
"KiB", "MiB", "GiB", "TiB", "PiB", "EiB",
2016-12-21 11:30:41 +00:00
"DirectX",
"ECMAScript",
2016-12-21 11:30:41 +00:00
"GPLv2", "GPLv3",
"GitHub", "GitLab",
2016-12-21 11:30:41 +00:00
"IPv4", "IPv6",
"ClojureScript", "CoffeeScript", "JavaScript", "PureScript", "TypeScript",
"NaN", "NaNs",
2020-09-01 13:05:19 +00:00
"OAuth", "GraphQL",
"OCaml",
2021-02-24 04:04:00 +00:00
"OpenGL", "OpenMP", "OpenSSH", "OpenSSL", "OpenStreetMap", "OpenDNS",
2020-11-27 00:42:37 +00:00
"WebGL",
"TensorFlow",
2016-12-21 11:30:41 +00:00
"TrueType",
"iOS", "macOS",
"TeX", "LaTeX", "BibTeX", "BibLaTeX",
2017-04-25 09:38:37 +00:00
"MinGW",
2018-12-11 18:37:43 +00:00
"CamelCase",
].iter().map(ToString::to_string).collect()),
2016-02-22 13:25:51 +00:00
/// Lint: TOO_MANY_ARGUMENTS. The maximum number of argument a function or method can have
2021-04-28 02:04:06 +00:00
(too_many_arguments_threshold: u64 = 7),
2016-02-22 13:25:51 +00:00
/// Lint: TYPE_COMPLEXITY. The maximum complexity a type can have
2021-04-28 02:04:06 +00:00
(type_complexity_threshold: u64 = 250),
/// Lint: MANY_SINGLE_CHAR_NAMES. The maximum number of single char bindings a scope may have
2021-04-28 02:04:06 +00:00
(single_char_binding_names_threshold: u64 = 4),
/// Lint: BOXED_LOCAL, USELESS_VEC. The maximum size of objects (in bytes) that will be linted. Larger objects are ok on the heap
2021-04-28 02:04:06 +00:00
(too_large_for_stack: u64 = 200),
/// Lint: ENUM_VARIANT_NAMES. The minimum number of enum variants for the lints about variant names to trigger
2021-04-28 02:04:06 +00:00
(enum_variant_name_threshold: u64 = 3),
2018-12-07 11:24:59 +00:00
/// Lint: LARGE_ENUM_VARIANT. The maximum size of a enum's variant to avoid box suggestion
2021-04-28 02:04:06 +00:00
(enum_variant_size_threshold: u64 = 200),
/// Lint: VERBOSE_BIT_MASK. The maximum allowed size of a bit mask before suggesting to use 'trailing_zeros'
2021-04-28 02:04:06 +00:00
(verbose_bit_mask_threshold: u64 = 1),
2018-01-23 14:29:31 +00:00
/// Lint: DECIMAL_LITERAL_REPRESENTATION. The lower bound for linting decimal literals
2021-04-28 02:04:06 +00:00
(literal_representation_threshold: u64 = 16384),
/// Lint: TRIVIALLY_COPY_PASS_BY_REF. The maximum size (in bytes) to consider a `Copy` type for passing by value instead of by reference.
2021-05-02 22:50:22 +00:00
(trivial_copy_size_limit: Option<u64> = None),
/// Lint: LARGE_TYPE_PASS_BY_MOVE. The minimum size (in bytes) to consider a type for passing by reference instead of by value.
2021-04-28 02:04:06 +00:00
(pass_by_value_size_limit: u64 = 256),
2019-01-13 15:19:02 +00:00
/// Lint: TOO_MANY_LINES. The maximum number of lines a function or method can have
2021-04-28 02:04:06 +00:00
(too_many_lines_threshold: u64 = 100),
2020-03-23 21:07:46 +00:00
/// Lint: LARGE_STACK_ARRAYS, LARGE_CONST_ARRAYS. The maximum allowed size for arrays on the stack
2021-04-28 02:04:06 +00:00
(array_size_threshold: u64 = 512_000),
2020-01-23 14:52:41 +00:00
/// Lint: VEC_BOX. The size of the boxed type in bytes, where boxing in a `Vec` is allowed
2021-04-28 02:04:06 +00:00
(vec_box_size_threshold: u64 = 4096),
/// Lint: TYPE_REPETITION_IN_BOUNDS. The maximum number of bounds a trait can have to be linted
2021-04-28 02:04:06 +00:00
(max_trait_bounds: u64 = 3),
2020-02-01 23:49:52 +00:00
/// Lint: STRUCT_EXCESSIVE_BOOLS. The maximum number of bools a struct can have
2021-04-28 02:04:06 +00:00
(max_struct_bools: u64 = 3),
2020-02-01 23:49:52 +00:00
/// Lint: FN_PARAMS_EXCESSIVE_BOOLS. The maximum number of bools function parameters can have
2021-04-28 02:04:06 +00:00
(max_fn_params_bools: u64 = 3),
/// Lint: WILDCARD_IMPORTS. Whether to allow certain wildcard imports (prelude, super in tests).
2021-05-02 22:50:22 +00:00
(warn_on_all_wildcard_imports: bool = false),
/// Lint: DISALLOWED_METHOD. The list of disallowed methods, written as fully qualified paths.
2021-05-02 22:50:22 +00:00
(disallowed_methods: Vec<String> = Vec::new()),
/// Lint: UNREADABLE_LITERAL. Should the fraction of a decimal be linted to include separators.
2021-04-28 02:04:06 +00:00
(unreadable_literal_lint_fractions: bool = true),
/// Lint: UPPER_CASE_ACRONYMS. Enables verbose mode. Triggers if there is more than one uppercase char next to each other
2021-05-02 22:50:22 +00:00
(upper_case_acronyms_aggressive: bool = false),
/// Lint: _CARGO_COMMON_METADATA. For internal testing only, ignores the current `publish` settings in the Cargo manifest.
2021-05-02 22:50:22 +00:00
(cargo_ignore_publish: bool = false),
}
2016-10-25 17:41:24 +00:00
/// Search for the configuration file.
pub fn lookup_conf_file() -> io::Result<Option<PathBuf>> {
2016-10-25 17:41:24 +00:00
/// Possible filename to search for.
const CONFIG_FILE_NAMES: [&str; 2] = [".clippy.toml", "clippy.toml"];
2016-10-25 17:41:24 +00:00
// Start looking for a config file in CLIPPY_CONF_DIR, or failing that, CARGO_MANIFEST_DIR.
// If neither of those exist, use ".".
let mut current = env::var_os("CLIPPY_CONF_DIR")
.or_else(|| env::var_os("CARGO_MANIFEST_DIR"))
.map_or_else(|| PathBuf::from("."), PathBuf::from);
2016-10-25 17:41:24 +00:00
loop {
for config_file_name in &CONFIG_FILE_NAMES {
let config_file = current.join(config_file_name);
match fs::metadata(&config_file) {
// Only return if it's a file to handle the unlikely situation of a directory named
// `clippy.toml`.
Ok(ref md) if !md.is_dir() => return Ok(Some(config_file)),
2016-10-25 17:41:24 +00:00
// Return the error if it's something other than `NotFound`; otherwise we didn't
// find the project file yet, and continue searching.
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
_ => {},
2016-10-25 17:41:24 +00:00
}
}
// If the current directory has no parent, we're done searching.
if !current.pop() {
return Ok(None);
}
}
}
/// Read the `toml` configuration file.
///
2016-03-06 14:48:56 +00:00
/// In case of error, the function tries to continue as much as possible.
2021-04-28 02:04:06 +00:00
pub fn read(path: &Path) -> TryConf {
let content = match fs::read_to_string(path) {
2021-04-28 02:04:06 +00:00
Err(e) => return TryConf::from_error(e),
Ok(content) => content,
};
2021-04-28 02:04:06 +00:00
toml::from_str(&content).unwrap_or_else(TryConf::from_error)
}