-
Notifications
You must be signed in to change notification settings - Fork 903
/
missing_newline_at_end_of_file.rs
62 lines (53 loc) · 1.5 KB
/
missing_newline_at_end_of_file.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
use ruff_text_size::{TextLen, TextRange};
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_codegen::Stylist;
use ruff_source_file::Locator;
/// ## What it does
/// Checks for files missing a new line at the end of the file.
///
/// ## Why is this bad?
/// Trailing blank lines are superfluous.
/// However the last line should end with a new line.
///
/// ## Example
/// ```python
/// spam(1)
/// ```
///
/// Use instead:
/// ```python
/// spam(1)\n
/// ```
#[violation]
pub struct MissingNewlineAtEndOfFile;
impl AlwaysFixableViolation for MissingNewlineAtEndOfFile {
#[derive_message_formats]
fn message(&self) -> String {
format!("No newline at end of file")
}
fn fix_title(&self) -> String {
"Add trailing newline".to_string()
}
}
/// W292
pub(crate) fn no_newline_at_end_of_file(
locator: &Locator,
stylist: &Stylist,
) -> Option<Diagnostic> {
let source = locator.contents();
// Ignore empty and BOM only files.
if source.is_empty() || source == "\u{feff}" {
return None;
}
if !source.ends_with(['\n', '\r']) {
let range = TextRange::empty(locator.contents().text_len());
let mut diagnostic = Diagnostic::new(MissingNewlineAtEndOfFile, range);
diagnostic.set_fix(Fix::safe_edit(Edit::insertion(
stylist.line_ending().to_string(),
range.start(),
)));
return Some(diagnostic);
}
None
}