[flake8-bugbear] Avoid adding default initializers to stubs (`B006… · astral-sh/ruff@36bc725 (original) (raw)

`@@ -2,7 +2,7 @@ use ast::call_path::{from_qualified_name, CallPath};

`

2

2

`use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};

`

3

3

`use ruff_macros::{derive_message_formats, violation};

`

4

4

`use ruff_python_ast::helpers::is_docstring_stmt;

`

5

``

`-

use ruff_python_ast::{self as ast, Expr, Parameter, ParameterWithDefault};

`

``

5

`+

use ruff_python_ast::{self as ast, Expr, Parameter, ParameterWithDefault, Stmt};

`

6

6

`use ruff_python_codegen::{Generator, Stylist};

`

7

7

`use ruff_python_index::Indexer;

`

8

8

`use ruff_python_semantic::analyze::typing::{is_immutable_annotation, is_mutable_expr};

`

`@@ -152,6 +152,11 @@ fn move_initialization(

`

152

152

`` // Set the default argument value to None.

``

153

153

`let default_edit = Edit::range_replacement("None".to_string(), default.range());

`

154

154

``

``

155

`+

// If the function is a stub, this is the only necessary edit.

`

``

156

`+

if is_stub(function_def) {

`

``

157

`+

return Some(Fix::unsafe_edit(default_edit));

`

``

158

`+

}

`

``

159

+

155

160

`` // Add an if, to set the argument to its original value if still None.

``

156

161

`let mut content = String::new();

`

157

162

` content.push_str(&format!("if {} is None:", parameter.name.as_str()));

`

`@@ -204,3 +209,20 @@ fn move_initialization(

`

204

209

`let initialization_edit = Edit::insertion(content, pos);

`

205

210

`Some(Fix::unsafe_edits(default_edit, [initialization_edit]))

`

206

211

`}

`

``

212

+

``

213

`` +

/// Returns true if a function has an empty body, and is therefore a stub.

``

``

214

`+

///

`

``

215

`` +

/// A function body is considered to be empty if it contains only pass statements, ... literals,

``

``

216

`+

/// and docstrings.

`

``

217

`+

fn is_stub(function_def: &ast::StmtFunctionDef) -> bool {

`

``

218

`+

function_def.body.iter().all(|stmt| match stmt {

`

``

219

`+

Stmt::Pass(_) => true,

`

``

220

`+

Stmt::Expr(ast::StmtExpr { value, range: _ }) => {

`

``

221

`+

matches!(

`

``

222

`+

value.as_ref(),

`

``

223

`+

Expr::StringLiteral() | Expr::EllipsisLiteral()

`

``

224

`+

)

`

``

225

`+

}

`

``

226

`+

_ => false,

`

``

227

`+

})

`

``

228

`+

}

`