Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented flake8-django plugin rules #2586

Merged
merged 18 commits into from
Feb 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ This README is also available as [documentation](https://beta.ruff.rs/docs/).
1. [flake8-comprehensions (C4)](#flake8-comprehensions-c4)
1. [flake8-datetimez (DTZ)](#flake8-datetimez-dtz)
1. [flake8-debugger (T10)](#flake8-debugger-t10)
1. [flake8-django (DJ)](#flake8-django-dj)
1. [flake8-errmsg (EM)](#flake8-errmsg-em)
1. [flake8-executable (EXE)](#flake8-executable-exe)
1. [flake8-implicit-str-concat (ISC)](#flake8-implicit-str-concat-isc)
Expand Down Expand Up @@ -1077,6 +1078,16 @@ For more, see [flake8-debugger](https://pypi.org/project/flake8-debugger/) on Py
| ---- | ---- | ------- | --- |
| T100 | debugger | Trace found: `{name}` used | |

### flake8-django (DJ)

For more, see [flake8-django](https://pypi.org/project/flake8-django/) on PyPI.

| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| DJ001 | [model-string-field-nullable](https://github.com/charliermarsh/ruff/blob/main/docs/rules/model-string-field-nullable.md) | Avoid using `null=True` on string-based fields such as {field_name} | |
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Controversially, I renamed these to add a leading zero. It deviates from upstream, but it's much more consistent with the other plugins.

| DJ008 | [model-dunder-str](https://github.com/charliermarsh/ruff/blob/main/docs/rules/model-dunder-str.md) | Model does not define `__str__` method | |
| DJ013 | [receiver-decorator-checker](https://github.com/charliermarsh/ruff/blob/main/docs/rules/receiver-decorator-checker.md) | `@receiver` decorator must be on top of all the other decorators | |

### flake8-errmsg (EM)

For more, see [flake8-errmsg](https://pypi.org/project/flake8-errmsg/) on PyPI.
Expand Down Expand Up @@ -1722,6 +1733,7 @@ natively, including:
* [flake8-comprehensions](https://pypi.org/project/flake8-comprehensions/)
* [flake8-datetimez](https://pypi.org/project/flake8-datetimez/)
* [flake8-debugger](https://pypi.org/project/flake8-debugger/)
* [flake8-django](https://pypi.org/project/flake8-django/) ([#2817](https://github.com/charliermarsh/ruff/issues/2817))
* [flake8-docstrings](https://pypi.org/project/flake8-docstrings/)
* [flake8-eradicate](https://pypi.org/project/flake8-eradicate/)
* [flake8-errmsg](https://pypi.org/project/flake8-errmsg/)
Expand Down Expand Up @@ -1820,6 +1832,7 @@ Today, Ruff can be used to replace Flake8 when used with any of the following pl
* [flake8-comprehensions](https://pypi.org/project/flake8-comprehensions/)
* [flake8-datetimez](https://pypi.org/project/flake8-datetimez/)
* [flake8-debugger](https://pypi.org/project/flake8-debugger/)
* [flake8-django](https://pypi.org/project/flake8-django/) ([#2817](https://github.com/charliermarsh/ruff/issues/2817))
* [flake8-docstrings](https://pypi.org/project/flake8-docstrings/)
* [flake8-eradicate](https://pypi.org/project/flake8-eradicate/)
* [flake8-errmsg](https://pypi.org/project/flake8-errmsg/)
Expand Down
39 changes: 39 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_django/DJ001.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from django.db.models import Model as DjangoModel
from django.db import models
from django.db.models import CharField as SmthCharField


class IncorrectModel(models.Model):
charfield = models.CharField(max_length=255, null=True)
textfield = models.TextField(max_length=255, null=True)
slugfield = models.SlugField(max_length=255, null=True)
emailfield = models.EmailField(max_length=255, null=True)
filepathfield = models.FilePathField(max_length=255, null=True)
urlfield = models.URLField(max_length=255, null=True)


class IncorrectModelWithAliasedBase(DjangoModel):
charfield = DjangoModel.CharField(max_length=255, null=True)
textfield = SmthCharField(max_length=255, null=True)
slugfield = models.SlugField(max_length=255, null=True)
emailfield = models.EmailField(max_length=255, null=True)
filepathfield = models.FilePathField(max_length=255, null=True)
urlfield = models.URLField(max_length=255, null=True)


class CorrectModel(models.Model):
charfield = models.CharField(max_length=255, null=False, blank=True)
textfield = models.TextField(max_length=255, null=False, blank=True)
slugfield = models.SlugField(max_length=255, null=False, blank=True)
emailfield = models.EmailField(max_length=255, null=False, blank=True)
filepathfield = models.FilePathField(max_length=255, null=False, blank=True)
urlfield = models.URLField(max_length=255, null=False, blank=True)

charfieldu = models.CharField(max_length=255, null=True, blank=True, unique=True)
textfieldu = models.TextField(max_length=255, null=True, blank=True, unique=True)
slugfieldu = models.SlugField(max_length=255, null=True, blank=True, unique=True)
emailfieldu = models.EmailField(max_length=255, null=True, blank=True, unique=True)
filepathfieldu = models.FilePathField(
max_length=255, null=True, blank=True, unique=True
)
urlfieldu = models.URLField(max_length=255, null=True, blank=True, unique=True)
167 changes: 167 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_django/DJ008.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
from django.db import models
from django.db.models import Model


# Models without __str__
class TestModel1(models.Model):
new_field = models.CharField(max_length=10)

class Meta:
verbose_name = "test model"
verbose_name_plural = "test models"

@property
def my_brand_new_property(self):
return 1

def my_beautiful_method(self):
return 2


class TestModel2(Model):
new_field = models.CharField(max_length=10)

class Meta:
verbose_name = "test model"
verbose_name_plural = "test models"

@property
def my_brand_new_property(self):
return 1

def my_beautiful_method(self):
return 2


class TestModel3(Model):
new_field = models.CharField(max_length=10)

class Meta:
abstract = False

@property
def my_brand_new_property(self):
return 1

def my_beautiful_method(self):
return 2


# Models with __str__
class TestModel4(Model):
new_field = models.CharField(max_length=10)

class Meta:
verbose_name = "test model"
verbose_name_plural = "test models"

def __str__(self):
return self.new_field

@property
def my_brand_new_property(self):
return 1

def my_beautiful_method(self):
return 2


class TestModel5(models.Model):
new_field = models.CharField(max_length=10)

class Meta:
verbose_name = "test model"
verbose_name_plural = "test models"

def __str__(self):
return self.new_field

@property
def my_brand_new_property(self):
return 1

def my_beautiful_method(self):
return 2


# Abstract models without str
class AbstractTestModel1(models.Model):
new_field = models.CharField(max_length=10)

class Meta:
abstract = True

@property
def my_brand_new_property(self):
return 1

def my_beautiful_method(self):
return 2


class AbstractTestModel2(Model):
new_field = models.CharField(max_length=10)

class Meta:
abstract = True

@property
def my_brand_new_property(self):
return 1

def my_beautiful_method(self):
return 2


# Abstract models with __str__


class AbstractTestModel3(Model):
new_field = models.CharField(max_length=10)

class Meta:
abstract = True

def __str__(self):
return self.new_field

@property
def my_brand_new_property(self):
return 1

def my_beautiful_method(self):
return 2


class AbstractTestModel4(models.Model):
new_field = models.CharField(max_length=10)

class Meta:
abstract = True

def __str__(self):
return self.new_field

@property
def my_brand_new_property(self):
return 1

def my_beautiful_method(self):
return 2


class AbstractTestModel5(models.Model):
new_field = models.CharField(max_length=10)

class Meta:
abstract = False

def __str__(self):
return self.new_field

@property
def my_brand_new_property(self):
return 1

def my_beautiful_method(self):
return 2
17 changes: 17 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_django/DJ013.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import MyModel

test_decorator = lambda func: lambda *args, **kwargs: func(*args, **kwargs)


@receiver(pre_save, sender=MyModel)
@test_decorator
def correct_pre_save_handler():
pass


@test_decorator
@receiver(pre_save, sender=MyModel)
def incorrect_pre_save_handler():
pass
28 changes: 25 additions & 3 deletions crates/ruff/src/checkers/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ use crate::registry::{Diagnostic, Rule};
use crate::rules::{
flake8_2020, flake8_annotations, flake8_bandit, flake8_blind_except, flake8_boolean_trap,
flake8_bugbear, flake8_builtins, flake8_comprehensions, flake8_datetimez, flake8_debugger,
flake8_errmsg, flake8_implicit_str_concat, flake8_import_conventions, flake8_logging_format,
flake8_pie, flake8_print, flake8_pyi, flake8_pytest_style, flake8_raise, flake8_return,
flake8_self, flake8_simplify, flake8_tidy_imports, flake8_type_checking,
flake8_django, flake8_errmsg, flake8_implicit_str_concat, flake8_import_conventions,
flake8_logging_format, flake8_pie, flake8_print, flake8_pyi, flake8_pytest_style, flake8_raise,
flake8_return, flake8_self, flake8_simplify, flake8_tidy_imports, flake8_type_checking,
flake8_unused_arguments, flake8_use_pathlib, mccabe, pandas_vet, pep8_naming, pycodestyle,
pydocstyle, pyflakes, pygrep_hooks, pylint, pyupgrade, ruff, tryceratops,
};
Expand Down Expand Up @@ -464,6 +464,15 @@ where
body,
..
} => {
if self.settings.rules.enabled(&Rule::ReceiverDecoratorChecker) {
if let Some(diagnostic) =
flake8_django::rules::receiver_decorator_checker(decorator_list, |expr| {
self.resolve_call_path(expr)
})
{
self.diagnostics.push(diagnostic);
}
}
if self.settings.rules.enabled(&Rule::AmbiguousFunctionName) {
if let Some(diagnostic) =
pycodestyle::rules::ambiguous_function_name(name, || {
Expand Down Expand Up @@ -771,6 +780,19 @@ where
decorator_list,
body,
} => {
if self.settings.rules.enabled(&Rule::ModelStringFieldNullable) {
self.diagnostics
.extend(flake8_django::rules::model_string_field_nullable(
self, bases, body,
));
}
if self.settings.rules.enabled(&Rule::ModelDunderStr) {
if let Some(diagnostic) =
flake8_django::rules::model_dunder_str(self, bases, body, stmt)
{
self.diagnostics.push(diagnostic);
}
}
if self.settings.rules.enabled(&Rule::UselessObjectInheritance) {
pyupgrade::rules::useless_object_inheritance(self, stmt, name, bases, keywords);
}
Expand Down
7 changes: 7 additions & 0 deletions crates/ruff/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,10 @@ ruff_macros::define_rule_mapping!(
RUF004 => rules::ruff::rules::KeywordArgumentBeforeStarArgument,
RUF005 => rules::ruff::rules::UnpackInsteadOfConcatenatingToCollectionLiteral,
RUF100 => rules::ruff::rules::UnusedNOQA,
// flake8-django
DJ001 => rules::flake8_django::rules::ModelStringFieldNullable,
DJ008 => rules::flake8_django::rules::ModelDunderStr,
DJ013 => rules::flake8_django::rules::ReceiverDecoratorChecker,
);

#[derive(EnumIter, Debug, PartialEq, Eq, RuleNamespace)]
Expand Down Expand Up @@ -612,6 +616,9 @@ pub enum Linter {
/// [flake8-debugger](https://pypi.org/project/flake8-debugger/)
#[prefix = "T10"]
Flake8Debugger,
/// [flake8-django](https://pypi.org/project/flake8-django/)
#[prefix = "DJ"]
Flake8Django,
/// [flake8-errmsg](https://pypi.org/project/flake8-errmsg/)
#[prefix = "EM"]
Flake8ErrMsg,
Expand Down
27 changes: 27 additions & 0 deletions crates/ruff/src/rules/flake8_django/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//! Rules from [django-flake8](https://pypi.org/project/flake8-django/)
pub(crate) mod rules;

#[cfg(test)]
mod tests {
use std::path::Path;

use anyhow::Result;
use test_case::test_case;

use crate::registry::Rule;
use crate::test::test_path;
use crate::{assert_yaml_snapshot, settings};

#[test_case(Rule::ModelStringFieldNullable, Path::new("DJ001.py"); "DJ001")]
#[test_case(Rule::ModelDunderStr, Path::new("DJ008.py"); "DJ008")]
#[test_case(Rule::ReceiverDecoratorChecker, Path::new("DJ013.py"); "DJ013")]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.code(), path.to_string_lossy());
let diagnostics = test_path(
Path::new("flake8_django").join(path).as_path(),
&settings::Settings::for_rule(rule_code),
)?;
assert_yaml_snapshot!(snapshot, diagnostics);
Ok(())
}
}
20 changes: 20 additions & 0 deletions crates/ruff/src/rules/flake8_django/rules/helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use rustpython_parser::ast::Expr;

use crate::checkers::ast::Checker;

/// Return `true` if a Python class appears to be a Django model based on a base class.
pub fn is_model(checker: &Checker, base: &Expr) -> bool {
checker.resolve_call_path(base).map_or(false, |call_path| {
call_path.as_slice() == ["django", "db", "models", "Model"]
})
}

pub fn get_model_field_name<'a>(checker: &'a Checker, expr: &'a Expr) -> Option<&'a str> {
checker.resolve_call_path(expr).and_then(|call_path| {
let call_path = call_path.as_slice();
if !call_path.starts_with(&["django", "db", "models"]) {
return None;
}
call_path.last().copied()
})
}
8 changes: 8 additions & 0 deletions crates/ruff/src/rules/flake8_django/rules/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
mod helpers;
mod model_dunder_str;
mod model_string_field_nullable;
mod receiver_decorator_checker;

pub use model_dunder_str::{model_dunder_str, ModelDunderStr};
pub use model_string_field_nullable::{model_string_field_nullable, ModelStringFieldNullable};
pub use receiver_decorator_checker::{receiver_decorator_checker, ReceiverDecoratorChecker};
Loading