-
Notifications
You must be signed in to change notification settings - Fork 897
/
assignment_to_os_environ.rs
72 lines (67 loc) · 2 KB
/
assignment_to_os_environ.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
use ruff_python_ast::{self as ast, Expr};
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for assignments to `os.environ`.
///
/// ## Why is this bad?
/// In Python, `os.environ` is a mapping that represents the environment of the
/// current process.
///
/// However, reassigning to `os.environ` does not clear the environment. Instead,
/// it merely updates the `os.environ` for the current process. This can lead to
/// unexpected behavior, especially when running the program in a subprocess.
///
/// Instead, use `os.environ.clear()` to clear the environment, or use the
/// `env` argument of `subprocess.Popen` to pass a custom environment to
/// a subprocess.
///
/// ## Example
/// ```python
/// import os
///
/// os.environ = {"foo": "bar"}
/// ```
///
/// Use instead:
/// ```python
/// import os
///
/// os.environ.clear()
/// os.environ["foo"] = "bar"
/// ```
///
/// ## References
/// - [Python documentation: `os.environ`](https://docs.python.org/3/library/os.html#os.environ)
/// - [Python documentation: `subprocess.Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)
#[violation]
pub struct AssignmentToOsEnviron;
impl Violation for AssignmentToOsEnviron {
#[derive_message_formats]
fn message(&self) -> String {
format!("Assigning to `os.environ` doesn't clear the environment")
}
}
/// B003
pub(crate) fn assignment_to_os_environ(checker: &mut Checker, targets: &[Expr]) {
let [target] = targets else {
return;
};
let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = target else {
return;
};
if attr != "environ" {
return;
}
let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() else {
return;
};
if id.as_str() != "os" {
return;
}
checker
.diagnostics
.push(Diagnostic::new(AssignmentToOsEnviron, target.range()));
}