forked from astral-sh/ruff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.rs
658 lines (585 loc) · 17.2 KB
/
types.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use anyhow::{bail, Result};
use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};
use pep440_rs::{Version as Pep440Version, VersionSpecifier, VersionSpecifiers};
use rustc_hash::FxHashMap;
use serde::{de, Deserialize, Deserializer, Serialize};
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
use ruff_cache::{CacheKey, CacheKeyHasher};
use ruff_diagnostics::Applicability;
use ruff_macros::CacheKey;
use ruff_python_ast::PySourceType;
use crate::registry::RuleSet;
use crate::rule_selector::RuleSelector;
use crate::{display_settings, fs};
#[derive(
Clone,
Copy,
Debug,
PartialOrd,
Ord,
PartialEq,
Eq,
Default,
Serialize,
Deserialize,
CacheKey,
EnumIter,
)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum PythonVersion {
Py37,
// Make sure to also change the default for `ruff_python_formatter::PythonVersion`
// when changing the default here.
#[default]
Py38,
Py39,
Py310,
Py311,
Py312,
}
impl From<PythonVersion> for Pep440Version {
fn from(version: PythonVersion) -> Self {
let (major, minor) = version.as_tuple();
Self::from_str(&format!("{major}.{minor}.100")).unwrap()
}
}
impl PythonVersion {
/// Return the latest supported Python version.
pub const fn latest() -> Self {
Self::Py312
}
pub const fn as_tuple(&self) -> (u8, u8) {
match self {
Self::Py37 => (3, 7),
Self::Py38 => (3, 8),
Self::Py39 => (3, 9),
Self::Py310 => (3, 10),
Self::Py311 => (3, 11),
Self::Py312 => (3, 12),
}
}
pub const fn major(&self) -> u8 {
self.as_tuple().0
}
pub const fn minor(&self) -> u8 {
self.as_tuple().1
}
pub fn get_minimum_supported_version(requires_version: &VersionSpecifiers) -> Option<Self> {
let mut minimum_version = None;
for python_version in PythonVersion::iter() {
if requires_version
.iter()
.all(|specifier| specifier.contains(&python_version.into()))
{
minimum_version = Some(python_version);
break;
}
}
minimum_version
}
/// Return `true` if the current version supports [PEP 701].
///
/// [PEP 701]: https://peps.python.org/pep-0701/
pub fn supports_pep701(self) -> bool {
self >= Self::Py312
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, CacheKey, is_macro::Is)]
pub enum PreviewMode {
#[default]
Disabled,
Enabled,
}
impl From<bool> for PreviewMode {
fn from(version: bool) -> Self {
if version {
PreviewMode::Enabled
} else {
PreviewMode::Disabled
}
}
}
impl Display for PreviewMode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Disabled => write!(f, "disabled"),
Self::Enabled => write!(f, "enabled"),
}
}
}
/// Toggle for unsafe fixes.
/// `Hint` will not apply unsafe fixes but a message will be shown when they are available.
/// `Disabled` will not apply unsafe fixes or show a message.
/// `Enabled` will apply unsafe fixes.
#[derive(Debug, Copy, Clone, CacheKey, Default, PartialEq, Eq, is_macro::Is)]
pub enum UnsafeFixes {
#[default]
Hint,
Disabled,
Enabled,
}
impl Display for UnsafeFixes {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::Hint => "hint",
Self::Disabled => "disabled",
Self::Enabled => "enabled",
}
)
}
}
impl From<bool> for UnsafeFixes {
fn from(value: bool) -> Self {
if value {
UnsafeFixes::Enabled
} else {
UnsafeFixes::Disabled
}
}
}
impl UnsafeFixes {
pub fn required_applicability(&self) -> Applicability {
match self {
Self::Enabled => Applicability::Unsafe,
Self::Disabled | Self::Hint => Applicability::Safe,
}
}
}
#[derive(Debug, Clone, CacheKey, PartialEq, PartialOrd, Eq, Ord)]
pub enum FilePattern {
Builtin(&'static str),
User(String, PathBuf),
}
impl FilePattern {
pub fn add_to(self, builder: &mut GlobSetBuilder) -> Result<()> {
match self {
FilePattern::Builtin(pattern) => {
builder.add(Glob::from_str(pattern)?);
}
FilePattern::User(pattern, absolute) => {
// Add the absolute path.
builder.add(Glob::new(&absolute.to_string_lossy())?);
// Add basename path.
if !pattern.contains(std::path::MAIN_SEPARATOR) {
builder.add(Glob::new(&pattern)?);
}
}
}
Ok(())
}
}
impl Display for FilePattern {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{:?}",
match self {
Self::Builtin(pattern) => pattern,
Self::User(pattern, _) => pattern.as_str(),
}
)
}
}
impl FromStr for FilePattern {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let pattern = s.to_string();
let absolute = fs::normalize_path(&pattern);
Ok(Self::User(pattern, absolute))
}
}
#[derive(Debug, Clone, Default)]
pub struct FilePatternSet {
set: GlobSet,
cache_key: u64,
// This field is only for displaying the internals
// of `set`.
#[allow(clippy::used_underscore_binding)]
_set_internals: Vec<FilePattern>,
}
impl FilePatternSet {
#[allow(clippy::used_underscore_binding)]
pub fn try_from_iter<I>(patterns: I) -> Result<Self, anyhow::Error>
where
I: IntoIterator<Item = FilePattern>,
{
let mut builder = GlobSetBuilder::new();
let mut hasher = CacheKeyHasher::new();
let mut _set_internals = vec![];
for pattern in patterns {
_set_internals.push(pattern.clone());
pattern.cache_key(&mut hasher);
pattern.add_to(&mut builder)?;
}
let set = builder.build()?;
Ok(FilePatternSet {
set,
cache_key: hasher.finish(),
_set_internals,
})
}
}
impl Display for FilePatternSet {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self._set_internals.is_empty() {
write!(f, "[]")?;
} else {
writeln!(f, "[")?;
for pattern in &self._set_internals {
writeln!(f, "\t{pattern},")?;
}
write!(f, "]")?;
}
Ok(())
}
}
impl Deref for FilePatternSet {
type Target = GlobSet;
fn deref(&self) -> &Self::Target {
&self.set
}
}
impl CacheKey for FilePatternSet {
fn cache_key(&self, state: &mut CacheKeyHasher) {
state.write_usize(self.set.len());
state.write_u64(self.cache_key);
}
}
#[derive(Debug, Clone)]
pub struct PerFileIgnore {
pub(crate) basename: String,
pub(crate) absolute: PathBuf,
pub(crate) negated: bool,
pub(crate) rules: RuleSet,
}
impl PerFileIgnore {
pub fn new(
mut pattern: String,
prefixes: &[RuleSelector],
project_root: Option<&Path>,
) -> Self {
// Rules in preview are included here even if preview mode is disabled; it's safe to ignore disabled rules
let rules: RuleSet = prefixes.iter().flat_map(RuleSelector::all_rules).collect();
let negated = pattern.starts_with('!');
if negated {
pattern.drain(..1);
}
let path = Path::new(&pattern);
let absolute = match project_root {
Some(project_root) => fs::normalize_path_to(path, project_root),
None => fs::normalize_path(path),
};
Self {
basename: pattern,
absolute,
negated,
rules,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PatternPrefixPair {
pub pattern: String,
pub prefix: RuleSelector,
}
impl PatternPrefixPair {
const EXPECTED_PATTERN: &'static str = "<FilePattern>:<RuleCode> pattern";
}
impl<'de> Deserialize<'de> for PatternPrefixPair {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let str_result = String::deserialize(deserializer)?;
Self::from_str(str_result.as_str()).map_err(|_| {
de::Error::invalid_value(
de::Unexpected::Str(str_result.as_str()),
&Self::EXPECTED_PATTERN,
)
})
}
}
impl FromStr for PatternPrefixPair {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (pattern_str, code_string) = {
let tokens = s.split(':').collect::<Vec<_>>();
if tokens.len() != 2 {
bail!("Expected {}", Self::EXPECTED_PATTERN);
}
(tokens[0].trim(), tokens[1].trim())
};
let pattern = pattern_str.into();
let prefix = RuleSelector::from_str(code_string)?;
Ok(Self { pattern, prefix })
}
}
#[derive(
Clone,
Copy,
Debug,
PartialOrd,
Ord,
PartialEq,
Eq,
Default,
Serialize,
Deserialize,
CacheKey,
EnumIter,
)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum Language {
#[default]
Python,
Pyi,
Ipynb,
}
impl FromStr for Language {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"python" => Ok(Self::Python),
"pyi" => Ok(Self::Pyi),
"ipynb" => Ok(Self::Ipynb),
_ => {
bail!("Unrecognized language: `{s}`. Expected one of `python`, `pyi`, or `ipynb`.")
}
}
}
}
impl From<Language> for PySourceType {
fn from(value: Language) -> Self {
match value {
Language::Python => Self::Python,
Language::Ipynb => Self::Ipynb,
Language::Pyi => Self::Stub,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExtensionPair {
pub extension: String,
pub language: Language,
}
impl ExtensionPair {
const EXPECTED_PATTERN: &'static str = "<Extension>:<LanguageCode> pattern";
}
impl FromStr for ExtensionPair {
type Err = anyhow::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
let (extension_str, language_str) = {
let tokens = s.split(':').collect::<Vec<_>>();
if tokens.len() != 2 {
bail!("Expected {}", Self::EXPECTED_PATTERN);
}
(tokens[0].trim(), tokens[1].trim())
};
let extension = extension_str.into();
let language = Language::from_str(language_str)?;
Ok(Self {
extension,
language,
})
}
}
impl From<ExtensionPair> for (String, Language) {
fn from(value: ExtensionPair) -> Self {
(value.extension, value.language)
}
}
#[derive(Debug, Clone, Default, CacheKey)]
pub struct ExtensionMapping {
mapping: FxHashMap<String, Language>,
}
impl ExtensionMapping {
/// Return the [`Language`] for the given file.
pub fn get(&self, path: &Path) -> Option<Language> {
let ext = path.extension()?.to_str()?;
self.mapping.get(ext).copied()
}
}
impl Display for ExtensionMapping {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.extension",
fields = [
self.mapping | debug
]
}
Ok(())
}
}
impl From<FxHashMap<String, Language>> for ExtensionMapping {
fn from(value: FxHashMap<String, Language>) -> Self {
Self { mapping: value }
}
}
impl FromIterator<ExtensionPair> for ExtensionMapping {
fn from_iter<T: IntoIterator<Item = ExtensionPair>>(iter: T) -> Self {
Self {
mapping: iter
.into_iter()
.map(|pair| (pair.extension, pair.language))
.collect(),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Debug, Hash)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum SerializationFormat {
Text,
Concise,
Full,
Json,
JsonLines,
Junit,
Grouped,
Github,
Gitlab,
Pylint,
Azure,
Sarif,
}
impl Display for SerializationFormat {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Text => write!(f, "text"),
Self::Concise => write!(f, "concise"),
Self::Full => write!(f, "full"),
Self::Json => write!(f, "json"),
Self::JsonLines => write!(f, "json_lines"),
Self::Junit => write!(f, "junit"),
Self::Grouped => write!(f, "grouped"),
Self::Github => write!(f, "github"),
Self::Gitlab => write!(f, "gitlab"),
Self::Pylint => write!(f, "pylint"),
Self::Azure => write!(f, "azure"),
Self::Sarif => write!(f, "sarif"),
}
}
}
impl SerializationFormat {
pub fn default(preview: bool) -> Self {
if preview {
Self::Full
} else {
Self::Concise
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)]
#[serde(try_from = "String")]
pub struct RequiredVersion(VersionSpecifiers);
impl TryFrom<String> for RequiredVersion {
type Error = pep440_rs::VersionSpecifiersParseError;
fn try_from(value: String) -> Result<Self, Self::Error> {
// Treat `0.3.1` as `==0.3.1`, for backwards compatibility.
if let Ok(version) = pep440_rs::Version::from_str(&value) {
Ok(Self(VersionSpecifiers::from(
VersionSpecifier::equals_version(version),
)))
} else {
Ok(Self(VersionSpecifiers::from_str(&value)?))
}
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for RequiredVersion {
fn schema_name() -> String {
"RequiredVersion".to_string()
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
gen.subschema_for::<String>()
}
}
impl RequiredVersion {
/// Return `true` if the given version is required.
pub fn contains(&self, version: &pep440_rs::Version) -> bool {
self.0.contains(version)
}
}
impl Display for RequiredVersion {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.0, f)
}
}
/// Pattern to match an identifier.
///
/// # Notes
///
/// [`glob::Pattern`] matches a little differently than we ideally want to.
/// Specifically it uses `**` to match an arbitrary number of subdirectories,
/// luckily this not relevant since identifiers don't contains slashes.
///
/// For reference pep8-naming uses
/// [`fnmatch`](https://docs.python.org/3/library/fnmatch.html) for
/// pattern matching.
pub type IdentifierPattern = glob::Pattern;
#[derive(Debug, Clone, CacheKey, Default)]
pub struct PerFileIgnores {
// Ordered as (absolute path matcher, basename matcher, rules)
ignores: Vec<(GlobMatcher, GlobMatcher, bool, RuleSet)>,
}
impl PerFileIgnores {
/// Given a list of patterns, create a `GlobSet`.
pub fn resolve(per_file_ignores: Vec<PerFileIgnore>) -> Result<Self> {
let ignores: Result<Vec<_>> = per_file_ignores
.into_iter()
.map(|per_file_ignore| {
// Construct absolute path matcher.
let absolute =
Glob::new(&per_file_ignore.absolute.to_string_lossy())?.compile_matcher();
// Construct basename matcher.
let basename = Glob::new(&per_file_ignore.basename)?.compile_matcher();
Ok((
absolute,
basename,
per_file_ignore.negated,
per_file_ignore.rules,
))
})
.collect();
Ok(Self { ignores: ignores? })
}
}
impl Display for PerFileIgnores {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.is_empty() {
write!(f, "{{}}")?;
} else {
writeln!(f, "{{")?;
for (absolute, basename, negated, rules) in &self.ignores {
writeln!(
f,
"\t{{ absolute = {absolute:#?}, basename = {basename:#?}, negated = {negated:#?}, rules = {rules} }},"
)?;
}
write!(f, "}}")?;
}
Ok(())
}
}
impl Deref for PerFileIgnores {
type Target = Vec<(GlobMatcher, GlobMatcher, bool, RuleSet)>;
fn deref(&self) -> &Self::Target {
&self.ignores
}
}