reek-rs 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/Cargo.lock +614 -0
- data/Cargo.toml +24 -0
- data/DIVERGENCES.md +15 -0
- data/LICENSE +22 -0
- data/README.md +125 -0
- data/THIRD_PARTY_NOTICES.md +57 -0
- data/crates/reek-cli/Cargo.toml +22 -0
- data/crates/reek-cli/src/main.rs +277 -0
- data/crates/reek-core/Cargo.toml +21 -0
- data/crates/reek-core/src/ast.rs +449 -0
- data/crates/reek-core/src/code_comment.rs +245 -0
- data/crates/reek-core/src/comments.rs +179 -0
- data/crates/reek-core/src/config.rs +803 -0
- data/crates/reek-core/src/context.rs +891 -0
- data/crates/reek-core/src/detectors/attribute.rs +13 -0
- data/crates/reek-core/src/detectors/boolean_parameter.rs +20 -0
- data/crates/reek-core/src/detectors/class_variable.rs +25 -0
- data/crates/reek-core/src/detectors/control_parameter.rs +110 -0
- data/crates/reek-core/src/detectors/data_clump.rs +114 -0
- data/crates/reek-core/src/detectors/duplicate_method_call.rs +63 -0
- data/crates/reek-core/src/detectors/feature_envy.rs +32 -0
- data/crates/reek-core/src/detectors/instance_variable_assumption.rs +39 -0
- data/crates/reek-core/src/detectors/irresponsible_module.rs +12 -0
- data/crates/reek-core/src/detectors/long_parameter_list.rs +16 -0
- data/crates/reek-core/src/detectors/long_yield_list.rs +20 -0
- data/crates/reek-core/src/detectors/manual_dispatch.rs +18 -0
- data/crates/reek-core/src/detectors/missing_safe_method.rs +34 -0
- data/crates/reek-core/src/detectors/mod.rs +479 -0
- data/crates/reek-core/src/detectors/module_initialize.rs +15 -0
- data/crates/reek-core/src/detectors/nested_iterators.rs +82 -0
- data/crates/reek-core/src/detectors/nil_check.rs +40 -0
- data/crates/reek-core/src/detectors/repeated_conditional.rs +51 -0
- data/crates/reek-core/src/detectors/subclassed_from_core_class.rs +22 -0
- data/crates/reek-core/src/detectors/too_many_constants.rs +18 -0
- data/crates/reek-core/src/detectors/too_many_instance_variables.rs +25 -0
- data/crates/reek-core/src/detectors/too_many_methods.rs +15 -0
- data/crates/reek-core/src/detectors/too_many_statements.rs +16 -0
- data/crates/reek-core/src/detectors/uncommunicative_method_name.rs +32 -0
- data/crates/reek-core/src/detectors/uncommunicative_module_name.rs +33 -0
- data/crates/reek-core/src/detectors/uncommunicative_parameter_name.rs +49 -0
- data/crates/reek-core/src/detectors/uncommunicative_variable_name.rs +138 -0
- data/crates/reek-core/src/detectors/unused_parameters.rs +21 -0
- data/crates/reek-core/src/detectors/unused_private_method.rs +59 -0
- data/crates/reek-core/src/detectors/utility_function.rs +27 -0
- data/crates/reek-core/src/encodings.rs +180 -0
- data/crates/reek-core/src/examiner.rs +165 -0
- data/crates/reek-core/src/lib.rs +21 -0
- data/crates/reek-core/src/node.rs +423 -0
- data/crates/reek-core/src/ruby_format.rs +60 -0
- data/crates/reek-core/src/ruby_inspect.rs +172 -0
- data/crates/reek-core/src/ruby_regexp.rs +243 -0
- data/crates/reek-core/src/single_byte_encodings.rs +6007 -0
- data/crates/reek-core/src/source.rs +280 -0
- data/crates/reek-core/src/translate.rs +3112 -0
- data/crates/reek-core/src/yaml.rs +520 -0
- data/ext/reek_rs/Cargo.toml +18 -0
- data/ext/reek_rs/extconf.rb +6 -0
- data/ext/reek_rs/src/lib.rs +155 -0
- data/lib/reek_rs/version.rb +8 -0
- data/lib/reek_rs.rb +390 -0
- metadata +123 -0
|
@@ -0,0 +1,803 @@
|
|
|
1
|
+
//! Reek's configuration file (`Reek::Configuration::AppConfiguration`):
|
|
2
|
+
//! finding `.reek.yml`, loading and validating it as Reek does (Psych's
|
|
3
|
+
//! `YAML.load_file`, then Reek's dry-schema schema), turning `/.../`
|
|
4
|
+
//! strings into patterns, and choosing the directive for a file.
|
|
5
|
+
|
|
6
|
+
use std::path::{Path, PathBuf};
|
|
7
|
+
|
|
8
|
+
use indexmap::IndexMap;
|
|
9
|
+
|
|
10
|
+
use crate::detectors::DETECTORS;
|
|
11
|
+
use crate::examiner::Directive;
|
|
12
|
+
use crate::ruby_regexp::RubyRegexp;
|
|
13
|
+
use crate::yaml::{self, Value, YamlError};
|
|
14
|
+
|
|
15
|
+
/// `ConfigurationFileFinder::DEFAULT_FILE_NAME`.
|
|
16
|
+
pub const DEFAULT_FILE_NAME: &str = ".reek.yml";
|
|
17
|
+
|
|
18
|
+
/// An error loading the configuration: usually
|
|
19
|
+
/// `Reek::Errors::ConfigFileError`.
|
|
20
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
21
|
+
pub struct ConfigError {
|
|
22
|
+
/// The Ruby class of the error.
|
|
23
|
+
pub class: &'static str,
|
|
24
|
+
pub message: String,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
impl ConfigError {
|
|
28
|
+
fn config_file(message: String) -> Self {
|
|
29
|
+
ConfigError { class: "Reek::Errors::ConfigFileError", message }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/// The loaded configuration.
|
|
34
|
+
#[derive(Clone, Debug, Default)]
|
|
35
|
+
pub struct AppConfiguration {
|
|
36
|
+
/// `default_directive`: the `detectors` section, by detector.
|
|
37
|
+
default_directive: Directive,
|
|
38
|
+
/// `directory_directives`: the `directories` section, by directory
|
|
39
|
+
/// (without a trailing `/`), in file order.
|
|
40
|
+
directory_directives: Vec<(String, Directive)>,
|
|
41
|
+
/// The `exclude_paths` patterns, as written. Reek expands them with
|
|
42
|
+
/// `Dir[]` when loading; callers do that themselves.
|
|
43
|
+
exclude_paths: Vec<String>,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
impl AppConfiguration {
|
|
47
|
+
/// `AppConfiguration.from_default_path`: the `.reek.yml` in the current
|
|
48
|
+
/// directory or the nearest directory above it, else in the home
|
|
49
|
+
/// directory; the default configuration when there is none.
|
|
50
|
+
pub fn from_default_path() -> Result<Self, ConfigError> {
|
|
51
|
+
let current = std::env::current_dir()
|
|
52
|
+
.map_err(|error| ConfigError { class: "Errno::ENOENT", message: error.to_string() })?;
|
|
53
|
+
let home = std::env::var_os("HOME").map(PathBuf::from);
|
|
54
|
+
match find(¤t, home.as_deref()) {
|
|
55
|
+
Some(path) => Self::from_path(&path),
|
|
56
|
+
None => Ok(Self::default()),
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/// `AppConfiguration.from_path(path)`.
|
|
61
|
+
pub fn from_path(path: &Path) -> Result<Self, ConfigError> {
|
|
62
|
+
let values = load_from_file(path)?;
|
|
63
|
+
Self::from_values(values)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// `AppConfiguration.new(values:)`: `load_values`.
|
|
67
|
+
fn from_values(values: IndexMap<String, Value>) -> Result<Self, ConfigError> {
|
|
68
|
+
let mut configuration = AppConfiguration::default();
|
|
69
|
+
for (key, value) in values {
|
|
70
|
+
match (key.as_str(), value) {
|
|
71
|
+
("exclude_paths", Value::Array(paths)) => {
|
|
72
|
+
configuration.exclude_paths.extend(paths.into_iter().map(|path| path.to_s()));
|
|
73
|
+
}
|
|
74
|
+
("directories", Value::Hash(directories)) => configuration.add_directories(directories)?,
|
|
75
|
+
("detectors", Value::Hash(detectors)) => {
|
|
76
|
+
for (name, options) in detectors {
|
|
77
|
+
let Value::Hash(options) = options else { continue };
|
|
78
|
+
let directive = configuration.default_directive.entry(name).or_default();
|
|
79
|
+
directive.extend(options);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
_ => {}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
Ok(configuration)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/// `DirectoryDirectives#add`: a directory that is a file is an error.
|
|
89
|
+
fn add_directories(&mut self, directories: IndexMap<String, Value>) -> Result<(), ConfigError> {
|
|
90
|
+
for (path, detector_config) in directories {
|
|
91
|
+
let directory = path.strip_suffix('/').unwrap_or(&path).to_string();
|
|
92
|
+
if Path::new(&directory).is_file() {
|
|
93
|
+
return Err(ConfigError::config_file(format!("`{directory}` is supposed to be a directory but is a file")));
|
|
94
|
+
}
|
|
95
|
+
let Value::Hash(detector_config) = detector_config else { continue };
|
|
96
|
+
let mut directive = Directive::new();
|
|
97
|
+
for (name, options) in detector_config {
|
|
98
|
+
let Value::Hash(options) = options else { continue };
|
|
99
|
+
directive.insert(name, options);
|
|
100
|
+
}
|
|
101
|
+
match self.directory_directives.iter_mut().find(|(existing, _)| *existing == directory) {
|
|
102
|
+
Some((_, existing)) => *existing = directive,
|
|
103
|
+
None => self.directory_directives.push((directory, directive)),
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
Ok(())
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/// The `exclude_paths` patterns.
|
|
110
|
+
pub fn exclude_paths(&self) -> &[String] {
|
|
111
|
+
&self.exclude_paths
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/// `directive_for(origin)`: the `detectors` section, with each detector
|
|
115
|
+
/// the best matching `directories` entry configures replaced by that
|
|
116
|
+
/// entry's configuration. The best match is the longest directory
|
|
117
|
+
/// pattern matching the file's directory.
|
|
118
|
+
pub fn directive_for(&self, origin: &str) -> Result<Directive, ConfigError> {
|
|
119
|
+
let mut directive = self.default_directive.clone();
|
|
120
|
+
if let Some(hit) = self.best_match_for(&ruby_dirname(origin))? {
|
|
121
|
+
for (name, options) in hit {
|
|
122
|
+
directive.insert(name.clone(), options.clone());
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
Ok(directive)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
fn best_match_for(&self, source_base_dir: &str) -> Result<Option<&Directive>, ConfigError> {
|
|
129
|
+
let mut best: Option<(&str, &Directive)> = None;
|
|
130
|
+
for (pathname, directive) in &self.directory_directives {
|
|
131
|
+
let matches = glob_matches(source_base_dir, pathname)? || glob_matches(source_base_dir, &expand_path(pathname))?;
|
|
132
|
+
if matches && best.is_none_or(|(best_path, _)| pathname.chars().count() > best_path.chars().count()) {
|
|
133
|
+
best = Some((pathname, directive));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
Ok(best.map(|(_, directive)| directive))
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/// `ConfigurationFileFinder.find`: `.reek.yml` in `current` or the nearest
|
|
141
|
+
/// directory above it, else in `home`.
|
|
142
|
+
pub fn find(current: &Path, home: Option<&Path>) -> Option<PathBuf> {
|
|
143
|
+
current.ancestors().chain(home).map(|dir| dir.join(DEFAULT_FILE_NAME)).find(|file| file.is_file())
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/// `ConfigurationFileFinder.load_from_file`: the file's values, validated
|
|
147
|
+
/// and with `/.../` strings in `accept`, `reject` and `exclude` turned into
|
|
148
|
+
/// patterns.
|
|
149
|
+
fn load_from_file(path: &Path) -> Result<IndexMap<String, Value>, ConfigError> {
|
|
150
|
+
let shown = path.to_string_lossy();
|
|
151
|
+
let invalid = |error: String| ConfigError::config_file(format!("Invalid configuration file {shown}, error is {error}"));
|
|
152
|
+
let configuration = load_yaml(path).map_err(&invalid)?;
|
|
153
|
+
validate(&configuration).map_err(invalid)?;
|
|
154
|
+
let Value::Hash(mut configuration) = configuration else {
|
|
155
|
+
unreachable!("validation accepts only a mapping or an empty file")
|
|
156
|
+
};
|
|
157
|
+
convert(&mut configuration)?;
|
|
158
|
+
Ok(configuration)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/// `YAML.load_file(path) || {}`.
|
|
162
|
+
fn load_yaml(path: &Path) -> Result<Value, String> {
|
|
163
|
+
let bytes = std::fs::read(path).map_err(|error| {
|
|
164
|
+
let reason = match error.kind() {
|
|
165
|
+
std::io::ErrorKind::NotFound => "No such file or directory".to_string(),
|
|
166
|
+
std::io::ErrorKind::PermissionDenied => "Permission denied".to_string(),
|
|
167
|
+
_ => error.to_string(),
|
|
168
|
+
};
|
|
169
|
+
format!("{reason} @ rb_sysopen - {}", path.to_string_lossy())
|
|
170
|
+
})?;
|
|
171
|
+
let bytes = bytes.strip_prefix("\u{feff}".as_bytes()).unwrap_or(&bytes);
|
|
172
|
+
let text = String::from_utf8_lossy(bytes);
|
|
173
|
+
match yaml::load_with_key_text(&text, false) {
|
|
174
|
+
Ok(None | Some(Value::Nil | Value::Bool(false))) => Ok(Value::Hash(IndexMap::new())),
|
|
175
|
+
Ok(Some(value)) => Ok(value),
|
|
176
|
+
Err(YamlError::Syntax(message)) => Err(format!("({}): {message}", path.to_string_lossy())),
|
|
177
|
+
Err(error) => Err(error.to_string()),
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ----------------------------------------------------------------------
|
|
182
|
+
// Validation (`SchemaValidator` with `Schema.schema(directories)`)
|
|
183
|
+
|
|
184
|
+
/// The type a schema key requires.
|
|
185
|
+
#[derive(Clone, Copy)]
|
|
186
|
+
enum Rule {
|
|
187
|
+
/// `filled(:bool)`.
|
|
188
|
+
Bool,
|
|
189
|
+
/// `filled(:integer)`.
|
|
190
|
+
Integer,
|
|
191
|
+
/// `array(:string)`.
|
|
192
|
+
Strings,
|
|
193
|
+
/// `array(:string) & filled?`.
|
|
194
|
+
FilledStrings,
|
|
195
|
+
/// `filled(:hash) { required(:initialize).filled(:hash) {
|
|
196
|
+
/// required(:max_params).filled(:integer) } }`.
|
|
197
|
+
Overrides,
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/// The keys `ALL_DETECTORS_SCHEMA` allows for a detector, in schema order.
|
|
201
|
+
fn detector_rules(smell_type: &str) -> Vec<(&'static str, Rule)> {
|
|
202
|
+
let mut rules = vec![("enabled", Rule::Bool), ("exclude", Rule::Strings)];
|
|
203
|
+
let extra: &[(&'static str, Rule)] = match smell_type {
|
|
204
|
+
"DataClump" => &[("max_copies", Rule::Integer), ("min_clump_size", Rule::Integer)],
|
|
205
|
+
"DuplicateMethodCall" => &[("max_calls", Rule::Integer), ("allow_calls", Rule::Strings)],
|
|
206
|
+
"LongParameterList" => &[("max_params", Rule::Integer), ("overrides", Rule::Overrides)],
|
|
207
|
+
"LongYieldList" => &[("max_params", Rule::Integer)],
|
|
208
|
+
"NestedIterators" => &[("max_allowed_nesting", Rule::Integer), ("ignore_iterators", Rule::FilledStrings)],
|
|
209
|
+
"RepeatedConditional" => &[("max_ifs", Rule::Integer)],
|
|
210
|
+
"TooManyConstants" => &[("max_constants", Rule::Integer)],
|
|
211
|
+
"TooManyInstanceVariables" => &[("max_instance_variables", Rule::Integer)],
|
|
212
|
+
"TooManyMethods" => &[("max_methods", Rule::Integer)],
|
|
213
|
+
"TooManyStatements" => &[("max_statements", Rule::Integer)],
|
|
214
|
+
"UncommunicativeMethodName"
|
|
215
|
+
| "UncommunicativeModuleName"
|
|
216
|
+
| "UncommunicativeParameterName"
|
|
217
|
+
| "UncommunicativeVariableName" => &[("reject", Rule::Strings), ("accept", Rule::Strings)],
|
|
218
|
+
"UtilityFunction" => &[("public_methods_only", Rule::Bool)],
|
|
219
|
+
_ => &[],
|
|
220
|
+
};
|
|
221
|
+
rules.extend_from_slice(extra);
|
|
222
|
+
rules
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/// One validation error: a path and dry-schema's text.
|
|
226
|
+
struct SchemaError {
|
|
227
|
+
path: Vec<String>,
|
|
228
|
+
text: &'static str,
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/// `SchemaValidator#validate`, including the lookups Reek makes first.
|
|
232
|
+
/// Returns the error text Reek wraps in a `ConfigFileError`.
|
|
233
|
+
fn validate(configuration: &Value) -> Result<(), String> {
|
|
234
|
+
let hash = match configuration {
|
|
235
|
+
Value::Hash(hash) => hash,
|
|
236
|
+
// `"text"['directories']` is a substring lookup.
|
|
237
|
+
Value::Str(text) if text.contains("directories") => {
|
|
238
|
+
return Err("undefined method `keys' for an instance of String".to_string());
|
|
239
|
+
}
|
|
240
|
+
Value::Str(_) => return Err("unrecognized configuration data".to_string()),
|
|
241
|
+
Value::Int(_) | Value::Array(_) => return Err("no implicit conversion of String into Integer".to_string()),
|
|
242
|
+
Value::Bool(true) => return Err("undefined method `[]' for true".to_string()),
|
|
243
|
+
other => return Err(format!("undefined method `[]' for an instance of {}", other.class_name())),
|
|
244
|
+
};
|
|
245
|
+
// `configuration['directories']&.keys`
|
|
246
|
+
let directories: Vec<String> = match hash.get("directories") {
|
|
247
|
+
None | Some(Value::Nil) => Vec::new(),
|
|
248
|
+
Some(Value::Hash(directories)) => directories.keys().cloned().collect(),
|
|
249
|
+
Some(other) => return Err(format!("undefined method `keys' for {}", ruby_receiver(other))),
|
|
250
|
+
};
|
|
251
|
+
let key_errors = unexpected_keys(hash, &directories);
|
|
252
|
+
let mut rule_errors = Vec::new();
|
|
253
|
+
rule_errors_for_root(hash, &directories, &mut rule_errors).map_err(|()| "unrecognized configuration data".to_string())?;
|
|
254
|
+
let rule_errors = rule_errors.into_iter().filter(|error| !is_hidden_by_key_errors(error, &key_errors));
|
|
255
|
+
let messages: Vec<String> = key_errors
|
|
256
|
+
.iter()
|
|
257
|
+
.chain(rule_errors.collect::<Vec<_>>().iter())
|
|
258
|
+
.map(|error| format!("[/{}] {}.", error.path.join("/"), error.text))
|
|
259
|
+
.collect();
|
|
260
|
+
if messages.is_empty() {
|
|
261
|
+
Ok(())
|
|
262
|
+
} else {
|
|
263
|
+
Err(format!("\n{}", messages.join("\n")))
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/// How Ruby names a receiver in `NoMethodError` messages.
|
|
268
|
+
fn ruby_receiver(value: &Value) -> String {
|
|
269
|
+
match value {
|
|
270
|
+
Value::Bool(value) => value.to_string(),
|
|
271
|
+
other => format!("an instance of {}", other.class_name()),
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/// dry-schema reports a rule error only when no unexpected key lies under
|
|
276
|
+
/// its path, and reports no rule errors inside a detectors section (the
|
|
277
|
+
/// `detectors` mapping or a directory's) when an unexpected key lies inside
|
|
278
|
+
/// any detectors section.
|
|
279
|
+
fn is_hidden_by_key_errors(error: &SchemaError, key_errors: &[SchemaError]) -> bool {
|
|
280
|
+
let under = |key_error: &SchemaError| {
|
|
281
|
+
key_error.path.len() > error.path.len() && key_error.path[..error.path.len()] == error.path[..]
|
|
282
|
+
};
|
|
283
|
+
let detectors_section_depth = |path: &[String]| match path.first().map(String::as_str) {
|
|
284
|
+
Some("detectors") => Some(1),
|
|
285
|
+
Some("directories") => Some(2),
|
|
286
|
+
_ => None,
|
|
287
|
+
};
|
|
288
|
+
let inside_detectors_section =
|
|
289
|
+
|path: &[String]| detectors_section_depth(path).is_some_and(|depth| path.len() > depth);
|
|
290
|
+
key_errors.iter().any(under)
|
|
291
|
+
|| (inside_detectors_section(&error.path) && key_errors.iter().any(|key_error| inside_detectors_section(&key_error.path)))
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/// `KeyValidator#call`: the paths of input keys the schema does not have,
|
|
295
|
+
/// in input order.
|
|
296
|
+
fn unexpected_keys(hash: &IndexMap<String, Value>, directories: &[String]) -> Vec<SchemaError> {
|
|
297
|
+
let mut key_paths = schema_key_paths(directories);
|
|
298
|
+
key_paths.sort();
|
|
299
|
+
let mut errors = Vec::new();
|
|
300
|
+
for path in input_key_paths(hash) {
|
|
301
|
+
if let Some(error_path) = validate_path(&key_paths, &path) {
|
|
302
|
+
errors.push(SchemaError { path: error_path, text: "is not allowed" });
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
errors
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/// `key_map.to_dot_notation`.
|
|
309
|
+
fn schema_key_paths(directories: &[String]) -> Vec<String> {
|
|
310
|
+
let mut detector_paths = Vec::new();
|
|
311
|
+
for detector in DETECTORS.iter() {
|
|
312
|
+
for (key, rule) in detector_rules(detector.smell_type) {
|
|
313
|
+
match rule {
|
|
314
|
+
Rule::Overrides => detector_paths.push(format!("{}.{key}.initialize.max_params", detector.smell_type)),
|
|
315
|
+
_ => detector_paths.push(format!("{}.{key}", detector.smell_type)),
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
let mut paths: Vec<String> = detector_paths.iter().map(|path| format!("detectors.{path}")).collect();
|
|
320
|
+
for directory in directories {
|
|
321
|
+
paths.extend(detector_paths.iter().map(|path| format!("directories.{directory}.{path}")));
|
|
322
|
+
}
|
|
323
|
+
paths.push("exclude_paths".to_string());
|
|
324
|
+
paths
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/// `KeyValidator#key_paths`: a dotted path for each leaf of the input; an
|
|
328
|
+
/// empty mapping or a sequence without mappings or sequences is a leaf, and
|
|
329
|
+
/// sequence items are `[index]`.
|
|
330
|
+
fn input_key_paths(hash: &IndexMap<String, Value>) -> Vec<String> {
|
|
331
|
+
let mut paths = Vec::new();
|
|
332
|
+
for (key, value) in hash {
|
|
333
|
+
match value {
|
|
334
|
+
Value::Hash(nested) if !nested.is_empty() => {
|
|
335
|
+
paths.extend(input_key_paths(nested).into_iter().map(|path| format!("{key}.{path}")));
|
|
336
|
+
}
|
|
337
|
+
Value::Array(items) if items.iter().any(is_nonempty_collection) => {
|
|
338
|
+
paths.extend(traverse_array(items).into_iter().map(|path| format!("{key}{path}")));
|
|
339
|
+
}
|
|
340
|
+
_ => paths.push(key.clone()),
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
paths
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
fn is_nonempty_collection(value: &Value) -> bool {
|
|
347
|
+
match value {
|
|
348
|
+
Value::Hash(hash) => !hash.is_empty(),
|
|
349
|
+
Value::Array(items) => !items.is_empty(),
|
|
350
|
+
_ => false,
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/// `KeyValidator#traverse_array`.
|
|
355
|
+
fn traverse_array(items: &[Value]) -> Vec<String> {
|
|
356
|
+
let mut paths = Vec::new();
|
|
357
|
+
for (index, item) in items.iter().enumerate() {
|
|
358
|
+
match item {
|
|
359
|
+
Value::Hash(hash) => {
|
|
360
|
+
paths.extend(input_key_paths(hash).into_iter().map(|path| format!("[{index}].{path}")));
|
|
361
|
+
}
|
|
362
|
+
Value::Array(nested) => {
|
|
363
|
+
paths.extend(traverse_array(nested).into_iter().map(|path| format!("[{index}]{path}")));
|
|
364
|
+
}
|
|
365
|
+
_ => {}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
paths
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/// `KeyValidator#validate_path`: the error path for an input path no
|
|
372
|
+
/// schema path matches, split into keys (and indexes).
|
|
373
|
+
fn validate_path(key_paths: &[String], path: &str) -> Option<Vec<String>> {
|
|
374
|
+
let index_pattern = RubyRegexp::new(r"\[\d+\]", "").expect("index pattern");
|
|
375
|
+
if index_pattern.is_match(path.as_bytes()) {
|
|
376
|
+
let key = index_pattern.replace_all(path, "[]");
|
|
377
|
+
// Consecutive indexes collapse into one `[]` in Ruby's pattern.
|
|
378
|
+
let multi_index = RubyRegexp::new(r"(\[\])+", "").expect("multi-index pattern");
|
|
379
|
+
let key = multi_index.replace_all(&key, "[]");
|
|
380
|
+
if any_key_paths_match(key_paths, &key) {
|
|
381
|
+
return None;
|
|
382
|
+
}
|
|
383
|
+
let dotted = RubyRegexp::new(r"\[(\d+)\]", "").expect("index pattern");
|
|
384
|
+
let mut out = String::new();
|
|
385
|
+
let mut last = 0;
|
|
386
|
+
for groups in dotted.scan(path.as_bytes()) {
|
|
387
|
+
let (start, end) = groups[0].expect("a match has a range");
|
|
388
|
+
let (digits_start, digits_end) = groups[1].expect("the index matched");
|
|
389
|
+
out.push_str(&path[last..start]);
|
|
390
|
+
out.push('.');
|
|
391
|
+
out.push_str(&path[digits_start..digits_end]);
|
|
392
|
+
last = end;
|
|
393
|
+
}
|
|
394
|
+
out.push_str(&path[last..]);
|
|
395
|
+
Some(out.split('.').map(str::to_string).collect())
|
|
396
|
+
} else if any_key_paths_match(key_paths, path) {
|
|
397
|
+
None
|
|
398
|
+
} else {
|
|
399
|
+
Some(path.split('.').map(str::to_string).collect())
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/// `any_key_paths_match?`: the path itself, or a path under it.
|
|
404
|
+
fn any_key_paths_match(key_paths: &[String], path: &str) -> bool {
|
|
405
|
+
find_path(key_paths, path, false)
|
|
406
|
+
|| find_path(key_paths, &format!("{path}."), true)
|
|
407
|
+
|| find_path(key_paths, &format!("{path}[]"), true)
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/// `find_path`: the first schema path not less than `path` equals it, or
|
|
411
|
+
/// starts with it.
|
|
412
|
+
fn find_path(key_paths: &[String], path: &str, prefix_match: bool) -> bool {
|
|
413
|
+
let index = key_paths.partition_point(|key_path| key_path.as_str() < path);
|
|
414
|
+
key_paths.get(index).is_some_and(|key| if prefix_match { key.starts_with(path) } else { key == path })
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/// The rule errors of the root schema, in schema order. `Err` when
|
|
418
|
+
/// dry-schema fails with `NoMethodError` (a detectors section that is not
|
|
419
|
+
/// a mapping), which Reek reports as unrecognized data.
|
|
420
|
+
fn rule_errors_for_root(hash: &IndexMap<String, Value>, directories: &[String], errors: &mut Vec<SchemaError>) -> Result<(), ()> {
|
|
421
|
+
if let Some(detectors) = hash.get("detectors") {
|
|
422
|
+
detectors_section(detectors, vec!["detectors".to_string()], errors)?;
|
|
423
|
+
}
|
|
424
|
+
if !directories.is_empty() {
|
|
425
|
+
if let Some(Value::Hash(directory_values)) = hash.get("directories") {
|
|
426
|
+
for directory in directories {
|
|
427
|
+
let path = vec!["directories".to_string(), directory.clone()];
|
|
428
|
+
detectors_section(&directory_values[directory], path, errors)?;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
if let Some(exclude_paths) = hash.get("exclude_paths") {
|
|
433
|
+
strings_rule(exclude_paths, &["exclude_paths".to_string()], errors);
|
|
434
|
+
}
|
|
435
|
+
Ok(())
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/// `filled(ALL_DETECTORS_SCHEMA)`.
|
|
439
|
+
fn detectors_section(value: &Value, path: Vec<String>, errors: &mut Vec<SchemaError>) -> Result<(), ()> {
|
|
440
|
+
if !is_filled(value) {
|
|
441
|
+
errors.push(SchemaError { path, text: "must be filled" });
|
|
442
|
+
return Ok(());
|
|
443
|
+
}
|
|
444
|
+
let Value::Hash(detectors) = value else { return Err(()) };
|
|
445
|
+
for detector in DETECTORS.iter() {
|
|
446
|
+
let Some(options) = detectors.get(detector.smell_type) else { continue };
|
|
447
|
+
let mut detector_path = path.clone();
|
|
448
|
+
detector_path.push(detector.smell_type.to_string());
|
|
449
|
+
if !is_filled(options) {
|
|
450
|
+
errors.push(SchemaError { path: detector_path, text: "must be filled" });
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
let Value::Hash(options) = options else {
|
|
454
|
+
errors.push(SchemaError { path: detector_path, text: "must be a hash" });
|
|
455
|
+
continue;
|
|
456
|
+
};
|
|
457
|
+
for (key, rule) in detector_rules(detector.smell_type) {
|
|
458
|
+
let Some(value) = options.get(key) else { continue };
|
|
459
|
+
let mut key_path = detector_path.clone();
|
|
460
|
+
key_path.push(key.to_string());
|
|
461
|
+
match rule {
|
|
462
|
+
Rule::Bool => filled_rule(value, &key_path, is_params_bool, "must be boolean", errors),
|
|
463
|
+
Rule::Integer => filled_rule(value, &key_path, is_params_integer, "must be an integer", errors),
|
|
464
|
+
Rule::Strings => strings_rule(value, &key_path, errors),
|
|
465
|
+
Rule::FilledStrings => {
|
|
466
|
+
if matches!(value, Value::Array(items) if items.is_empty()) {
|
|
467
|
+
errors.push(SchemaError { path: key_path, text: "must be filled" });
|
|
468
|
+
} else {
|
|
469
|
+
strings_rule(value, &key_path, errors);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
Rule::Overrides => overrides_rule(value, key_path, errors),
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
Ok(())
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/// `filled?`: not `nil`, and not an empty string, sequence or mapping.
|
|
480
|
+
fn is_filled(value: &Value) -> bool {
|
|
481
|
+
match value {
|
|
482
|
+
Value::Nil => false,
|
|
483
|
+
Value::Str(text) => !text.is_empty(),
|
|
484
|
+
Value::Array(items) => !items.is_empty(),
|
|
485
|
+
Value::Hash(hash) => !hash.is_empty(),
|
|
486
|
+
_ => true,
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/// `filled(type)`: filled, and of the type after Params coercion.
|
|
491
|
+
fn filled_rule(value: &Value, path: &[String], is_type: fn(&Value) -> bool, text: &'static str, errors: &mut Vec<SchemaError>) {
|
|
492
|
+
if !is_filled(value) {
|
|
493
|
+
errors.push(SchemaError { path: path.to_vec(), text: "must be filled" });
|
|
494
|
+
} else if !is_type(value) {
|
|
495
|
+
errors.push(SchemaError { path: path.to_vec(), text });
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/// `array(:string)`: a sequence (an empty string coerces to one) of
|
|
500
|
+
/// strings.
|
|
501
|
+
fn strings_rule(value: &Value, path: &[String], errors: &mut Vec<SchemaError>) {
|
|
502
|
+
match value {
|
|
503
|
+
Value::Array(items) => {
|
|
504
|
+
for (index, item) in items.iter().enumerate() {
|
|
505
|
+
if !matches!(item, Value::Str(_)) {
|
|
506
|
+
let mut item_path = path.to_vec();
|
|
507
|
+
item_path.push(index.to_string());
|
|
508
|
+
errors.push(SchemaError { path: item_path, text: "must be a string" });
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
Value::Str(text) if text.is_empty() => {}
|
|
513
|
+
_ => errors.push(SchemaError { path: path.to_vec(), text: "must be an array" }),
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/// `LongParameterList`'s `overrides`.
|
|
518
|
+
fn overrides_rule(value: &Value, path: Vec<String>, errors: &mut Vec<SchemaError>) {
|
|
519
|
+
if !is_filled(value) {
|
|
520
|
+
errors.push(SchemaError { path, text: "must be filled" });
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
let Value::Hash(overrides) = value else {
|
|
524
|
+
errors.push(SchemaError { path, text: "must be a hash" });
|
|
525
|
+
return;
|
|
526
|
+
};
|
|
527
|
+
let mut initialize_path = path;
|
|
528
|
+
initialize_path.push("initialize".to_string());
|
|
529
|
+
let Some(initialize) = overrides.get("initialize") else {
|
|
530
|
+
errors.push(SchemaError { path: initialize_path, text: "is missing" });
|
|
531
|
+
return;
|
|
532
|
+
};
|
|
533
|
+
if !is_filled(initialize) {
|
|
534
|
+
errors.push(SchemaError { path: initialize_path, text: "must be filled" });
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
let Value::Hash(initialize) = initialize else {
|
|
538
|
+
errors.push(SchemaError { path: initialize_path, text: "must be a hash" });
|
|
539
|
+
return;
|
|
540
|
+
};
|
|
541
|
+
let mut max_params_path = initialize_path;
|
|
542
|
+
max_params_path.push("max_params".to_string());
|
|
543
|
+
match initialize.get("max_params") {
|
|
544
|
+
None => errors.push(SchemaError { path: max_params_path, text: "is missing" }),
|
|
545
|
+
Some(max_params) => filled_rule(max_params, &max_params_path, is_params_integer, "must be an integer", errors),
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/// dry-types' Params boolean coercion accepts these.
|
|
550
|
+
fn is_params_bool(value: &Value) -> bool {
|
|
551
|
+
const BOOLEAN_STRINGS: [&str; 28] = [
|
|
552
|
+
"1", "on", "On", "ON", "t", "true", "True", "TRUE", "T", "y", "yes", "Yes", "YES", "Y", "0", "off", "Off",
|
|
553
|
+
"OFF", "f", "false", "False", "FALSE", "F", "n", "no", "No", "NO", "N",
|
|
554
|
+
];
|
|
555
|
+
match value {
|
|
556
|
+
Value::Bool(_) => true,
|
|
557
|
+
Value::Int(number) => *number == 0 || *number == 1,
|
|
558
|
+
Value::Str(text) => BOOLEAN_STRINGS.contains(&text.as_str()),
|
|
559
|
+
_ => false,
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/// dry-types' Params integer coercion (`Integer(value, 10)` for strings,
|
|
564
|
+
/// truncation for finite floats) accepts these.
|
|
565
|
+
fn is_params_integer(value: &Value) -> bool {
|
|
566
|
+
match value {
|
|
567
|
+
Value::Int(_) => true,
|
|
568
|
+
Value::Float(number) => number.is_finite(),
|
|
569
|
+
Value::Str(text) => is_base_10_integer(text),
|
|
570
|
+
_ => false,
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/// `Integer(text, 10)` succeeds: optional whitespace around an optional
|
|
575
|
+
/// sign and digits, with single underscores between digits.
|
|
576
|
+
fn is_base_10_integer(text: &str) -> bool {
|
|
577
|
+
let trimmed = text.trim_matches(|c: char| matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r'));
|
|
578
|
+
let digits = trimmed.strip_prefix(['+', '-']).unwrap_or(trimmed);
|
|
579
|
+
!digits.is_empty()
|
|
580
|
+
&& !digits.starts_with('_')
|
|
581
|
+
&& !digits.ends_with('_')
|
|
582
|
+
&& !digits.contains("__")
|
|
583
|
+
&& digits.chars().all(|c| c.is_ascii_digit() || c == '_')
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// ----------------------------------------------------------------------
|
|
587
|
+
// Conversion and directory matching
|
|
588
|
+
|
|
589
|
+
/// `ConfigurationConverter#convert`: in each detector's `accept`, `reject`
|
|
590
|
+
/// and `exclude`, a string between slashes becomes a pattern.
|
|
591
|
+
fn convert(configuration: &mut IndexMap<String, Value>) -> Result<(), ConfigError> {
|
|
592
|
+
if let Some(Value::Hash(detectors)) = configuration.get_mut("detectors") {
|
|
593
|
+
for options in detectors.values_mut() {
|
|
594
|
+
convert_detector(options)?;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
if let Some(Value::Hash(directories)) = configuration.get_mut("directories") {
|
|
598
|
+
for detectors in directories.values_mut() {
|
|
599
|
+
let Value::Hash(detectors) = detectors else { continue };
|
|
600
|
+
for options in detectors.values_mut() {
|
|
601
|
+
convert_detector(options)?;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
Ok(())
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
fn convert_detector(options: &mut Value) -> Result<(), ConfigError> {
|
|
609
|
+
let Value::Hash(options) = options else { return Ok(()) };
|
|
610
|
+
for (key, value) in options.iter_mut() {
|
|
611
|
+
if !matches!(key.as_str(), "accept" | "reject" | "exclude") {
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
let Value::Array(items) = value else { continue };
|
|
615
|
+
for item in items.iter_mut() {
|
|
616
|
+
let Value::Str(text) = item else { continue };
|
|
617
|
+
if text.starts_with('/') && text.ends_with('/') {
|
|
618
|
+
let source = if text.len() >= 2 { &text[1..text.len() - 1] } else { "" };
|
|
619
|
+
let regexp = RubyRegexp::new(source, "")
|
|
620
|
+
.map_err(|message| ConfigError { class: "RegexpError", message: format!("{message}: /{source}/") })?;
|
|
621
|
+
*item = Value::Regexp(regexp);
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
Ok(())
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/// `DirectoryDirectives#match?`: the directory matches the pattern
|
|
629
|
+
/// (`glob_to_regexp`), ignoring case.
|
|
630
|
+
fn glob_matches(source_base_dir: &str, glob: &str) -> Result<bool, ConfigError> {
|
|
631
|
+
let regexp = if glob.contains('*') {
|
|
632
|
+
let eol_wildcards = RubyRegexp::new(r"/\*\*$", "").expect("glob pattern");
|
|
633
|
+
eol_wildcards
|
|
634
|
+
.replace_all(glob, "<<to_eol_wildcards>>")
|
|
635
|
+
.replace("**", "<<to_wildcards>>")
|
|
636
|
+
.replace('*', "[^/]*")
|
|
637
|
+
.replace('.', "\\.")
|
|
638
|
+
.replace("<<to_eol_wildcards>>", ".*")
|
|
639
|
+
.replace("<<to_wildcards>>", ".*")
|
|
640
|
+
} else {
|
|
641
|
+
format!("{glob}.*")
|
|
642
|
+
};
|
|
643
|
+
let pattern = RubyRegexp::new(&format!("^{regexp}$"), "i")
|
|
644
|
+
.map_err(|message| ConfigError { class: "RegexpError", message: format!("{message}: /^{regexp}$/") })?;
|
|
645
|
+
Ok(pattern.is_match(source_base_dir.as_bytes()))
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/// `File.dirname(path)`.
|
|
649
|
+
pub fn ruby_dirname(path: &str) -> String {
|
|
650
|
+
let trimmed = path.trim_end_matches('/');
|
|
651
|
+
if trimmed.is_empty() {
|
|
652
|
+
return if path.starts_with('/') { "/".to_string() } else { ".".to_string() };
|
|
653
|
+
}
|
|
654
|
+
match trimmed.rfind('/') {
|
|
655
|
+
None => ".".to_string(),
|
|
656
|
+
Some(index) => {
|
|
657
|
+
let parent = trimmed[..index].trim_end_matches('/');
|
|
658
|
+
if parent.is_empty() { "/".to_string() } else { parent.to_string() }
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/// `File.expand_path(path)`: absolute, from the current directory (or the
|
|
664
|
+
/// home directory for `~`), without `.` and `..` segments.
|
|
665
|
+
pub fn expand_path(path: &str) -> String {
|
|
666
|
+
let home = std::env::var("HOME").unwrap_or_default();
|
|
667
|
+
let absolute = if path == "~" || path.starts_with("~/") {
|
|
668
|
+
format!("{home}{}", &path[1..])
|
|
669
|
+
} else if path.starts_with('/') {
|
|
670
|
+
path.to_string()
|
|
671
|
+
} else {
|
|
672
|
+
let current = std::env::current_dir().map(|dir| dir.to_string_lossy().into_owned()).unwrap_or_default();
|
|
673
|
+
format!("{current}/{path}")
|
|
674
|
+
};
|
|
675
|
+
let mut segments: Vec<&str> = Vec::new();
|
|
676
|
+
for segment in absolute.split('/') {
|
|
677
|
+
match segment {
|
|
678
|
+
"" | "." => {}
|
|
679
|
+
".." => {
|
|
680
|
+
segments.pop();
|
|
681
|
+
}
|
|
682
|
+
other => segments.push(other),
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
format!("/{}", segments.join("/"))
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
#[cfg(test)]
|
|
689
|
+
mod tests {
|
|
690
|
+
use super::*;
|
|
691
|
+
|
|
692
|
+
fn load(text: &str) -> Result<AppConfiguration, ConfigError> {
|
|
693
|
+
let directory = std::env::temp_dir().join(format!("reek-rs-config-{}", std::process::id()));
|
|
694
|
+
std::fs::create_dir_all(&directory).unwrap();
|
|
695
|
+
let path = directory.join(format!("{:x}.yml", text.len() * 31 + text.bytes().map(usize::from).sum::<usize>()));
|
|
696
|
+
std::fs::write(&path, text).unwrap();
|
|
697
|
+
let result = AppConfiguration::from_path(&path).map_err(|error| ConfigError {
|
|
698
|
+
message: error.message.replace(&path.to_string_lossy().into_owned(), ".reek.yml"),
|
|
699
|
+
..error
|
|
700
|
+
});
|
|
701
|
+
std::fs::remove_file(&path).unwrap();
|
|
702
|
+
result
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
fn error(text: &str) -> String {
|
|
706
|
+
match load(text) {
|
|
707
|
+
Ok(_) => "ok".to_string(),
|
|
708
|
+
Err(error) => error.message.trim_start_matches("Invalid configuration file .reek.yml, error is ").to_string(),
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
#[test]
|
|
713
|
+
fn validation_errors_match_reek() {
|
|
714
|
+
let cases = [
|
|
715
|
+
("", "ok"),
|
|
716
|
+
("foo", "unrecognized configuration data"),
|
|
717
|
+
("- a\n- b", "no implicit conversion of String into Integer"),
|
|
718
|
+
("foo: 1", "\n[/foo] is not allowed."),
|
|
719
|
+
("detectors: 1", "unrecognized configuration data"),
|
|
720
|
+
("detectors:", "\n[/detectors] must be filled."),
|
|
721
|
+
("detectors:\n Foo:\n enabled: false", "\n[/detectors/Foo/enabled] is not allowed."),
|
|
722
|
+
("detectors:\n FeatureEnvy: 1", "\n[/detectors/FeatureEnvy] must be a hash."),
|
|
723
|
+
("detectors:\n FeatureEnvy: {}", "\n[/detectors/FeatureEnvy] must be filled."),
|
|
724
|
+
("detectors:\n FeatureEnvy:\n enabled: 1", "ok"),
|
|
725
|
+
("detectors:\n FeatureEnvy:\n enabled: 'true'", "ok"),
|
|
726
|
+
("detectors:\n FeatureEnvy:\n max: 1", "\n[/detectors/FeatureEnvy/max] is not allowed."),
|
|
727
|
+
("detectors:\n FeatureEnvy:\n exclude: foo", "\n[/detectors/FeatureEnvy/exclude] must be an array."),
|
|
728
|
+
("detectors:\n FeatureEnvy:\n exclude: [1]", "\n[/detectors/FeatureEnvy/exclude/0] must be a string."),
|
|
729
|
+
("detectors:\n TooManyStatements:\n max_statements: '10'", "ok"),
|
|
730
|
+
("detectors:\n TooManyStatements:\n max_statements: 1.5", "ok"),
|
|
731
|
+
("detectors:\n TooManyStatements:\n max_statements:", "\n[/detectors/TooManyStatements/max_statements] must be filled."),
|
|
732
|
+
(
|
|
733
|
+
"detectors:\n LongParameterList:\n overrides:\n foo:\n max_params: 2",
|
|
734
|
+
"\n[/detectors/LongParameterList/overrides/foo/max_params] is not allowed.",
|
|
735
|
+
),
|
|
736
|
+
("detectors:\n LongParameterList:\n overrides: {}", "\n[/detectors/LongParameterList/overrides] must be filled."),
|
|
737
|
+
("detectors:\n NestedIterators:\n ignore_iterators: []", "\n[/detectors/NestedIterators/ignore_iterators] must be filled."),
|
|
738
|
+
("directories:\n \"app/x\":\n Foo:\n enabled: false", "\n[/directories/app/x/Foo/enabled] is not allowed."),
|
|
739
|
+
("directories:\n \"app/x\":", "\n[/directories/app/x] must be filled."),
|
|
740
|
+
("exclude_paths: foo", "\n[/exclude_paths] must be an array."),
|
|
741
|
+
(
|
|
742
|
+
"detectors:\n FeatureEnvy:\n enabled: 1\n max: 2\nfoo: 3",
|
|
743
|
+
"\n[/detectors/FeatureEnvy/max] is not allowed.\n[/foo] is not allowed.",
|
|
744
|
+
),
|
|
745
|
+
("a: &x 1\nb: *x", "Alias parsing was not enabled. To enable it, pass `aliases: true` to `Psych::load` or `Psych::safe_load`."),
|
|
746
|
+
("1: 2", "\n[/1] is not allowed."),
|
|
747
|
+
(
|
|
748
|
+
"foo: 1\ndetectors:\n FeatureEnvy:\n enabled: foo",
|
|
749
|
+
"\n[/foo] is not allowed.\n[/detectors/FeatureEnvy/enabled] must be boolean.",
|
|
750
|
+
),
|
|
751
|
+
("detectors:\n Foo: {}", "\n[/detectors/Foo] is not allowed."),
|
|
752
|
+
("foo:\n - a: 1\n - b: 2", "\n[/foo/0/a] is not allowed.\n[/foo/1/b] is not allowed."),
|
|
753
|
+
("foo: [1, 2]", "\n[/foo] is not allowed."),
|
|
754
|
+
("detectors:\n FeatureEnvy:\n enabled: 2", "\n[/detectors/FeatureEnvy/enabled] must be boolean."),
|
|
755
|
+
("detectors:\n TooManyStatements:\n max_statements: x", "\n[/detectors/TooManyStatements/max_statements] must be an integer."),
|
|
756
|
+
("detectors:\n TooManyStatements:\n max_statements: ''", "\n[/detectors/TooManyStatements/max_statements] must be filled."),
|
|
757
|
+
(
|
|
758
|
+
"detectors:\n FeatureEnvy:\n exclude: [~, 1, a]",
|
|
759
|
+
"\n[/detectors/FeatureEnvy/exclude/0] must be a string.\n[/detectors/FeatureEnvy/exclude/1] must be a string.",
|
|
760
|
+
),
|
|
761
|
+
("detectors:\n FeatureEnvy:\n exclude: {a: 1}", "\n[/detectors/FeatureEnvy/exclude/a] is not allowed."),
|
|
762
|
+
("detectors:\n LongParameterList:\n overrides: x", "\n[/detectors/LongParameterList/overrides] must be a hash."),
|
|
763
|
+
("directories: 1", "undefined method `keys' for an instance of Integer"),
|
|
764
|
+
("directories: {}", "\n[/directories] is not allowed."),
|
|
765
|
+
("directories:\n x: 1", "unrecognized configuration data"),
|
|
766
|
+
(
|
|
767
|
+
"detectors:\n NilCheck:\n enabled: x\n FeatureEnvy:\n exclude: 1",
|
|
768
|
+
"\n[/detectors/FeatureEnvy/exclude] must be an array.\n[/detectors/NilCheck/enabled] must be boolean.",
|
|
769
|
+
),
|
|
770
|
+
("---\na: 1\n---\nb: 2\n", "\n[/a] is not allowed."),
|
|
771
|
+
("detectors:\n 1.5: x", "\n[/detectors/1/5] is not allowed."),
|
|
772
|
+
("false", "ok"),
|
|
773
|
+
("~", "ok"),
|
|
774
|
+
("5", "no implicit conversion of String into Integer"),
|
|
775
|
+
("detectors:\n Foo: 1\nexclude_paths: x", "\n[/detectors/Foo] is not allowed.\n[/exclude_paths] must be an array."),
|
|
776
|
+
("detectors:\n FeatureEnvy:\n enabled: x\n foo: 1", "\n[/detectors/FeatureEnvy/foo] is not allowed."),
|
|
777
|
+
];
|
|
778
|
+
for (text, expected) in cases {
|
|
779
|
+
assert_eq!(error(text), expected, "{text:?}");
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
#[test]
|
|
784
|
+
fn directives_merge_directories_over_detectors() {
|
|
785
|
+
let configuration = load(
|
|
786
|
+
"detectors:\n FeatureEnvy:\n enabled: false\n NilCheck:\n enabled: false\n\
|
|
787
|
+
directories:\n \"lib/\":\n NilCheck:\n exclude: ['/a/']\n",
|
|
788
|
+
)
|
|
789
|
+
.unwrap();
|
|
790
|
+
let directive = configuration.directive_for("lib/x.rb").unwrap();
|
|
791
|
+
assert_eq!(Value::Hash(directive["FeatureEnvy"].clone()).inspect(), r#"{"enabled"=>false}"#);
|
|
792
|
+
assert_eq!(Value::Hash(directive["NilCheck"].clone()).inspect(), r#"{"exclude"=>[/a/]}"#);
|
|
793
|
+
let directive = configuration.directive_for("app/x.rb").unwrap();
|
|
794
|
+
assert_eq!(Value::Hash(directive["NilCheck"].clone()).inspect(), r#"{"enabled"=>false}"#);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
#[test]
|
|
798
|
+
fn dirname_matches_ruby() {
|
|
799
|
+
for (path, expected) in [("a/b/c.rb", "a/b"), ("c.rb", "."), ("/c.rb", "/"), ("a//b.rb", "a"), ("a/b/", "a"), ("/", "/")] {
|
|
800
|
+
assert_eq!(ruby_dirname(path), expected, "{path}");
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
}
|